From 470a25323ca89ffa3b0b697aeddcf184d12a1382 Mon Sep 17 00:00:00 2001
From: 3gg <3gg@shellblade.net>
Date: Mon, 23 Jan 2023 18:32:49 -0800
Subject: Update listpool's interface to be on par with mempool's.

---
 listpool/include/listpool.h | 32 ++++++++++++++++++++++++++------
 1 file changed, 26 insertions(+), 6 deletions(-)

(limited to 'listpool/include')

diff --git a/listpool/include/listpool.h b/listpool/include/listpool.h
index 1711449..85a3b27 100644
--- a/listpool/include/listpool.h
+++ b/listpool/include/listpool.h
@@ -45,13 +45,26 @@
     });                             \
   }
 
+/// Return the ith block.
+/// The block must have been allocated.
+#define listpool_get_block(POOL, INDEX) \
+  ((typeof((POOL)->blocks[0])*)listpool_get_block_(&(POOL)->pool, INDEX))
+
+/// Get the index to the given block.
+#define listpool_get_block_index(POOL, BLOCK_PTR) \
+  listpool_get_block_index_(&(POOL)->pool, BLOCK_PTR)
+
 /// Iterate over the used items of the pool.
-#define listpool_foreach(POOL, ITER, BODY)                    \
-  for (list* it_ = (POOL)->pool.used; it_; it_ = it_->next) { \
-    typeof((POOL)->blocks[0])* ITER =                         \
-        &(POOL)->blocks[it_ - (POOL)->pool.nodes];            \
-    (void)ITER;                                               \
-    BODY;                                                     \
+///
+/// The caller can use 'i' as the index of the current block.
+///
+/// It is valid to mempool_free() the object at each step of the iteration.
+#define listpool_foreach(POOL, ITER, BODY)                      \
+  for (list* it_ = (POOL)->pool.used; it_; it_ = it_->next) {   \
+    const size_t               i    = it_ - (POOL)->pool.nodes; \
+    typeof((POOL)->blocks[0])* ITER = &(POOL)->blocks[i];       \
+    (void)ITER;                                                 \
+    BODY;                                                       \
   }
 
 typedef struct listpool {
@@ -78,3 +91,10 @@ void* listpool_alloc_(listpool* pool);
 /// Free the block.
 /// The block pointer is conveniently set to 0.
 void listpool_free_(listpool* pool, void** block_ptr);
+
+/// Return the ith block.
+/// The block must have been allocated.
+void* listpool_get_block_(const listpool*, size_t block_index);
+
+/// Get the index to the given block.
+size_t listpool_get_block_index_(const listpool*, const void* block);
-- 
cgit v1.2.3