-
Notifications
You must be signed in to change notification settings - Fork 0
/
RingBuffer.h
103 lines (87 loc) · 1.55 KB
/
RingBuffer.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
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* RingBuffer.h
*
* Created: 23-Sep-20 16:02:22
* Author: Davod
*/
#ifndef RINGBUFFER_H_
#define RINGBUFFER_H_
template <uint8_t BUFFER_SIZE>
class RingBuffer
{
public:
uint8_t Read();
uint8_t Peek();
void Write(uint8_t in);
uint8_t Count();
void Flush();
const uint8_t length = BUFFER_SIZE;
//RingBuffer();
private:
uint8_t buffer[BUFFER_SIZE];
uint8_t head = 0;
uint8_t tail = 0;
};
/*
template <uint8_t BUFFER_SIZE>
RingBuffer<BUFFER_SIZE>::RingBuffer(){
tail = 0;
head = 0;
length = BUFFER_SIZE;
}
*/
//Read the next byte in buffer
template <uint8_t BUFFER_SIZE>
uint8_t RingBuffer<BUFFER_SIZE>::Read(){
if (Count() > 0)
{
tail++;
if (tail >= length)
{
tail = 0;
}
return buffer[tail];
}
return 0;
}
//Read next byte without incrementing pointers
template <uint8_t BUFFER_SIZE>
uint8_t RingBuffer<BUFFER_SIZE>::Peek(){
uint8_t tempTail = tail + 1;
if (tempTail >= length)
{
tempTail = 0;
}
return buffer[tempTail];
}
//Write a byte to the buffer
template <uint8_t BUFFER_SIZE>
void RingBuffer<BUFFER_SIZE>::Write(uint8_t in){
if (Count() < length - 2)
{
head++;
if (head >= length)
{
head = 0;
}
buffer[head] = in;
}
}
//Returns how many elements are in the buffer
template <uint8_t BUFFER_SIZE>
uint8_t RingBuffer<BUFFER_SIZE>::Count(){
//Compensate for overflows
if (head >= tail)
{
return (head - tail);
} else {
return (head - tail + length);
}
}
//Resets buffer
template <uint8_t BUFFER_SIZE>
void RingBuffer<BUFFER_SIZE>::Flush(){
tail = 0;
head = 0;
}
#endif /* RINGBUFFER_H_ */