/[cvs]/eggdrop1.9/src/egglib/mempool.c
ViewVC logotype

Contents of /eggdrop1.9/src/egglib/mempool.c

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.2 - (show annotations) (download) (as text)
Sun Oct 28 13:30:35 2001 UTC (17 years, 11 months ago) by ite
Branch: MAIN
CVS Tags: HEAD
Changes since 1.1: +0 -0 lines
File MIME type: text/x-chdr
FILE REMOVED
Renamed src/adns, src/compat, src/egglib to lib/adns, lib/compat, lib/egglib respectively.

1 #include "mempool.h"
2
3 mempool_t *mempool_create(mempool_t *pool, int nchunks, int chunk_size)
4 {
5 mempool_t *mypool;
6
7 if (pool) mypool = pool;
8 else mypool = (mempool_t *)malloc(sizeof(*pool));
9
10 if (!mypool) return((mempool_t *)0);
11
12 /* We need at least sizeof(char *) to keep track of free chunks. */
13 if (chunk_size < sizeof(char *)) chunk_size = sizeof(char *);
14
15 mypool->chunk_size = chunk_size;
16 mypool->nchunks = nchunks;
17 mypool->free_chunk_ptr = (char *)0;
18 mypool->pools = (char *)0;
19
20 mempool_grow(mypool, nchunks);
21
22 return(mypool);
23 }
24
25 int mempool_destroy(mempool_t *pool)
26 {
27 char *ptr, *next;
28
29 if (!pool) return(0);
30 for (ptr = pool->pools; ptr; ptr = next) {
31 next = *(char **)ptr;
32 free(ptr);
33 }
34 free(pool);
35 return(0);
36 }
37
38 int mempool_grow(mempool_t *pool, int nchunks)
39 {
40 char *ptr, *ptr_start;
41
42 ptr = (char *)malloc(sizeof(char *) + pool->chunk_size * nchunks);
43 if (!ptr) return(1);
44
45 /* Add this pool to the list of pools. */
46 if (pool->pools) *(char **)ptr = pool->pools;
47 pool->pools = ptr;
48
49 /* Now initialize all the chunks in this new pool. */
50 ptr += sizeof(char *);
51 ptr_start = ptr;
52 while (nchunks--) {
53 *(char **)ptr = ptr + pool->chunk_size;
54 ptr += pool->chunk_size;
55 }
56
57 /* Point to last valid block. */
58 ptr -= pool->chunk_size;
59
60 /* Add a link to the previous first free chunk. */
61 *(char **)ptr = pool->free_chunk_ptr;
62
63 /* Set our first chunk as the first free chunk. */
64 pool->free_chunk_ptr = ptr_start;
65
66 return(0);
67 }
68
69 void *mempool_get_chunk(mempool_t *pool)
70 {
71 register char *ptr;
72
73 /* See if we need more memory. */
74 if (!pool->free_chunk_ptr && mempool_grow(pool, pool->nchunks)) return((void *)0);
75 ptr = pool->free_chunk_ptr;
76
77 /* Update free_chunk_ptr. */
78 pool->free_chunk_ptr = *(char **)ptr;
79 return((void *)ptr);
80 }
81
82 int mempool_free_chunk(mempool_t *pool, void *chunk)
83 {
84 *(char **)chunk = pool->free_chunk_ptr;
85 pool->free_chunk_ptr = (char *)chunk;
86 return(0);
87 }

webmaster@eggheads.org
ViewVC Help
Powered by ViewVC 1.1.23