-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircbuff.hpp
59 lines (49 loc) · 1.28 KB
/
circbuff.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
// A simple circular buffer/queue structure
template <typename T, unsigned int BuffSize>
class CircularBuffer {
public:
CircularBuffer() : head(0), tail(0) {}
void add(const T& t) {
buf[head] = t;
lastIdx_ = head;
inc(head);
}
void remove() {
if (head != tail) {
inc(tail);
}
}
T& peek() {
return buf[tail];
}
// The index of the entry returned by 'peek'
unsigned int currIdx() const { return tail; }
// The index of the last entry added to the queue
unsigned int lastIdx() const { return lastIdx_; }
unsigned int size() {
if (head >= tail) {
return head - tail;
} else {
return head + BuffSize - tail;
}
}
bool empty() {
return head == tail;
}
void clear() {
tail = head;
}
void setTo(const T& t) {
clear();
add(t);
}
private:
void inc(unsigned int& x) {
x++;
if (x >= BuffSize) {
x = 0;
}
}
T buf[BuffSize];
unsigned int head, tail, lastIdx_;
};