-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSafeBuffer.cpp
More file actions
84 lines (69 loc) · 1.41 KB
/
SafeBuffer.cpp
File metadata and controls
84 lines (69 loc) · 1.41 KB
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
/*
* SafeBuffer.cpp
* File implementing a simple, safe character buffer
* Author: Alex St. Clair
* July 2019
*/
#include "SafeBuffer.h"
SafeBuffer::SafeBuffer(uint8_t * buf_pointer, uint16_t buf_size)
{
buffer = buf_pointer;
buffer_size = buf_size;
num_elements = 0;
head = 0;
tail = 0;
}
uint16_t SafeBuffer::NumElements()
{
return num_elements;
}
bool SafeBuffer::IsEmpty()
{
return num_elements == 0;
}
bool SafeBuffer::IsFull()
{
return num_elements == buffer_size;
}
bool SafeBuffer::Push(uint8_t item)
{
bool success = false;
if (IsFull()) {
success = false;
} else {
buffer[tail] = item;
tail = (tail + 1) % buffer_size;
num_elements++;
success = true;
}
return success;
}
bool SafeBuffer::Peek(uint8_t * item)
{
bool success = false;
if (IsEmpty()) {
success = false;
} else {
*item = buffer[head];
success = true;
}
return success;
}
bool SafeBuffer::Pop(uint8_t * item)
{
bool success = false;
if (IsEmpty()) {
success = false;
} else {
*item = buffer[head];
head = (head + 1) % buffer_size;
num_elements--;
success = true;
}
return success;
}
void SafeBuffer::Clear()
{
num_elements = 0;
tail = head;
}