-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFIFOqueue.cpp
101 lines (77 loc) · 2.34 KB
/
FIFOqueue.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
97
98
99
100
101
/*file: FIFOqueue.cpp
*---------------------------------------------------------------------
*
* fast and compact FIFO buffer queue class
*
* class definitions
*
* Author: Dave Harris. Andover, UK. © Dave Harris 2021
*/
#include "FIFOqueue.h"
FIFOqueue::FIFOqueue( uint8_t len ) /* Constructor method */
{
buflen = len; /* buflen = 8, 16, 32, 64, 128 */
val = 0;
for( uint8_t i = 0; i < 8; i++ ) /* count the bits in buflen */
{
val += ( len >> i ) & 0b00000001; /* shift & expose just LSB */
}
if( ( val != 1 ) || ( buflen < 8 ) ) /* is not a valid length */
{
buflen = 8; /* default buffer length */
errorCount++; /* fail silently */
}
MASK = buflen - 1; /* buflen = 8, 01000, so mask = 00111 */
buffer = new uint8_t[ buflen ]; /* make a new array */
};
uint8_t FIFOqueue::length()
{
return MASK; /* mask = buflen -1 (is an always empty byte)*/
};
void FIFOqueue::put( uint8_t v )
{
noInterrupts();
nexthead = ( head + 1 ) & MASK; /* increment & overflow to 0 */
if( nexthead == tail ) /* queue is full! */
{ /* Caller should check emptySlots() > 0 */
interrupts();
errorCount++; /* silently fail. */
return;
}
buffer[head] = v; /* add the value */
head = nexthead; /* update the head index */
interrupts();
};
uint8_t FIFOqueue::get()
{
noInterrupts();
if( head == tail ) /* queue is empty! */
{ /* Caller should check available() > 0 */
interrupts();
errorCount++; /* silently fail. */
return 255;
}
val = buffer[tail];
tail = ( tail + 1 ) & MASK; /* increment and overflow to 0 */
interrupts();
return val;
};
uint8_t FIFOqueue::available()
{
noInterrupts();
if( head >= tail )
{
val = head - tail;
}
else
{
val = MASK + 1 - tail + head;
}
interrupts();
return val;
};
uint8_t FIFOqueue::emptySlots()
{
return MASK - available(); /* mask = buflen -1 */
}
/* ---------------------- EoF FIFOqueue.cpp ---------------------- */