]> mj.ucw.cz Git - libucw.git/blob - lib/pool.c
8b6c73e1427fdbe97ec8547d58d15b93e70b66fe
[libucw.git] / lib / pool.c
1 /*
2  *      Sherlock Library -- Memory Pools (One-Time Allocation)
3  *
4  *      (c) 1997 Martin Mares, <mj@atrey.karlin.mff.cuni.cz>
5  */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9
10 #include "lib.h"
11 #include "pools.h"
12
13 struct memchunk {
14   struct memchunk *next;
15   byte data[0];
16 };
17
18 struct mempool *
19 new_pool(uns size)
20 {
21   struct mempool *p = xmalloc(sizeof(struct mempool));
22
23   size -= sizeof(struct memchunk);
24   p->chunks = NULL;
25   p->free = p->last = NULL;
26   p->chunk_size = size;
27   p->threshold = size / 3;
28   return p;
29 }
30
31 void
32 free_pool(struct mempool *p)
33 {
34   struct memchunk *c = p->chunks;
35
36   while (c)
37     {
38       struct memchunk *n = c->next;
39       free(c);
40       c = n;
41     }
42   free(p);
43 }
44
45 void *
46 pool_alloc(struct mempool *p, uns s)
47 {
48   if (s <= p->threshold)
49     {
50       byte *x = (byte *)(((uns) p->free + POOL_ALIGN - 1) & ~(POOL_ALIGN - 1));
51       if (x + s > p->last)
52         {
53           struct memchunk *c = xmalloc(sizeof(struct memchunk) + p->chunk_size);
54           c->next = p->chunks;
55           p->chunks = c;
56           x = c->data;
57           p->last = x + p->chunk_size;
58         }
59       p->free = x + s;
60       return x;
61     }
62   else
63     {
64       struct memchunk *c = xmalloc(sizeof(struct memchunk) + s);
65       c->next = p->chunks;
66       p->chunks = c;
67       return c->data;
68     }
69 }