From f5b77325c44649bb92fa379b7df77c275f3925dc Mon Sep 17 00:00:00 2001
From: 3gg <3gg@shellblade.net>
Date: Mon, 23 Jan 2023 17:42:27 -0800
Subject: Clear block info on init and simplify next free block search.

---
 mempool/src/mempool.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

(limited to 'mempool/src')

diff --git a/mempool/src/mempool.c b/mempool/src/mempool.c
index 5772883..b4693a5 100644
--- a/mempool/src/mempool.c
+++ b/mempool/src/mempool.c
@@ -18,6 +18,7 @@ void mempool_make_(
   pool->block_info       = block_info;
   pool->blocks           = blocks;
   memset(blocks, 0, num_blocks * block_size_bytes);
+  memset(block_info, 0, num_blocks * sizeof(BlockInfo));
 }
 
 void* mempool_alloc_(mempool* pool) {
@@ -31,9 +32,14 @@ void* mempool_alloc_(mempool* pool) {
   void* block = &pool->blocks[pool->next_free_block * pool->block_size_bytes];
   pool->block_info[pool->next_free_block].used = true;
 
-  // Search for the next free block. If it does not exist, flag the pool full.
+  // Search for the next free block. If it does not exist, flag the pool
+  // full.
+  //
+  // The search starts near the current free block, where we might be more
+  // likely to find free blocks. The search starts with i=1 since we only
+  // need to test the other N-1 blocks in the pool.
   pool->full = true;
-  for (size_t i = 1; i < pool->num_blocks && i != 0; i++) {
+  for (size_t i = 1; i < pool->num_blocks; i++) {
     pool->next_free_block = (pool->next_free_block + 1) % pool->num_blocks;
     if (!pool->block_info[pool->next_free_block].used) {
       pool->full = false;
-- 
cgit v1.2.3