forked from amaurial/mergCanBus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircularBuffer.cpp
96 lines (88 loc) · 1.65 KB
/
CircularBuffer.cpp
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
#include "CircularBuffer.h"
/** \brief
* Constructor
* Basically set the initial values of the internal variables.
*/
CircularBuffer::CircularBuffer()
{
tail=0;
op=0;
pos=0;
entries=0;
}
/** \brief
* Destructor
*/
/**< */
CircularBuffer::~CircularBuffer()
{
//dtor
}
/** \brief
* Add a message of the _msgSize size to the buffer.
* \param buffer
* \return False in case the buffer is being writing else return True.
*
*/
bool CircularBuffer::put(byte* buffer){
if (op==0){
op=1;//writing
}
else{
return false;
}
if (tail>=CIRCULARBUFFER_SIZE){
tail=0;
}
for (int i=0;i<_msgSize;i++){
_buf[tail]=buffer[i];
tail++;
entries++;
}
if (entries>CIRCULARBUFFER_SIZE){
incPos();
entries=CIRCULARBUFFER_SIZE;
}
op=0;
return true;
}
/** \brief Put the next message to the buffer.
*
* \param buffer. Buffer that will receive the message.
* \return Return False if the buffer is being reading or if the buffer is empty. Else returns True.
*
*/
bool CircularBuffer::get(byte* buffer){
if (op==0){
op=1;//reading
}
else{
return false;
}
if (entries<1){
op=0;
return false;
}
if (pos>=CIRCULARBUFFER_SIZE){
pos=0;
}
// if ((pos+1)>=tail){
// return false;//nothing to read.
// }
for (int i=0;i<_msgSize;i++){
buffer[i]=_buf[pos];
pos++;
entries--;
}
op=0;
return true;
}
/** \brief Advance the head position.
*
*/
void CircularBuffer::incPos(){
pos=pos+_msgSize;
if (pos>=CIRCULARBUFFER_SIZE){
pos=0;
}
}