1 /*
2 * Copyright (c) 2001-2009 Ville Laurikari <vl@iki.fi>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 *
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 /*
30 tre-mem.h - TRE memory allocator interface
31 */
32
33 #ifndef _TRE_MEM_H
34 #define _TRE_MEM_H
35
36 #include <stdlib.h>
37
38 #define TRE_MEM_BLOCK_SIZE 1024
39
40 typedef struct tre_list {
41 void *data;
42 struct tre_list *next;
43 } tre_list_t;
44
45 typedef struct tre_mem_struct {
46 tre_list_t *blocks;
47 tre_list_t *current;
48 char *ptr;
49 size_t n;
50 int failed;
51 void **provided;
52 } *tre_mem_t;
53
54 tre_mem_t tre_mem_new_impl(int provided, void *provided_block);
55 void *tre_mem_alloc_impl(tre_mem_t mem, int provided, void *provided_block,
56 int zero, size_t size);
57
58 /* Returns a new memory allocator or NULL if out of memory. */
59 #define tre_mem_new() tre_mem_new_impl(0, NULL)
60
61 /* Allocates a block of `size' bytes from `mem'. Returns a pointer to the
62 allocated block or NULL if an underlying malloc() failed. */
63 #define tre_mem_alloc(mem, size) tre_mem_alloc_impl(mem, 0, NULL, 0, size)
64
65 /* Allocates a block of `size' bytes from `mem'. Returns a pointer to the
66 allocated block or NULL if an underlying malloc() failed. The memory
67 is set to zero. */
68 #define tre_mem_calloc(mem, size) tre_mem_alloc_impl(mem, 0, NULL, 1, size)
69
70 /* Frees the memory allocator and all memory allocated with it. */
71 void tre_mem_destroy(tre_mem_t mem);
72
73 #endif /* _TRE_MEM_H */