b2StackQueue.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright (c) 2013 Google, Inc.
  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_STACK_QUEUE
  19. #define B2_STACK_QUEUE
  20. #include <Box2D/Common/b2StackAllocator.h>
  21. template <typename T>
  22. class b2StackQueue
  23. {
  24. public:
  25. b2StackQueue(b2StackAllocator *allocator, int32 capacity)
  26. {
  27. m_allocator = allocator;
  28. m_buffer = (T*) m_allocator->Allocate(sizeof(T) * capacity);
  29. m_front = 0;
  30. m_back = 0;
  31. m_capacity = capacity;
  32. }
  33. ~b2StackQueue()
  34. {
  35. m_allocator->Free(m_buffer);
  36. }
  37. void Push(const T &item)
  38. {
  39. if (m_back >= m_capacity)
  40. {
  41. for (int32 i = m_front; i < m_back; i++)
  42. {
  43. m_buffer[i - m_front] = m_buffer[i];
  44. }
  45. m_back -= m_front;
  46. m_front = 0;
  47. if (m_back >= m_capacity)
  48. {
  49. if (m_capacity > 0)
  50. {
  51. m_capacity *= 2;
  52. }
  53. else
  54. {
  55. m_capacity = 1;
  56. }
  57. m_buffer = (T*) m_allocator->Reallocate(m_buffer,
  58. sizeof(T) * m_capacity);
  59. }
  60. }
  61. m_buffer[m_back] = item;
  62. m_back++;
  63. }
  64. void Pop()
  65. {
  66. b2Assert(m_front < m_back);
  67. m_front++;
  68. }
  69. bool Empty() const
  70. {
  71. b2Assert(m_front <= m_back);
  72. return m_front == m_back;
  73. }
  74. const T &Front() const
  75. {
  76. return m_buffer[m_front];
  77. }
  78. private:
  79. b2StackAllocator *m_allocator;
  80. T* m_buffer;
  81. int32 m_front;
  82. int32 m_back;
  83. int32 m_capacity;
  84. };
  85. #endif