Skip to content

Commit bdfa7a2

Browse files
committed
Merge branch 'rs/mem-pool-improvements'
MemPool allocator fixes. * rs/mem-pool-improvements: mem-pool: simplify alignment calculation mem-pool: fix big allocations
2 parents 8a48cd4 + c61740d commit bdfa7a2

File tree

3 files changed

+36
-6
lines changed

3 files changed

+36
-6
lines changed

Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1340,6 +1340,7 @@ THIRD_PARTY_SOURCES += sha1collisiondetection/%
13401340
THIRD_PARTY_SOURCES += sha1dc/%
13411341

13421342
UNIT_TEST_PROGRAMS += t-basic
1343+
UNIT_TEST_PROGRAMS += t-mem-pool
13431344
UNIT_TEST_PROGRAMS += t-strbuf
13441345
UNIT_TEST_PROGS = $(patsubst %,$(UNIT_TEST_BIN)/%$X,$(UNIT_TEST_PROGRAMS))
13451346
UNIT_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(UNIT_TEST_PROGRAMS))

mem-pool.c

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -89,19 +89,17 @@ void *mem_pool_alloc(struct mem_pool *pool, size_t len)
8989
struct mp_block *p = NULL;
9090
void *r;
9191

92-
/* round up to a 'GIT_MAX_ALIGNMENT' alignment */
93-
if (len & (GIT_MAX_ALIGNMENT - 1))
94-
len += GIT_MAX_ALIGNMENT - (len & (GIT_MAX_ALIGNMENT - 1));
92+
len = DIV_ROUND_UP(len, GIT_MAX_ALIGNMENT) * GIT_MAX_ALIGNMENT;
9593

9694
if (pool->mp_block &&
9795
pool->mp_block->end - pool->mp_block->next_free >= len)
9896
p = pool->mp_block;
9997

10098
if (!p) {
10199
if (len >= (pool->block_alloc / 2))
102-
return mem_pool_alloc_block(pool, len, pool->mp_block);
103-
104-
p = mem_pool_alloc_block(pool, pool->block_alloc, NULL);
100+
p = mem_pool_alloc_block(pool, len, pool->mp_block);
101+
else
102+
p = mem_pool_alloc_block(pool, pool->block_alloc, NULL);
105103
}
106104

107105
r = p->next_free;

t/unit-tests/t-mem-pool.c

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include "test-lib.h"
2+
#include "mem-pool.h"
3+
4+
static void setup_static(void (*f)(struct mem_pool *), size_t block_alloc)
5+
{
6+
struct mem_pool pool = { .block_alloc = block_alloc };
7+
f(&pool);
8+
mem_pool_discard(&pool, 0);
9+
}
10+
11+
static void t_calloc_100(struct mem_pool *pool)
12+
{
13+
size_t size = 100;
14+
char *buffer = mem_pool_calloc(pool, 1, size);
15+
for (size_t i = 0; i < size; i++)
16+
check_int(buffer[i], ==, 0);
17+
if (!check(pool->mp_block != NULL))
18+
return;
19+
check(pool->mp_block->next_free != NULL);
20+
check(pool->mp_block->end != NULL);
21+
}
22+
23+
int cmd_main(int argc, const char **argv)
24+
{
25+
TEST(setup_static(t_calloc_100, 1024 * 1024),
26+
"mem_pool_calloc returns 100 zeroed bytes with big block");
27+
TEST(setup_static(t_calloc_100, 1),
28+
"mem_pool_calloc returns 100 zeroed bytes with tiny block");
29+
30+
return test_done();
31+
}

0 commit comments

Comments
 (0)