2 * ***** BEGIN GPL LICENSE BLOCK *****
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): none yet.
25 * ***** END GPL LICENSE BLOCK *****
26 * Efficient memory allocation for lots of similar small chunks.
29 /** \file blender/blenlib/intern/BLI_memarena.c
33 #include "MEM_guardedalloc.h"
35 #include "BLI_memarena.h"
36 #include "BLI_linklist.h"
39 unsigned char *curbuf;
49 MemArena *BLI_memarena_new(const int bufsize, const char *name)
51 MemArena *ma = MEM_callocN(sizeof(*ma), "memarena");
52 ma->bufsize = bufsize;
59 void BLI_memarena_use_calloc(MemArena *ma)
64 void BLI_memarena_use_malloc(MemArena *ma)
69 void BLI_memarena_use_align(struct MemArena *ma, const int align)
71 /* align should be a power of two */
75 void BLI_memarena_free(MemArena *ma)
77 BLI_linklist_free(ma->bufs, (void (*)(void *))MEM_freeN);
81 /* amt must be power of two */
82 #define PADUP(num, amt) ((num + (amt - 1)) & ~(amt - 1))
84 void *BLI_memarena_alloc(MemArena *ma, int size)
88 /* ensure proper alignment by rounding
89 * size up to multiple of 8 */
90 size = PADUP(size, ma->align);
92 if (size > ma->cursize) {
95 if (size > ma->bufsize - (ma->align - 1)) {
96 ma->cursize = PADUP(size + 1, ma->align);
99 ma->cursize = ma->bufsize;
102 ma->curbuf = MEM_callocN(ma->cursize, ma->name);
104 ma->curbuf = MEM_mallocN(ma->cursize, ma->name);
106 BLI_linklist_prepend(&ma->bufs, ma->curbuf);
108 /* align alloc'ed memory (needed if align > 8) */
109 tmp = (unsigned char *)PADUP( (intptr_t) ma->curbuf, ma->align);
110 ma->cursize -= (tmp - ma->curbuf);