Com o autor
[pspdecompiler.git] / alloc.c
bloba8dc99c0d1991a060e08f5446cbb6ce2540aa1b3
1 /**
2 * Author: Humberto Naves (hsnaves@gmail.com)
3 */
5 #include <stdlib.h>
6 #include <string.h>
7 #include "alloc.h"
8 #include "utils.h"
10 struct _link {
11 struct _link *next;
12 size_t size;
15 struct _fixedpool {
16 struct _link *allocated;
17 struct _link *nextfree;
18 size_t size;
19 size_t grownum;
20 size_t bytes;
21 int setzero;
25 fixedpool fixedpool_create (size_t size, size_t grownum, int setzero)
27 fixedpool p = (fixedpool) xmalloc (sizeof (struct _fixedpool));
29 if (size < sizeof (struct _link)) size = sizeof (struct _link);
30 if (grownum < 2) grownum = 2;
32 p->size = size;
33 p->grownum = grownum;
34 p->allocated = NULL;
35 p->nextfree = NULL;
36 p->bytes = 0;
37 p->setzero = setzero;
38 return p;
41 void fixedpool_destroy (fixedpool p, pooltraversefn destroyfn, void *arg)
43 struct _link *ptr, *nptr;
44 char *c;
45 size_t count;
47 for (ptr = p->allocated; ptr; ptr = nptr) {
48 if (destroyfn) {
49 c = (char *) ptr;
50 c += p->size;
51 count = 2 * p->size;
53 while (count <= ptr->size) {
54 destroyfn (c, arg);
55 c += p->size;
56 count += p->size;
60 nptr = ptr->next;
61 free (ptr);
64 p->allocated = NULL;
65 p->nextfree = NULL;
66 free (p);
69 void fixedpool_grow (fixedpool p, void *ptr, size_t ptrsize)
71 char *c;
72 struct _link *l;
73 size_t count;
75 if (ptrsize < 2 * p->size) {
76 free (ptr);
77 return;
80 l = ptr;
81 l->next = p->allocated;
82 l->size = ptrsize;
83 p->bytes += ptrsize;
84 p->allocated = l;
86 c = ptr;
87 c += p->size;
88 count = 2 * p->size;
90 while (count <= ptrsize) {
91 l = (struct _link *) c;
92 l->next = p->nextfree;
93 p->nextfree = l;
94 c += p->size;
95 count += p->size;
99 void *fixedpool_alloc (fixedpool p)
101 struct _link *l;
102 if (!p->nextfree) {
103 size_t size;
104 void *ptr;
106 size = p->grownum * p->size;
107 ptr = xmalloc (size);
108 fixedpool_grow (p, ptr, size);
110 l = p->nextfree;
111 p->nextfree = l->next;
112 if (p->setzero)
113 memset (l, 0, p->size);
114 return (void *) l;
117 void fixedpool_free (fixedpool p, void *ptr)
119 struct _link *l = ptr;
120 l->next = p->nextfree;
121 p->nextfree = l;