aboutsummaryrefslogtreecommitdiff
path: root/memstack/include
diff options
context:
space:
mode:
Diffstat (limited to 'memstack/include')
-rw-r--r--memstack/include/memstack.h66
1 files changed, 66 insertions, 0 deletions
diff --git a/memstack/include/memstack.h b/memstack/include/memstack.h
new file mode 100644
index 0000000..93cd2e6
--- /dev/null
+++ b/memstack/include/memstack.h
@@ -0,0 +1,66 @@
1/*
2 * Stack-based allocator.
3 */
4#pragma once
5
6#include <stddef.h>
7#include <stdint.h>
8
9/// Stack-based allocator.
10typedef struct memstack {
11 size_t capacity; // Total size available.
12 uint8_t* base; // Base pointer to memory.
13 uint8_t* watermark; // Pointer to next free area of memory.
14 bool owned; // True if memory is owned by the memstack.
15 bool trap; // Whether to trap when allocating beyond capacity.
16} memstack;
17
18/// Create a stack-based allocator.
19///
20/// `stack` may be user-provided or null.
21/// - If null, the allocator malloc()s the memory for them.
22/// - If given, `stack` must be at least `capacity` bytes.
23///
24/// The memory is zeroed out for convenience.
25bool memstack_make(memstack*, size_t capacity, void* memory);
26
27/// Destroy the stack.
28///
29/// If the allocator owns the memory, then this function frees it.
30void memstack_del(memstack*);
31
32/// Clear the stack.
33void memstack_clear(memstack*);
34
35/// Return the top of the stack.
36size_t memstack_watermark(const memstack*);
37
38/// Set the top of the stack.
39void memstack_set_watermark(memstack*, size_t watermark);
40
41/// Allocate a new block.
42///
43/// Return null if the block does not fit in the remaining memory.
44///
45/// When there is no space left in the stack, allocation can either trap
46/// (default) or gracefully return null. Call mem_enable_traps() to toggle this
47/// behaviour.
48///
49/// Newly allocated blocks are conveniently zeroed out.
50void* memstack_alloc(memstack*, size_t bytes);
51
52/// Allocate a new aligned block.
53///
54/// An alignment of 0 is allowed for convenience and has the same effect as 1.
55///
56/// Has the same properties as memstack_alloc().
57void* memstack_alloc_aligned(memstack*, size_t bytes, size_t alignment);
58
59/// Return the stack's used size in bytes.
60size_t memstack_size(const memstack*);
61
62/// Return the stack's total capacity in bytes.
63size_t memstack_capacity(const memstack*);
64
65/// Set whether to trap when attempting to allocate beyond capacity.
66void memstack_enable_traps(memstack*, bool);