Box2D 2.4.1
A 2D physics engine for games
Loading...
Searching...
No Matches
b2_growable_stack.h
1// MIT License
2
3// Copyright (c) 2019 Erin Catto
4
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11
12// The above copyright notice and this permission notice shall be included in all
13// copies or substantial portions of the Software.
14
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21// SOFTWARE.
22
23#ifndef B2_GROWABLE_STACK_H
24#define B2_GROWABLE_STACK_H
25
26#include <string.h>
27
28#include "b2_settings.h"
29
33template <typename T, int32 N>
35{
36public:
38 {
39 m_stack = m_array;
40 m_count = 0;
41 m_capacity = N;
42 }
43
45 {
46 if (m_stack != m_array)
47 {
48 b2Free(m_stack);
49 m_stack = nullptr;
50 }
51 }
52
53 void Push(const T& element)
54 {
55 if (m_count == m_capacity)
56 {
57 T* old = m_stack;
58 m_capacity *= 2;
59 m_stack = (T*)b2Alloc(m_capacity * sizeof(T));
60 memcpy(m_stack, old, m_count * sizeof(T));
61 if (old != m_array)
62 {
63 b2Free(old);
64 }
65 }
66
67 m_stack[m_count] = element;
68 ++m_count;
69 }
70
71 T Pop()
72 {
73 b2Assert(m_count > 0);
74 --m_count;
75 return m_stack[m_count];
76 }
77
78 int32 GetCount()
79 {
80 return m_count;
81 }
82
83private:
84 T* m_stack;
85 T m_array[N];
86 int32 m_count;
87 int32 m_capacity;
88};
89
90
91#endif
void b2Free(void *mem)
If you implement b2Alloc, you should also implement this function.
Definition b2_settings.h:106
void * b2Alloc(int32 size)
Implement this function to use your own memory allocator.
Definition b2_settings.h:100
Definition b2_growable_stack.h:35