1 /*
2 * pools.c
3 *
4 * MathMap
5 *
6 * Copyright (C) 2002-2004 Mark Probst
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include <string.h>
24 #include <assert.h>
25
26 #include "pools.h"
27
28 void
init_pools(pools_t * pools)29 init_pools (pools_t *pools)
30 {
31 int i;
32
33 pools->active_pool = -1;
34 pools->fill_ptr = 0;
35
36 for (i = 0; i < NUM_POOLS; ++i)
37 pools->pools[i] = 0;
38 }
39
40 void
reset_pools(pools_t * pools)41 reset_pools (pools_t *pools)
42 {
43 pools->active_pool = -1;
44 pools->fill_ptr = 0;
45 }
46
47 void
free_pools(pools_t * pools)48 free_pools (pools_t *pools)
49 {
50 int i;
51
52 /* printf("alloced %d pools\n", active_pool + 1); */
53 for (i = 0; i < NUM_POOLS; ++i)
54 if (pools->pools[i] != 0)
55 free(pools->pools[i]);
56
57 init_pools(pools);
58 }
59
60 void*
pools_alloc(pools_t * pools,size_t size)61 pools_alloc (pools_t *pools, size_t size)
62 {
63 size_t pool_size;
64 void *p;
65
66 if (pools->active_pool < 0)
67 {
68 pools->active_pool = 0;
69 if (pools->pools[0] == 0)
70 pools->pools[0] = (long*)malloc(GRANULARITY * FIRST_POOL_SIZE);
71 pools->fill_ptr = 0;
72
73 memset(pools->pools[0], 0, GRANULARITY * FIRST_POOL_SIZE);
74 }
75
76 pool_size = FIRST_POOL_SIZE << pools->active_pool;
77 size = (size + GRANULARITY - 1) / GRANULARITY;
78
79 if (pools->fill_ptr + size >= pool_size)
80 {
81 ++pools->active_pool;
82 assert(pools->active_pool < NUM_POOLS);
83 if (pools->pools[pools->active_pool] == 0)
84 pools->pools[pools->active_pool] = (long*)malloc(GRANULARITY * (FIRST_POOL_SIZE << pools->active_pool));
85 pools->fill_ptr = 0;
86
87 memset(pools->pools[pools->active_pool], 0, GRANULARITY * (FIRST_POOL_SIZE << pools->active_pool));
88 }
89
90 assert(pools->fill_ptr + size < pool_size);
91
92 p = pools->pools[pools->active_pool] + pools->fill_ptr;
93 pools->fill_ptr += size;
94
95 return p;
96 }
97