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 #include "box2d/b2_stack_allocator.h"
24 #include "box2d/b2_math.h"
25
b2StackAllocator()26 b2StackAllocator::b2StackAllocator()
27 {
28 m_index = 0;
29 m_allocation = 0;
30 m_maxAllocation = 0;
31 m_entryCount = 0;
32 }
33
~b2StackAllocator()34 b2StackAllocator::~b2StackAllocator()
35 {
36 b2Assert(m_index == 0);
37 b2Assert(m_entryCount == 0);
38 }
39
Allocate(int32 size)40 void* b2StackAllocator::Allocate(int32 size)
41 {
42 b2Assert(m_entryCount < b2_maxStackEntries);
43
44 b2StackEntry* entry = m_entries + m_entryCount;
45 entry->size = size;
46 if (m_index + size > b2_stackSize)
47 {
48 entry->data = (char*)b2Alloc(size);
49 entry->usedMalloc = true;
50 }
51 else
52 {
53 entry->data = m_data + m_index;
54 entry->usedMalloc = false;
55 m_index += size;
56 }
57
58 m_allocation += size;
59 m_maxAllocation = b2Max(m_maxAllocation, m_allocation);
60 ++m_entryCount;
61
62 return entry->data;
63 }
64
Free(void * p)65 void b2StackAllocator::Free(void* p)
66 {
67 b2Assert(m_entryCount > 0);
68 b2StackEntry* entry = m_entries + m_entryCount - 1;
69 b2Assert(p == entry->data);
70 if (entry->usedMalloc)
71 {
72 b2Free(p);
73 }
74 else
75 {
76 m_index -= entry->size;
77 }
78 m_allocation -= entry->size;
79 --m_entryCount;
80
81 p = nullptr;
82 }
83
GetMaxAllocation() const84 int32 b2StackAllocator::GetMaxAllocation() const
85 {
86 return m_maxAllocation;
87 }
88