auto_buffer *ab_new(size_t unit_size){ auto_buffer *ab=mem_malloc(sizeof(auto_buffer)); ab->head=_new_block(unit_size,AB_BLOCK_SIZE,NULL); return ab; }
struct mempool *mempool_new() { struct mempool *pool; pool = xcalloc(1, sizeof(*pool)); pool->blocks = _new_block(pool, MEMPOOL_BLOCKSIZE); pool->n_blocks++; return pool; }
void *ab_obj_malloc(auto_buffer *ab){ void *obj=_ab_first_available(ab->head); if (!obj){ // no free, create new block ab->head= _new_block(ab->head->obj_size - sizeof(int),AB_BLOCK_SIZE,ab->head); obj=ab->head->buffer; *((int*)obj)=1; return obj+sizeof(int);// 跳开前面的标记 } return obj; }
/* * malloc bytes with aligned address */ char *mempool_alloc_aligned(struct mempool *pool, uint32_t bytes) { int mod; int slob; int align; size_t ptr; char *base; char *results; uint32_t needed; struct mempool_block *blk; align = ((sizeof(void*) > 8) ? sizeof(void*) : 8); /* align must power of 2 */ nassert((align & (align - 1)) == 0); blk = pool->blocks; base = (blk->memory + (blk->size - blk->remaining)); ptr = (size_t)base; mod = ptr & (align - 1); slob = ((mod == 0) ? 0 : (align - mod)); needed = (bytes + slob); if (blk->remaining >= needed) { results = (base + slob); blk->remaining -= needed; pool->memory_used += needed; } else { blk = _new_block(pool, bytes); blk->next = pool->blocks; pool->blocks = blk; pool->n_blocks++; blk->remaining -= bytes; pool->memory_used += bytes; results = blk->memory; } return results; }