LibNRG  0.0.1
Networking for Real-time Games library
 All Classes Files Functions Variables Friends
nrg_queue.h
Go to the documentation of this file.
1 /*
2  LibNRG - Networking for Real-time Games
3 
4  Copyright (C) 2012-2014 Alex Baines <alex@abaines.me.uk>
5 
6  This software is provided 'as-is', without any express or implied
7  warranty. In no event will the authors be held liable for any damages
8  arising from the use of this software.
9 
10  Permission is granted to anyone to use this software for any purpose,
11  including commercial applications, and to alter it and redistribute it
12  freely, subject to the following restrictions:
13 
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 */
25 #include "nrg_core.h"
26 #include <vector>
27 #include <utility>
28 #include <stdexcept>
29 
30 namespace nrg {
31 
33 template<class T>
34 class Queue {
35 public:
37  Queue(size_t sz) : data(sz), tail(0), head(0){}
38 
40  void push(const T& t){
41  data[tail] = t;
42  tail = (tail + 1) % data.size();
43 
44  if(tail == head) expand();
45  }
46 
48  T pop(void){
49  //if(empty()) throw std::underflow_error(__PRETTY_FUNCTION__);
50 
51  T& t = data[head];
52  head = (head + 1) % data.size();
53  return std::move(t);
54  }
55 
57  void clear(){
58  head = tail = 0;
59  }
60 
62  size_t size(){
63  return tail >= head ? tail - head : data.size() - (head - tail);
64  }
65 
67  bool empty(){
68  return head == tail;
69  }
70 
71 private:
72 
73  void expand(){
74  size_t oldsz = data.size();
75  data.resize(oldsz * 2);
76 
77  for(size_t i = 0; i < oldsz; ++i){
78  data[oldsz + i] = std::move(data[(head + i) % oldsz]);
79  }
80 
81  tail = 0;
82  head = oldsz;
83  }
84 
85  std::vector<T> data;
86  size_t tail, head;
87 };
88 
89 }
90 
Simple queue class built on a std::vector.
Definition: nrg_queue.h:34
void push(const T &t)
Push t onto the back of the queue.
Definition: nrg_queue.h:40
bool empty()
Returns true if the queue is empty.
Definition: nrg_queue.h:67
T pop(void)
Remove the head of the queue and return it, don't call this if the queue is empty or all hell will br...
Definition: nrg_queue.h:48
size_t size()
Returns the size of the queue.
Definition: nrg_queue.h:62
Common defines and includes used by all the other nrg header files.
void clear()
Clears the queue.
Definition: nrg_queue.h:57
Queue(size_t sz)
Construct a Queue with initial size sz.
Definition: nrg_queue.h:37