diff --git a/GL/alloc/alloc.c b/GL/alloc/alloc.c index 3dfce8e..15207c1 100644 --- a/GL/alloc/alloc.c +++ b/GL/alloc/alloc.c @@ -516,29 +516,27 @@ size_t alloc_count_continuous(void* pool) { (void) pool; size_t largest_block = 0; - size_t current_block = 0; + size_t free_bits = 0; for(size_t i = 0; i < pool_header.block_count; ++i) { uint8_t t = pool_header.block_usage[i]; - if(!t) { - current_block += 2048; - } else { - for(int i = 7; i >= 0; --i) { - bool bitset = (t & (1 << i)); - if(bitset) { - current_block += (7 - i) * 256; - if(largest_block < current_block) { - largest_block = current_block; - current_block = 0; - } + for(int i = 7; i >= 0; --i) { + bool bitset = (t & (1 << i)); + if(!bitset) { + ++free_bits; + } else { + free_bits = 0; + size_t free_size = free_bits * 256; + if(free_size > largest_block) { + largest_block = free_size; } } } } - if(largest_block < current_block) { - largest_block = current_block; + if(free_bits && (free_bits * 256) > largest_block) { + largest_block = (free_bits * 256); } return largest_block; diff --git a/tests/test_allocator.h b/tests/test_allocator.h index 5967983..8aa146f 100644 --- a/tests/test_allocator.h +++ b/tests/test_allocator.h @@ -39,6 +39,42 @@ public: self->defrag_moves.push_back(std::make_pair(src, dst)); } + void test_count_free() { + alloc_init(pool, POOL_SIZE); + + assert_equal(alloc_count_free(pool), POOL_SIZE); + + void* a1 = alloc_malloc(pool, 2048); + assert_equal(alloc_count_free(pool), POOL_SIZE - 2048); + + void* a2 = alloc_malloc(pool, 2048); + assert_equal(alloc_count_free(pool), POOL_SIZE - 4096); + + alloc_free(pool, a1); + assert_equal(alloc_count_free(pool), POOL_SIZE - 2048); + + alloc_free(pool, a2); + assert_equal(alloc_count_free(pool), POOL_SIZE); + } + + void test_count_contiguous() { + alloc_init(pool, POOL_SIZE); + + assert_equal(alloc_count_continuous(pool), POOL_SIZE); + + void* a1 = alloc_malloc(pool, 2048); + assert_equal(alloc_count_continuous(pool), POOL_SIZE - 2048); + + void* a2 = alloc_malloc(pool, 2048); + assert_equal(alloc_count_continuous(pool), POOL_SIZE - 4096); + + alloc_free(pool, a1); + assert_equal(alloc_count_continuous(pool), POOL_SIZE - 4096); + + alloc_free(pool, a2); + assert_equal(alloc_count_continuous(pool), POOL_SIZE); + } + void test_defrag() { alloc_init(pool, POOL_SIZE);