Debian Codegraph @

src/memory.c

raw symbols SCIP
1 #include <stdlib.h>
2 #include <string.h>
3 #include "memory.h"
4
5 #define MEMORY_INCREMENT 1024
6
7 struct MemoryPool_ {
8 void** blocks;
9 long size;
10 long space;
11 };
12
13 static void enlarge(MemoryPool *pool);
14 static int move_to_front(MemoryPool *pool, void *pointer);
15 static void move_up_one(void **blocks, long amount);
16
17 MemoryPool *create_memory_pool() {
18 MemoryPool *pool = (MemoryPool *)malloc(sizeof(MemoryPool));
19 if (pool == NULL) {
20 return NULL;
21 }
22 pool->blocks = (void **)malloc(MEMORY_INCREMENT * sizeof(void *));
23 if (pool->blocks == NULL) {
24 free(pool);
25 return NULL;
26 }
27 pool->size = 0;
28 pool->space = MEMORY_INCREMENT;
29 return pool;
30 }
31
32 void free_memory_pool(MemoryPool *pool) {
33 long i;
34 for (i = 0; i < pool->size; i++) {
35 free(pool->blocks[i]);
36 }
37 free(pool->blocks);
38 free(pool);
39 }
40
41 void *memory_pool_allocate(MemoryPool *pool, size_t bytes) {
42 enlarge(pool);
43 return pool->blocks[pool->size++] = malloc(bytes);
44 }
45
46 void *memory_pool_reallocate(MemoryPool *pool, void *pointer, size_t bytes) {
47 if (! move_to_front(pool, pointer)) {
48 return NULL;
49 }
50 return pool->blocks[0] = realloc(pool->blocks[0], bytes);
51 }
52
53 static void enlarge(MemoryPool *pool) {
54 if (pool->size == pool->space) {
55 pool->blocks = (void**)realloc(pool->blocks, (pool->space + MEMORY_INCREMENT) * sizeof(void *));
56 pool->space += MEMORY_INCREMENT;
57 }
58 }
59
60 static int move_to_front(MemoryPool *pool, void *pointer) {
61 long i;
62 for (i = 1; i < pool->size; i++) {
63 if (pool->blocks[i] == pointer) {
64 move_up_one(pool->blocks, i);
65 pool->blocks[0] = pointer;
66 return 1;
67 }
68 }
69 return 0;
70 }
71
72 /* static void move_up_one(void **blocks, long amount) { */
73 /* if (amount == 0) { */
74 /* return; */
75 /* } */
76 /* // FIXME: this doesn't compile and the semantics might be wrong */
77 /* //memmove(blocks[0], blocks[1], (size_t)(blocks[amount] - blocks[1])); */
78 /* } */