-
Notifications
You must be signed in to change notification settings - Fork 0
/
memorypool.c
96 lines (70 loc) · 1.32 KB
/
memorypool.c
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <stdio.h>
#include <string.h>
#include "memorypool.h"
struct MemoryPool
{
unsigned int max_size;
unsigned int index;
char *buffer;
void *objs;
};
static struct MemoryPool mp;
int MP_set(unsigned int size)
{
mp.index = 0;
mp.max_size = 0;
mp.buffer = NULL;
if (size != 0)
{
mp.buffer = malloc(size);
if (mp.buffer == NULL)
return 1;
mp.max_size = size;
}
else
free(mp.buffer);
return 0;
}
int MP_add(unsigned int size)
{
if (size != 0)
{
char *tbuff = (int *)realloc(mp.buffer, mp.max_size + size);
if (tbuff == NULL)
return 1;
mp.buffer = tbuff;
mp.max_size += size;
}
return 0;
}
void MP_draw(int visual)
{
printf("[Pool allocator]\n\t[Size]: %d\n\t[Current]: %d\n", mp.max_size, mp.index);
if (visual)
{
printf("\t[Visual]: ");
for (unsigned int i = 0; i < mp.max_size; i++)
{
printf("%c", i < mp.index ? 254 : 'X');
}
printf("\n");
}
}
void* MP_alloc(unsigned int obj_size)
{
if (mp.index + obj_size <= mp.max_size)
{
unsigned int old_index = mp.index;
mp.index += obj_size;
return &mp.buffer[old_index];
}
// if there's no enough mem we reallocate it
// and (if success) retry the operation
if (MP_add((int)(mp.max_size * 0.5)))
return NULL;
return MP_alloc(obj_size);
}
void MP_dealloc(unsigned int size)
{
// todo implement defragmentation
}