-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtiny_stack_allocator.c
More file actions
71 lines (63 loc) · 1.94 KB
/
tiny_stack_allocator.c
File metadata and controls
71 lines (63 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*!
* @file
* @brief
*/
#include <stddef.h>
#include <stdint.h>
#include "tiny_stack_allocator.h"
#include "tiny_utils.h"
typedef struct {
uint8_t data;
union {
int _int;
long long _long_long;
float _float;
double _double;
long double _long_double;
void* _pointer;
} alignment;
} alignment_t;
enum {
alignment = offsetof(alignment_t, alignment),
};
#define define_worker(_size) \
static void worker_##_size(tiny_stack_allocator_callback_t callback, void* context) \
{ \
uint8_t data[_size + alignment - 1]; \
uintptr_t offset = alignment - ((uintptr_t)data % alignment); \
if(offset == alignment) { \
offset = 0; \
} \
callback(context, &data[offset]); \
} \
typedef int dummy##_size
define_worker(8);
define_worker(16);
define_worker(32);
define_worker(64);
define_worker(128);
define_worker(256);
typedef struct {
size_t size;
void (*worker)(tiny_stack_allocator_callback_t callback, void* context);
} worker_t;
static const worker_t workers[] = {
{ 8, worker_8 },
{ 16, worker_16 },
{ 32, worker_32 },
{ 64, worker_64 },
{ 128, worker_128 },
{ 256, worker_256 },
};
void tiny_stack_allocator_allocate_aligned(
size_t size,
void* context,
tiny_stack_allocator_callback_t callback)
{
for(uint8_t i = 0; i < element_count(workers); i++) {
if(size <= workers[i].size) {
workers[i].worker(callback, context);
return;
}
}
}