1 /* Copyright (c) 2015 Ytai Ben-tsvi */
2 
3 #include <lib/pool.h>
4 #include <assert.h>
5 
pool_init(pool_t * pool,size_t object_size,size_t object_align,size_t object_count,void * storage)6 void pool_init(pool_t *pool,
7                size_t object_size,
8                size_t object_align,
9                size_t object_count,
10                void *storage) {
11     assert(pool);
12     assert(!object_count || storage);
13     assert((intptr_t) storage % POOL_STORAGE_ALIGN(object_size, object_align) == 0);
14 
15     size_t offset = 0;
16     for (size_t i = 0; i < object_count; ++i) {
17         pool_free(pool, (uint8_t *) storage + offset);
18         offset += POOL_PADDED_OBJECT_SIZE(object_size, object_align);
19     }
20 }
21 
pool_alloc(pool_t * pool)22 void *pool_alloc(pool_t *pool) {
23     assert(pool);
24 
25     void *result = pool->next_free;
26     if (!result) {
27         return NULL;
28     }
29     pool->next_free = *((void **) result);
30     return result;
31 }
32 
pool_free(pool_t * pool,void * object)33 void pool_free(pool_t *pool, void *object) {
34     assert(pool);
35     assert(object);
36 
37     *((void **) object) = pool->next_free;
38     pool->next_free = object;
39 }
40