LiquidFun
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
b2StackQueue.h
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 
21 #include <Box2D/Common/b2StackAllocator.h>
22 
23 template <typename T>
25 {
26 
27 public:
28 
29  b2StackQueue(b2StackAllocator *allocator, int32 capacity)
30  {
31  m_allocator = allocator;
32  m_buffer = (T*) m_allocator->Allocate(sizeof(T) * capacity);
33  m_front = 0;
34  m_back = 0;
35  m_capacity = capacity;
36  }
37 
38  ~b2StackQueue()
39  {
40  m_allocator->Free(m_buffer);
41  }
42 
43  void Push(const T &item)
44  {
45  if (m_back >= m_capacity)
46  {
47  for (int32 i = m_front; i < m_back; i++)
48  {
49  m_buffer[i - m_front] = m_buffer[i];
50  }
51  m_back -= m_front;
52  m_front = 0;
53  if (m_back >= m_capacity)
54  {
55  if (m_capacity > 0)
56  {
57  m_capacity *= 2;
58  }
59  else
60  {
61  m_capacity = 1;
62  }
63  m_buffer = (T*) m_allocator->Reallocate(m_buffer,
64  sizeof(T) * m_capacity);
65  }
66  }
67  m_buffer[m_back] = item;
68  m_back++;
69  }
70 
71  void Pop()
72  {
73  b2Assert(m_front < m_back);
74  m_front++;
75  }
76 
77  bool Empty() const
78  {
79  b2Assert(m_front <= m_back);
80  return m_front == m_back;
81  }
82 
83  const T &Front() const
84  {
85  return m_buffer[m_front];
86  }
87 
88 private:
89 
90  b2StackAllocator *m_allocator;
91  T* m_buffer;
92  int32 m_front;
93  int32 m_back;
94  int32 m_capacity;
95 
96 };
97 
98 #endif
Definition: b2StackAllocator.h:37
Definition: b2StackQueue.h:24