aboutsummaryrefslogtreecommitdiff
path: root/listpool/src/listpool.c
diff options
context:
space:
mode:
Diffstat (limited to 'listpool/src/listpool.c')
-rw-r--r--listpool/src/listpool.c92
1 files changed, 0 insertions, 92 deletions
diff --git a/listpool/src/listpool.c b/listpool/src/listpool.c
deleted file mode 100644
index 758062c..0000000
--- a/listpool/src/listpool.c
+++ /dev/null
@@ -1,92 +0,0 @@
1#include "listpool.h"
2
3#include <string.h>
4
5void listpool_make_(
6 listpool* pool, list* nodes, void* blocks, size_t num_blocks,
7 size_t block_size_bytes) {
8 assert(pool);
9 pool->block_size_bytes = block_size_bytes;
10 pool->num_blocks = num_blocks;
11 pool->free = &nodes[0];
12 pool->used = 0;
13 pool->nodes = nodes;
14 pool->blocks = blocks;
15 list_make(nodes, num_blocks);
16 memset(blocks, 0, num_blocks * block_size_bytes);
17}
18
19void* listpool_alloc_(listpool* pool) {
20 assert(pool);
21 if (!pool->free) {
22 return 0;
23 }
24
25 const size_t index = pool->free - pool->nodes;
26 assert(index < pool->num_blocks);
27
28 list* free = pool->free;
29 pool->free = pool->free->next;
30
31 // pool->used is always the head of the used list, so prepend the new item to
32 // the list.
33 list* new_used = free;
34 new_used->prev = 0;
35 new_used->next = pool->used;
36 if (pool->used) {
37 pool->used->prev = new_used;
38 }
39 pool->used = new_used;
40
41 return pool->blocks + index * pool->block_size_bytes;
42}
43
44void listpool_free_(listpool* pool, void** block_ptr) {
45 assert(pool);
46 assert(block_ptr);
47
48 memset(*block_ptr, 0, pool->block_size_bytes);
49
50 const size_t index =
51 ((uint8_t*)*block_ptr - pool->blocks) / pool->block_size_bytes;
52 assert(index < pool->num_blocks);
53
54 list* item = &pool->nodes[index];
55
56 // We must remove the item from the used list first.
57 if (item->prev) {
58 item->prev->next = item->next;
59 }
60 if (item->next) {
61 item->next->prev = item->prev;
62 }
63 if (item == pool->used) {
64 pool->used = item->next;
65 }
66
67 // pool->free is always the head of the free list, so prepend the new item to
68 // the list. The item is now free to wire after removing it from the used
69 // list.
70 if (!pool->free) {
71 pool->free = item;
72 } else {
73 item->next = pool->free;
74 pool->free->prev = item;
75 pool->free = item;
76 }
77
78 *block_ptr = 0;
79}
80
81void* listpool_get_block_(const listpool* pool, size_t block_index) {
82 assert(pool);
83 assert(block_index < pool->num_blocks);
84 return pool->blocks + block_index * pool->block_size_bytes;
85}
86
87size_t listpool_get_block_index_(const listpool* pool, const void* block) {
88 assert(pool);
89 const size_t block_byte_index = (const uint8_t*)block - pool->blocks;
90 assert(block_byte_index % pool->block_size_bytes == 0);
91 return block_byte_index / pool->block_size_bytes;
92}