-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueRingBuffer.h
90 lines (77 loc) · 1.4 KB
/
QueueRingBuffer.h
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#ifndef QUEUERINGBUFFER_H
#define QUEUERINGBUFFER_H
#include <stdint.h>
template <uint16_t size> class QueueRingBuffer
{
public:
QueueRingBuffer() {
len = 0;
offset = 0;
}
uint16_t getContentLen() {
return len;
}
void enqueue(uint8_t val) {
uint16_t index = (offset + len) % size;
buffer[index] = val;
if (len < size) {
len++;
}
else { //overwrite old data
offset = (offset + 1) % size;
}
}
uint8_t dequeue() {
if (len > 0) {
uint8_t retval = buffer[offset];
offset = (offset + 1) % size;
len--;
return retval;
}
return 0;
}
void clear() {
offset = 0;
len = 0;
}
void push(uint8_t val) {
enqueue(val);
}
uint8_t pop() {
if (len > 0) {
uint8_t retval = buffer[(offset + len - 1) % size];
len--;
return retval;
}
return 0;
}
uint8_t peekBottom(uint16_t peekOffset = 0) {
if (peekOffset < len) {
uint16_t index = (offset + peekOffset) % size;
return buffer[index];
}
return 0;
}
uint8_t peekTop(uint16_t peekOffset = 0) {
if (peekOffset < len) {
uint16_t index = (offset + len - peekOffset) % size;
return buffer[index];
}
return 0;
}
void set(uint16_t index, uint8_t value) {
index = (offset + index) % size;
buffer[index] = value;
}
uint16_t getSize() {
return size;
}
uint8_t* getBuffer() {
return buffer;
}
private:
uint16_t offset;
uint16_t len;
uint8_t buffer[size];
};
#endif // !QUEUERINGBUFFER_H