diff options
author | 3gg <3gg@shellblade.net> | 2025-07-01 09:34:22 -0700 |
---|---|---|
committer | 3gg <3gg@shellblade.net> | 2025-07-01 09:34:22 -0700 |
commit | f99204184c8b96f499f6e7efbffb8b6b4ea8c93f (patch) | |
tree | 0aff3a962693312352f1f026e70ad479ee4f4147 /memstack/include/memstack.h | |
parent | 53aa4355da4fdadd65d2758f9c2ce68b6c884502 (diff) |
Diffstat (limited to 'memstack/include/memstack.h')
-rw-r--r-- | memstack/include/memstack.h | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/memstack/include/memstack.h b/memstack/include/memstack.h new file mode 100644 index 0000000..9a8a7ee --- /dev/null +++ b/memstack/include/memstack.h | |||
@@ -0,0 +1,50 @@ | |||
1 | /* | ||
2 | * Stack-based allocator. | ||
3 | */ | ||
4 | #pragma once | ||
5 | |||
6 | #include <stddef.h> | ||
7 | #include <stdint.h> | ||
8 | |||
9 | /// Stack-based allocator. | ||
10 | typedef 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. | ||
25 | bool 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. | ||
30 | void memstack_del(memstack*); | ||
31 | |||
32 | /// Clear the stack. | ||
33 | void memstack_clear(memstack*); | ||
34 | |||
35 | /// Allocate a new block. | ||
36 | /// Return null if the block does not fit in the remaining memory. | ||
37 | /// When there is no space left in the stack, allocation can either trap | ||
38 | /// (default) or gracefully return null. Call mem_enable_traps() to toggle this | ||
39 | /// behaviour. | ||
40 | /// Newly allocated blocks are conveniently zeroed out. | ||
41 | void* memstack_alloc(memstack*, size_t bytes); | ||
42 | |||
43 | /// Return the stack's used size in bytes. | ||
44 | size_t memstack_size(const memstack*); | ||
45 | |||
46 | /// Return the stack's total capacity in bytes. | ||
47 | size_t memstack_capacity(const memstack*); | ||
48 | |||
49 | /// Set whether to trap when attempting to allocate beyond capacity. | ||
50 | void memstack_enable_traps(memstack*, bool); | ||