Ocular Engine
CircularQueue.hpp
1 
17 #pragma once
18 #ifndef __H__OCULAR_UTILS_CIRCULAR_QUEUE__H__
19 #define __H__OCULAR_UTILS_CIRCULAR_QUEUE__H__
20 
21 #include <array>
22 
23 //------------------------------------------------------------------------------------------
24 
29 namespace Ocular
30 {
35  namespace Utils
36  {
42  template<typename T, std::size_t MAX_ELEMENTS>
44  {
45  public:
46 
51  : m_Last(MAX_ELEMENTS - 1), m_Head(0), m_Tail(0), m_NumElements(0)
52  {
53  }
54 
58  ~CircularQueue()
59  {
60  }
61 
67  bool enqueue(T const element)
68  {
69  bool retVal = false;
70 
71  if(m_NumElements < MAX_ELEMENTS)
72  {
73  m_Array[m_Tail] = element;
74  incrementTail();
75  retVal = true;
76  }
77 
78  return retVal;
79  }
80 
87  bool dequeue(T& retElement)
88  {
89  bool retVal = false;
90 
91  if(m_NumElements > 0)
92  {
93  retElement = m_Array[m_Head];
94 
95  incrementHead();
96  retVal = true;
97  }
98 
99  return retVal;
100  }
101 
102  bool dequeue()
103  {
104  bool retVal = false;
105 
106  if(m_NumElements > 0)
107  {
108  incrementHead();
109  retVal = true;
110  }
111 
112  return retVal;
113  }
114 
119  bool peek(T& retElement)
120  {
121  bool retVal = false;;
122 
123  if(m_NumElements > 0)
124  {
125  retElement = m_Array[m_Head];
126  retVal = true;
127  }
128 
129  return retVal;
130  }
131 
135  unsigned getNumElements() const
136  {
137  return m_NumElements;
138  }
139 
143  void clear()
144  {
145  while(dequeue());
146  }
147 
148  protected:
149 
150  private:
151 
155  void incrementHead()
156  {
157  if (m_NumElements > 0)
158  {
159 
160  if (m_Head != m_Last)
161  {
162  m_Head++;
163  }
164  else
165  {
166  m_Head = 0;
167  }
168 
169  m_NumElements--;
170  }
171  }
172 
176  void incrementTail()
177  {
178  if (m_NumElements < MAX_ELEMENTS)
179  {
180  if (m_Tail != m_Last)
181  {
182  m_Tail++;
183  }
184  else
185  {
186  m_Tail = 0;
187  }
188 
189  m_NumElements++;
190  }
191  }
192 
193  //----------------------------------------
194 
195  unsigned m_NumElements;
196  unsigned m_Head;
197  unsigned m_Tail;
198  unsigned m_Last;
199 
200  std::array<T, MAX_ELEMENTS> m_Array;
201  };
202  }
206 }
211 //------------------------------------------------------------------------------------------
212 
213 #endif
bool dequeue(T &retElement)
Definition: CircularQueue.hpp:87
Definition: CircularQueue.hpp:43
bool enqueue(T const element)
Definition: CircularQueue.hpp:67
Note: Once this library is made dynamic, this will no longer be needed.
Definition: Common.hpp:70
CircularQueue()
Definition: CircularQueue.hpp:50
unsigned getNumElements() const
Definition: CircularQueue.hpp:135
bool peek(T &retElement)
Definition: CircularQueue.hpp:119
void clear()
Definition: CircularQueue.hpp:143