GrowableStack.cs 2.1 KB

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