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
* Contributor(s): Nicholas Bishop
20
* ***** END GPL LICENSE BLOCK *****
24
/** \file blender/blenlib/intern/stack.c
29
#include <stdlib.h> /* abort() */
31
#include "BLI_stack.h" /* own include */
33
#include "BLI_utildefines.h"
34
#include "MEM_guardedalloc.h"
45
BLI_Stack *BLI_stack_new(int elem_size, const char *description)
47
BLI_Stack *stack = MEM_callocN(sizeof(*stack), description);
49
stack->elem_size = elem_size;
54
void BLI_stack_free(BLI_Stack *stack)
58
MEM_freeN(stack->data);
63
/* Gets the last element in the stack */
64
#define STACK_LAST_ELEM(stack__) \
65
(((char *)(stack__)->data) + \
66
((stack__)->elem_size * ((stack__)->totelem - 1)))
68
void BLI_stack_push(BLI_Stack *stack, void *src)
70
/* Ensure stack is large enough */
71
if (stack->totelem == stack->maxelem) {
72
if (stack->maxelem == 0) {
73
/* Initialize stack with space for a small hardcoded
74
* number of elements */
76
stack->data = MEM_mallocN((stack->elem_size *
80
/* Double stack size */
81
int maxelem = stack->maxelem + stack->maxelem;
82
/* Check for overflow */
83
BLI_assert(maxelem > stack->maxelem);
84
stack->data = MEM_reallocN(stack->data,
87
stack->maxelem = maxelem;
91
BLI_assert(stack->totelem < stack->maxelem);
93
/* Copy source to end of stack */
95
memcpy(STACK_LAST_ELEM(stack), src, stack->elem_size);
98
void BLI_stack_pop(BLI_Stack *stack, void *dst)
100
BLI_assert(stack->totelem > 0);
101
if (stack->totelem > 0) {
102
memcpy(dst, STACK_LAST_ELEM(stack), stack->elem_size);
107
int BLI_stack_empty(const BLI_Stack *stack)
109
return stack->totelem == 0;