b2GrowableStack.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2010 Erin Catto http://www.box2d.org
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. * Permission is granted to anyone to use this software for any purpose,
  8. * including commercial applications, and to alter it and redistribute it
  9. * freely, subject to the following restrictions:
  10. * 1. The origin of this software must not be misrepresented; you must not
  11. * claim that you wrote the original software. If you use this software
  12. * in a product, an acknowledgment in the product documentation would be
  13. * appreciated but is not required.
  14. * 2. Altered source versions must be plainly marked as such, and must not be
  15. * misrepresented as being the original software.
  16. * 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #ifndef B2_GROWABLE_STACK_H
  19. #define B2_GROWABLE_STACK_H
  20. #include <Box2D/Common/b2Settings.h>
  21. #include <memory.h>
  22. #include <string.h>
  23. /// This is a growable LIFO stack with an initial capacity of N.
  24. /// If the stack size exceeds the initial capacity, the heap is used
  25. /// to increase the size of the stack.
  26. template <typename T, int32 N>
  27. class b2GrowableStack
  28. {
  29. public:
  30. b2GrowableStack()
  31. {
  32. m_stack = m_array;
  33. m_count = 0;
  34. m_capacity = N;
  35. }
  36. ~b2GrowableStack()
  37. {
  38. if (m_stack != m_array)
  39. {
  40. b2Free(m_stack);
  41. m_stack = NULL;
  42. }
  43. }
  44. void Push(const T& element)
  45. {
  46. if (m_count == m_capacity)
  47. {
  48. T* old = m_stack;
  49. m_capacity *= 2;
  50. m_stack = (T*)b2Alloc(m_capacity * sizeof(T));
  51. memcpy(m_stack, old, m_count * sizeof(T));
  52. if (old != m_array)
  53. {
  54. b2Free(old);
  55. }
  56. }
  57. m_stack[m_count] = element;
  58. ++m_count;
  59. }
  60. T Pop()
  61. {
  62. b2Assert(m_count > 0);
  63. --m_count;
  64. return m_stack[m_count];
  65. }
  66. int32 GetCount()
  67. {
  68. return m_count;
  69. }
  70. private:
  71. T* m_stack;
  72. T m_array[N];
  73. int32 m_count;
  74. int32 m_capacity;
  75. };
  76. #endif