tmem.h - iomenu - interactive terminal-based selection menu
(HTM) git clone git://bitreich.org/iomenu git://hg6vgqziawt5s4dj.onion/iomenu
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) Tags
(DIR) README
(DIR) LICENSE
---
tmem.h (2610B)
---
1 #ifndef MEM_H
2 #define MEM_H
3
4 /*
5 * Lightweight wrapper over malloc, that permit to define a memory pool of
6 * multiple buffers, and free them all at once.
7 *
8 * *──────────┐
9 * │ mem_pool │
10 * ├──────────┤
11 * │*head │
12 * └┬─────────┘
13 * v
14 * NULL< *───────────┐< >*───────────┐< >*───────────┐< >*───────────┐ >NULL
15 * \ │ mem_block │ \/ │ mem_block │ \/ │ mem_block │ \/ │ mem_block │ /
16 * \ ├───────────┤ /\ ├───────────┤ /\ ├───────────┤ /\ ├───────────┤ /
17 * `┤*prev *next├' `┤*prev *next├' `┤*prev *next├' `┤*prev *next├'
18 * │len │ │len │ │len │ │len │
19 * ├─┴─magic───┤ ├─┴─magic───┤ ├─┴─magic───┤ ├─┴─magic───┤
20 * │///////////│ │///////////│ │///////////│ │///////////│
21 * │///////////│ │///////////│ │///////////│ │///////////│
22 * │///////////│ │///////////│ │///////////│ └───────────┘
23 * └───────────┘ │///////////│ │///////////│
24 * │///////////│ └───────────┘
25 * └───────────┘
26 *
27 * This permits the type checker to still work on all operations while
28 * providing generic memory management functions for all types of data
29 * structures and keep track of each object's length.
30 */
31
32 #include <stddef.h>
33
34 #define MEM_BLOCK_MAGIC "\xcc\x68\x23\xd7\x9b\x7d\x39\xb9"
35
36 struct mem_pool {
37 struct mem_block *head;
38 };
39
40 struct mem_block {
41 struct mem_pool *pool;
42 struct mem_block *prev, *next;
43 size_t len;
44 char magic[8]; /* at the end to detect buffer underflow */
45 char buf[];
46 };
47
48 /** src/mem.c **/
49 void * mem_alloc(struct mem_pool *pool, size_t len);
50 int mem_resize(void **memp, size_t len);
51 int mem_grow(void **memp, size_t len);
52 int mem_shrink(void **memp, size_t len);
53 size_t mem_length(void *mem);
54 int mem_append(void **memp, void const *buf, size_t len);
55 int mem_read(void **memp, struct mem_pool *pool);
56 void mem_delete(void *mem);
57 void mem_free(struct mem_pool *pool);
58
59 #endif