-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircularBuffer.h
67 lines (52 loc) · 1.13 KB
/
CircularBuffer.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
/* EspSoftSerial receiver
Scott Day 2015
github.com/scottwday/EspSoftSerial
*/
#ifndef CIRCULARBUFFER_H
#define CIRCULARBUFFER_H
template <typename T, unsigned int LEN>
class CircularBuffer
{
private:
const unsigned int _capacity = LEN;
//Index of the oldest element
unsigned int _out = 0;
//The next empty index we can write to
unsigned int _nextIn = 0;
T _buffer[LEN];
public:
void reset()
{
_nextIn = 0;
_out = 0;
}
bool write(T value)
{
_buffer[_nextIn] = value;
_nextIn = (_nextIn+1) % LEN;
//If we've overwritten the first byte then move up the out value to keep overwriting the oldest stuff
if (_nextIn == _out)
_out = (_out+1) % LEN;
}
bool read(T& value)
{
if (_nextIn == _out)
return false;
value = _buffer[_out];
_out = (_out+1) % LEN;
return true;
}
T read()
{
if (_nextIn == _out)
return 0;
T value = _buffer[_out];
_out = (_out+1) % LEN;
return value;
}
unsigned int size()
{
unsigned int len = (_nextIn - _out) & 0x7FFF;
}
};
#endif