aboutsummaryrefslogtreecommitdiff
path: root/memstack/include/memstack.h
diff options
context:
space:
mode:
author3gg <3gg@shellblade.net>2025-07-01 09:34:22 -0700
committer3gg <3gg@shellblade.net>2025-07-01 09:34:22 -0700
commitf99204184c8b96f499f6e7efbffb8b6b4ea8c93f (patch)
tree0aff3a962693312352f1f026e70ad479ee4f4147 /memstack/include/memstack.h
parent53aa4355da4fdadd65d2758f9c2ce68b6c884502 (diff)
Add memstackHEADmain
Diffstat (limited to 'memstack/include/memstack.h')
-rw-r--r--memstack/include/memstack.h50
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.
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/// 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.
41void* memstack_alloc(memstack*, size_t bytes);
42
43/// Return the stack's used size in bytes.
44size_t memstack_size(const memstack*);
45
46/// Return the stack's total capacity in bytes.
47size_t memstack_capacity(const memstack*);
48
49/// Set whether to trap when attempting to allocate beyond capacity.
50void memstack_enable_traps(memstack*, bool);