]>
Commit | Line | Data |
---|---|---|
ad3c9f2a A |
1 | /* |
2 | tre-mem.h - TRE memory allocator interface | |
3 | ||
4 | This software is released under a BSD-style license. | |
5 | See the file LICENSE for details and copyright. | |
6 | ||
7 | */ | |
8 | ||
9 | #ifndef TRE_MEM_H | |
10 | #define TRE_MEM_H 1 | |
11 | ||
12 | #include <stdlib.h> | |
13 | ||
14 | #define TRE_MEM_BLOCK_SIZE 1024 | |
15 | ||
16 | typedef struct tre_list { | |
17 | void *data; | |
18 | struct tre_list *next; | |
19 | } tre_list_t; | |
20 | ||
21 | typedef struct tre_mem_struct { | |
22 | tre_list_t *blocks; | |
23 | tre_list_t *current; | |
24 | char *ptr; | |
25 | size_t n; | |
26 | int failed; | |
27 | void **provided; | |
28 | } *tre_mem_t; | |
29 | ||
30 | ||
31 | __private_extern__ tre_mem_t tre_mem_new_impl(int provided, | |
32 | void *provided_block); | |
33 | __private_extern__ void *tre_mem_alloc_impl(tre_mem_t mem, int provided, | |
34 | void *provided_block, | |
35 | int zero, size_t size); | |
36 | ||
37 | /* Returns a new memory allocator or NULL if out of memory. */ | |
38 | #define tre_mem_new() tre_mem_new_impl(0, NULL) | |
39 | ||
40 | /* Allocates a block of `size' bytes from `mem'. Returns a pointer to the | |
41 | allocated block or NULL if an underlying malloc() failed. */ | |
42 | #define tre_mem_alloc(mem, size) tre_mem_alloc_impl(mem, 0, NULL, 0, size) | |
43 | ||
44 | /* Allocates a block of `size' bytes from `mem'. Returns a pointer to the | |
45 | allocated block or NULL if an underlying malloc() failed. The memory | |
46 | is set to zero. */ | |
47 | #define tre_mem_calloc(mem, size) tre_mem_alloc_impl(mem, 0, NULL, 1, size) | |
48 | ||
49 | #ifdef TRE_USE_ALLOCA | |
50 | /* alloca() versions. Like above, but memory is allocated with alloca() | |
51 | instead of malloc(). */ | |
52 | ||
53 | #define tre_mem_newa() \ | |
54 | tre_mem_new_impl(1, alloca(sizeof(struct tre_mem_struct))) | |
55 | ||
56 | #define tre_mem_alloca(mem, size) \ | |
57 | ((mem)->n >= (size) \ | |
58 | ? tre_mem_alloc_impl((mem), 1, NULL, 0, (size)) \ | |
59 | : tre_mem_alloc_impl((mem), 1, alloca(TRE_MEM_BLOCK_SIZE), 0, (size))) | |
60 | #endif /* TRE_USE_ALLOCA */ | |
61 | ||
62 | ||
63 | /* Frees the memory allocator and all memory allocated with it. */ | |
64 | __private_extern__ void tre_mem_destroy(tre_mem_t mem); | |
65 | ||
66 | #endif /* TRE_MEM_H */ | |
67 | ||
68 | /* EOF */ |