Passo intermediario, ainda falta um longo caminho
[pspdecompiler.git] / alloc.c
blob1dd8499c42d439ea72530a98bdeefdba3696ba07
2 #include <stdlib.h>
3 #include <string.h>
4 #include "alloc.h"
5 #include "utils.h"
7 struct _link {
8 struct _link *next;
9 size_t size;
12 struct _fixedpool {
13 struct _link *allocated;
14 struct _link *nextfree;
15 size_t size;
16 size_t grownum;
17 size_t bytes;
18 int setzero;
22 fixedpool fixedpool_create (size_t size, size_t grownum, int setzero)
24 fixedpool p = (fixedpool) xmalloc (sizeof (struct _fixedpool));
26 if (size < sizeof (struct _link)) size = sizeof (struct _link);
27 if (grownum < 2) grownum = 2;
29 p->size = size;
30 p->grownum = grownum;
31 p->allocated = NULL;
32 p->nextfree = NULL;
33 p->bytes = 0;
34 p->setzero = setzero;
35 return p;
38 void fixedpool_destroy (fixedpool p, pooltraversefn destroyfn, void *arg)
40 struct _link *ptr, *nptr;
41 char *c;
42 size_t count;
44 for (ptr = p->allocated; ptr; ptr = nptr) {
45 if (destroyfn) {
46 c = (char *) ptr;
47 c += p->size;
48 count = 2 * p->size;
50 while (count <= ptr->size) {
51 destroyfn (c, arg);
52 c += p->size;
53 count += p->size;
57 nptr = ptr->next;
58 free (ptr);
61 p->allocated = NULL;
62 p->nextfree = NULL;
63 free (p);
66 void fixedpool_grow (fixedpool p, void *ptr, size_t ptrsize)
68 char *c;
69 struct _link *l;
70 size_t count;
72 if (ptrsize < 2 * p->size) {
73 free (ptr);
74 return;
77 l = ptr;
78 l->next = p->allocated;
79 l->size = ptrsize;
80 p->bytes += ptrsize;
81 p->allocated = l;
83 c = ptr;
84 c += p->size;
85 count = 2 * p->size;
87 while (count <= ptrsize) {
88 l = (struct _link *) c;
89 l->next = p->nextfree;
90 p->nextfree = l;
91 c += p->size;
92 count += p->size;
96 void *fixedpool_alloc (fixedpool p)
98 struct _link *l;
99 if (!p->nextfree) {
100 size_t size;
101 void *ptr;
103 size = p->grownum * p->size;
104 ptr = xmalloc (size);
105 fixedpool_grow (p, ptr, size);
107 l = p->nextfree;
108 p->nextfree = l->next;
109 if (p->setzero)
110 memset (l, 0, p->size);
111 return (void *) l;
114 void fixedpool_free (fixedpool p, void *ptr)
116 struct _link *l = ptr;
117 l->next = p->nextfree;
118 p->nextfree = l;