File indexing completed on 2024-05-19 14:56:23

0001 /*
0002 * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
0003 *
0004 * This software is provided 'as-is', without any express or implied
0005 * warranty.  In no event will the authors be held liable for any damages
0006 * arising from the use of this software.
0007 * Permission is granted to anyone to use this software for any purpose,
0008 * including commercial applications, and to alter it and redistribute it
0009 * freely, subject to the following restrictions:
0010 * 1. The origin of this software must not be misrepresented; you must not
0011 * claim that you wrote the original software. If you use this software
0012 * in a product, an acknowledgment in the product documentation would be
0013 * appreciated but is not required.
0014 * 2. Altered source versions must be plainly marked as such, and must not be
0015 * misrepresented as being the original software.
0016 * 3. This notice may not be removed or altered from any source distribution.
0017 */
0018 
0019 #include <Box2D/Common/b2StackAllocator.h>
0020 #include <Box2D/Common/b2Math.h>
0021 
0022 b2StackAllocator::b2StackAllocator()
0023 {
0024     m_index = 0;
0025     m_allocation = 0;
0026     m_maxAllocation = 0;
0027     m_entryCount = 0;
0028 }
0029 
0030 b2StackAllocator::~b2StackAllocator()
0031 {
0032     b2Assert(m_index == 0);
0033     b2Assert(m_entryCount == 0);
0034 }
0035 
0036 void* b2StackAllocator::Allocate(int32 size)
0037 {
0038     b2Assert(m_entryCount < b2_maxStackEntries);
0039 
0040     b2StackEntry* entry = m_entries + m_entryCount;
0041     entry->size = size;
0042     if (m_index + size > b2_stackSize)
0043     {
0044         entry->data = (char*)b2Alloc(size);
0045         entry->usedMalloc = true;
0046     }
0047     else
0048     {
0049         entry->data = m_data + m_index;
0050         entry->usedMalloc = false;
0051         m_index += size;
0052     }
0053 
0054     m_allocation += size;
0055     m_maxAllocation = b2Max(m_maxAllocation, m_allocation);
0056     ++m_entryCount;
0057 
0058     return entry->data;
0059 }
0060 
0061 void b2StackAllocator::Free(void* p)
0062 {
0063     b2Assert(m_entryCount > 0);
0064     b2StackEntry* entry = m_entries + m_entryCount - 1;
0065     b2Assert(p == entry->data);
0066     if (entry->usedMalloc)
0067     {
0068         b2Free(p);
0069     }
0070     else
0071     {
0072         m_index -= entry->size;
0073     }
0074     m_allocation -= entry->size;
0075     --m_entryCount;
0076 
0077     p = NULL;
0078 }
0079 
0080 int32 b2StackAllocator::GetMaxAllocation() const
0081 {
0082     return m_maxAllocation;
0083 }