GBAlatro
A Demake of Balatro for the GBA
Loading...
Searching...
No Matches
pool.h
1#ifndef POOL_H
2#define POOL_H
3
4#include "bitset.h"
5#include "mgba_logger.h"
6
7#include <stdbool.h>
8#include <stdint.h>
9
10#ifdef POOLS_TEST_ENV
11// We defined these as empty here for tests that will include this header but don't rely on tonc.h.
12#define POOLS_DEF_FILE "def_test_mempool.h"
13#ifndef IWRAM_DATA
14#define IWRAM_DATA
15#endif
16#ifndef EWRAM_DATA
17#define EWRAM_DATA
18#endif
19#else
20#define POOLS_DEF_FILE "def_balatro_mempool.h"
21#endif
22
23#define POOL_DECLARE_TYPE(type) \
24 typedef struct \
25 { \
26 Bitset* bitset; \
27 type* objects; \
28 } type##Pool; \
29 type* pool_get_##type(); \
30 void pool_free_##type(type* obj); \
31 int pool_idx_##type(type* obj); \
32 type* pool_at_##type(int idx);
33
34#define POOL_DEFINE_TYPE(type, capacity, mem_section) \
35 BITSET_DEFINE(type##_bitset, capacity) \
36 mem_section##_DATA static type type##_storage[capacity]; \
37 mem_section##_DATA static type##Pool type##_pool = { \
38 .bitset = &type##_bitset, \
39 .objects = type##_storage, \
40 }; \
41 type* pool_get_##type() \
42 { \
43 int free_offset = bitset_set_next_free_idx(type##_pool.bitset); \
44 if (free_offset == -1) \
45 { \
46 MGBA_FUNC_ERROR("No more free space in pool for new '%s' object", "##type"); \
47 return NULL; \
48 } \
49 return &type##_pool.objects[free_offset]; \
50 } \
51 void pool_free_##type(type* entry) \
52 { \
53 if (entry == NULL) \
54 return; \
55 int offset = entry - &type##_pool.objects[0]; \
56 bitset_set_idx(type##_pool.bitset, offset, false); \
57 } \
58 int pool_idx_##type(type* entry) \
59 { \
60 return entry - &type##_pool.objects[0]; \
61 } \
62 type* pool_at_##type(int idx) \
63 { \
64 if (idx < 0 || idx >= (type##_pool.bitset)->cap) \
65 return NULL; \
66 return &type##_pool.objects[idx]; \
67 }
68
69#define POOL_GET(type) pool_get_##type()
70#define POOL_FREE(type, obj) pool_free_##type(obj)
71#define POOL_IDX(type, obj) pool_idx_##type(obj) // the index of the object
72#define POOL_AT(type, idx) pool_at_##type(idx) // the object at
73
74#define POOL_ENTRY(name, capacity, mem_section) POOL_DECLARE_TYPE(name);
75#include POOLS_DEF_FILE
76#undef POOL_ENTRY
77
78#endif // POOL_H
A bitset for operating on flags.
Interface to interact with the mgba logger.