core: Add simple temporary buffer allocator.
[gfxprim.git] / include / core / GP_TempAlloc.h
blob925b112ecfbe8bfd58364b4db6354a13798b0720
1 /*****************************************************************************
2 * This file is part of gfxprim library. *
3 * *
4 * Gfxprim is free software; you can redistribute it and/or *
5 * modify it under the terms of the GNU Lesser General Public *
6 * License as published by the Free Software Foundation; either *
7 * version 2.1 of the License, or (at your option) any later version. *
8 * *
9 * Gfxprim 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 GNU *
12 * Lesser General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU Lesser General Public *
15 * License along with gfxprim; if not, write to the Free Software *
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, *
17 * Boston, MA 02110-1301 USA *
18 * *
19 * Copyright (C) 2009-2012 Cyril Hrubis <metan@ucw.cz> *
20 * *
21 *****************************************************************************/
25 Temporary block allocator implementation.
27 Creates pool for block allocation (small ones are done on the stack, bigger
28 using malloc).
30 The usage is:
32 // Creates new allocation pool
33 GP_TempAllocCrate(buf, 3 * 1024);
35 // Make use of it
36 int *R = GP_TempAllocGet(buf, 1024);
37 int *G = GP_TempAllocGet(buf, 1024);
38 int *B = GP_TempAllocGet(buf, 1024);
40 ...
42 // Free it
43 GP_TempAllocDestroy(buf);
47 #ifndef CORE_GP_TEMP_ALLOC_H
48 #define CORE_GP_TEMP_ALLOC_H
50 #include <alloca.h>
51 #include <stdlib.h>
53 #include "core/GP_Common.h"
55 #ifndef GP_ALLOCA_THRESHOLD
56 # define GP_ALLOCA_THRESHOLD 2048
57 #endif
59 struct GP_TempAlloc {
60 void *buffer;
61 size_t pos;
62 size_t size;
65 #define GP_TEMP_ALLOC(size) ({ \
66 ((size) > GP_ALLOCA_THRESHOLD) ? malloc(size) : alloca(size); \
69 #define GP_TempAllocCreate(name, bsize) \
70 struct GP_TempAlloc name = {.size = (bsize), .pos = 0, \
71 .buffer = GP_TEMP_ALLOC(bsize)};
73 #define GP_TempAllocGet(self, bsize) ({ \
74 GP_ASSERT(self.pos + bsize <= self.size); \
75 size_t _pos = self.pos; \
76 self.pos += bsize; \
77 (void*)(((char*)(self.buffer)) + _pos); \
80 #define GP_TempAllocFree(self) do { \
81 if (self.size > GP_ALLOCA_THRESHOLD) \
82 free(self.buffer); \
83 } while (0)
85 #endif /* CORE_GP_TEMP_ALLOC_H */