b2_growable_stack.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // MIT License
  2. // Copyright (c) 2019 Erin Catto
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. // The above copyright notice and this permission notice shall be included in all
  10. // copies or substantial portions of the Software.
  11. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. // SOFTWARE.
  18. #ifndef B2_GROWABLE_STACK_H
  19. #define B2_GROWABLE_STACK_H
  20. #include <string.h>
  21. #include "b2_settings.h"
  22. /// This is a growable LIFO stack with an initial capacity of N.
  23. /// If the stack size exceeds the initial capacity, the heap is used
  24. /// to increase the size of the stack.
  25. template <typename T, int32 N>
  26. class b2GrowableStack
  27. {
  28. public:
  29. b2GrowableStack()
  30. {
  31. m_stack = m_array;
  32. m_count = 0;
  33. m_capacity = N;
  34. }
  35. ~b2GrowableStack()
  36. {
  37. if (m_stack != m_array)
  38. {
  39. b2Free(m_stack);
  40. m_stack = nullptr;
  41. }
  42. }
  43. void Push(const T& element)
  44. {
  45. if (m_count == m_capacity)
  46. {
  47. T* old = m_stack;
  48. m_capacity *= 2;
  49. m_stack = (T*)b2Alloc(m_capacity * sizeof(T));
  50. memcpy(m_stack, old, m_count * sizeof(T));
  51. if (old != m_array)
  52. {
  53. b2Free(old);
  54. }
  55. }
  56. m_stack[m_count] = element;
  57. ++m_count;
  58. }
  59. T Pop()
  60. {
  61. b2Assert(m_count > 0);
  62. --m_count;
  63. return m_stack[m_count];
  64. }
  65. int32 GetCount()
  66. {
  67. return m_count;
  68. }
  69. private:
  70. T* m_stack;
  71. T m_array[N];
  72. int32 m_count;
  73. int32 m_capacity;
  74. };
  75. #endif