-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventQueue.hpp
64 lines (53 loc) · 1.48 KB
/
EventQueue.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#ifndef EVENTQUEUE_HPP
#define EVENTQUEUE_HPP
#include <array>
/**
* @brief The EventQueue class uses a ring buffer to store events. You can always push, but once you fill your buffer
* completely, you loose all events currently stored.
*/
// TODO "loose all events"? more like "begin overwriting"? which ones?
template <class T, unsigned int size = 10>
class EventQueue
{
public:
EventQueue()
: writePos{ringBuffer.begin()}
, readPos{ringBuffer.begin()}
{}
/**
* @brief push will add new events to the buffer, possibly overwriting existing ones.
*/
void push(T const& event)
{
*writePos = event;
writePos++;
if(writePos == ringBuffer.end())
writePos = ringBuffer.begin();
}
bool hasEvent() const { return writePos != readPos; }
/**
* @brief get writes the current event (if any) to the parameter, pops it and returns true iff there was an event.
*/
bool get(T& event)
{
if(!hasEvent())
return false;
event = *readPos;
pop();
return true;
}
void pop()
{
if(not hasEvent())
return;
readPos++;
if(readPos == ringBuffer.end())
readPos = ringBuffer.begin();
}
void clear() { readPos = writePos; }
private:
std::array<T, size> ringBuffer;
typename decltype(ringBuffer)::iterator writePos;
typename decltype(ringBuffer)::iterator readPos;
};
#endif // EVENTQUEUE_HPP