2 * mempool.c: efficient memory allocation
4 * MonoMemPool is for fast allocation of memory. We free
5 * all memory when the pool is destroyed.
8 * Dietmar Maurer (dietmar@ximian.com)
10 * (C) 2001 Ximian, Inc.
20 * MonoMemPool is for fast allocation of memory. We free
21 * all memory when the pool is destroyed.
26 #define MONO_MEMPOOL_PAGESIZE 8192
34 double pad; /* to assure proper alignment */
42 * Returns: a new memory pool.
47 MonoMemPool *pool = g_malloc (MONO_MEMPOOL_PAGESIZE);
50 pool->pos = (char *)pool + sizeof (MonoMemPool);
51 pool->rest = MONO_MEMPOOL_PAGESIZE - sizeof (MonoMemPool);
52 pool->d.allocated = pool->size = MONO_MEMPOOL_PAGESIZE;
57 * mono_mempool_destroy:
58 * @pool: the memory pool to destroy
60 * Free all memory associated with this pool.
63 mono_mempool_destroy (MonoMemPool *pool)
76 * mono_mempool_invalidate:
77 * @pool: the memory pool to invalidate
79 * Fill the memory associated with this pool to 0x2a (42). Useful for debugging.
82 mono_mempool_invalidate (MonoMemPool *pool)
89 memset (p, 42, p->size);
95 mono_mempool_empty (MonoMemPool *pool)
97 pool->pos = (char *)pool + sizeof (MonoMemPool);
98 pool->rest = MONO_MEMPOOL_PAGESIZE - sizeof (MonoMemPool);
102 * mono_mempool_stats:
103 * @pool: the momory pool we need stats for
105 * Print a few stats about the mempool
108 mono_mempool_stats (MonoMemPool *pool)
112 guint32 still_free = 0;
116 still_free += p->rest;
122 g_print ("Mempool %p stats:\n", pool);
123 g_print ("Total mem allocated: %d\n", pool->d.allocated);
124 g_print ("Num chunks: %d\n", count);
125 g_print ("Free memory: %d\n", still_free);
130 * mono_mempool_alloc:
131 * @pool: the momory pool to destroy
132 * @size: size of the momory block
134 * Allocates a new block of memory in @pool. @size must
135 * be smaller than 256.
137 * Returns: the address of a newly allocated memory block.
140 mono_mempool_alloc (MonoMemPool *pool, guint size)
144 g_assert (pool != NULL);
146 size = (size + MEM_ALIGN - 1) & ~(MEM_ALIGN - 1);
148 if (pool->rest < size) {
150 MonoMemPool *np = g_malloc (sizeof (MonoMemPool) + size);
151 np->next = pool->next;
153 np->size = sizeof (MonoMemPool) + size;
154 pool->d.allocated += sizeof (MonoMemPool) + size;
155 return (char *)np + sizeof (MonoMemPool);
157 MonoMemPool *np = g_malloc (MONO_MEMPOOL_PAGESIZE);
158 np->next = pool->next;
160 pool->pos = (char *)np + sizeof (MonoMemPool);
161 np->size = MONO_MEMPOOL_PAGESIZE;
162 pool->rest = MONO_MEMPOOL_PAGESIZE - sizeof (MonoMemPool);
163 pool->d.allocated += MONO_MEMPOOL_PAGESIZE;
169 pool->pos = (char *)pool->pos + size;
175 * mono_mempool_alloc0:
177 * same as mono_mempool_alloc, but fills memory with zero.
180 mono_mempool_alloc0 (MonoMemPool *pool, guint size)
182 gpointer rval = mono_mempool_alloc (pool, size);
183 memset (rval, 0, size);