forked from Zidit/partyhat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircular_buffer.h
85 lines (66 loc) · 1.45 KB
/
circular_buffer.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
#ifndef CIRCULAR_BUFFER_H_INCLUDED
#define CIRCULAR_BUFFER_H_INCLUDED
#include "util/atomic.h"
/// few notes:
/// -capacity must be 2, 4, 8, 16, 32, 64, 128 or 256
/// -buffer is not protected against overflow, it's up to user to read buffer frequently enough
template<class T, uint8_t capacity>
class circularBuffer {
public:
circularBuffer() : tail(0), count(0)
{
}
uint8_t isEmpty()
{
return count == 0;
}
uint8_t isFull()
{
return count == capacity;
}
uint8_t size()
{
return count;
}
uint8_t getCapacity()
{
return capacity;
}
T read()
{
T tmp;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
uint8_t t = tail;
tmp = data[t];
t++;
t &= capacity - 1;
tail = t;
count--;
}
return tmp;
}
void write(const T c)
{
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
uint8_t head;
head = tail + count;
head &= capacity - 1;
data[head] = c;
count++;
}
}
T peak()
{
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
return data[tail];
}
}
private:
volatile uint8_t tail;
volatile uint8_t count;
T data[capacity];
};
#endif // CIRCULAR_BUFFER_H_INCLUDED