-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathuartbuffer.cpp
More file actions
108 lines (97 loc) · 2.04 KB
/
Copy pathuartbuffer.cpp
File metadata and controls
108 lines (97 loc) · 2.04 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "uartbuffer.h"
#include <stdlib.h>
#include <string.h>
/*
implement a simple ringbuffer of bytes
*/
UARTBuffer::UARTBuffer(uint32_t _size)
{
size = _size;
buf = new uint8_t[size];
allocated = true;
head = tail = 0;
}
UARTBuffer::UARTBuffer(uint8_t *_buf, uint32_t _size)
{
size = _size;
buf = _buf;
head = tail = 0;
}
UARTBuffer::~UARTBuffer(void)
{
if (allocated) {
delete [] buf;
}
}
uint32_t UARTBuffer::available(void) const
{
uint32_t _tail;
return ((head > (_tail=tail))? (size - head) + _tail: _tail - head);
}
uint32_t UARTBuffer::space(void) const
{
uint32_t _head;
return (((_head=head) > tail)?(_head - tail) - 1:((size - tail) + _head) - 1);
}
bool UARTBuffer::empty(void) const
{
return head == tail;
}
uint32_t UARTBuffer::write(const uint8_t *data, uint32_t len)
{
if (len > space()) {
len = space();
}
if (len == 0) {
return 0;
}
if (tail+len <= size) {
// perform as single memcpy
memcpy(&buf[tail], data, len);
tail = (tail + len) % size;
return len;
}
// perform as two memcpy calls
uint32_t n = size - tail;
if (n > len) {
n = len;
}
memcpy(&buf[tail], data, n);
tail = (tail + n) % size;
data += n;
n = len - n;
if (n > 0) {
memcpy(&buf[tail], data, n);
tail = (tail + n) % size;
}
return len;
}
uint32_t UARTBuffer::read(uint8_t *data, uint32_t len)
{
if (len > available()) {
len = available();
}
if (len == 0) {
return 0;
}
if (head+len <= size) {
// perform as single memcpy
memcpy(data, &buf[head], len);
head = (head + len) % size;
return len;
}
// perform as two memcpy calls
uint32_t n = size - head;
if (n > len) {
n = len;
}
memcpy(data, &buf[head], n);
head = (head + n) % size;
data += n;
n = len - n;
if (n > 0) {
memcpy(data, &buf[head], n);
head = (head + n) % size;
}
return len;
}