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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#![no_std]
#![deny(warnings)]
#![allow(dead_code)]
pub struct PingpongBuffer<const N: usize> {
buffer_a: [u8; N],
buffer_b: [u8; N],
active_index: usize,
active_toggle: bool,
is_reserve_full: bool,
}
impl<const N: usize> PingpongBuffer<N> {
pub const DEFAULT: PingpongBuffer<N> = PingpongBuffer::<N> {
buffer_a: [0; N],
buffer_b: [0; N],
active_index: 0,
active_toggle: true,
is_reserve_full: false,
};
pub fn is_empty(&self) -> bool {
self.active_index == 0
}
pub fn is_half_full(&self) -> bool {
self.active_index >= (N / 2)
}
pub fn clear(&mut self) {
self.buffer_a = [0; N];
self.buffer_b = [0; N];
self.active_index = 0;
self.active_toggle = true;
self.is_reserve_full = false;
}
pub fn flush(&mut self) -> ([u8; N], usize) {
let buff = if self.active_toggle {
&self.buffer_a
} else {
&self.buffer_b
};
let mut data: [u8; N] = [0; N];
let remainder = self.active_index;
data[0..remainder].copy_from_slice(&buff[0..remainder]);
self.active_index = 0;
(data, remainder)
}
pub fn read(&mut self) -> Option<&[u8; N]> {
if !self.is_reserve_full {
return Option::None;
}
let buff = if self.active_toggle {
Option::Some(&self.buffer_b)
} else {
Option::Some(&self.buffer_a)
};
self.is_reserve_full = false;
return buff;
}
pub fn append(&mut self, data: &[u8]) -> bool {
let buff = if self.active_toggle {
&mut self.buffer_a
} else {
&mut self.buffer_b
};
let capacity = buff.len() - self.active_index;
let start = self.active_index;
for i in 0..data.len() {
if i >= capacity {
break;
}
buff[start + i] = data[i];
self.active_index += 1;
}
let transferred = if capacity > data.len() {
data.len()
} else {
capacity
};
if self.active_index == buff.len() {
if self.is_reserve_full {
panic!("The reserve buffer cannot be written to as it is still full. Clear it by reading the data");
}
self.is_reserve_full = true;
self.active_index = 0;
self.active_toggle = !self.active_toggle;
if transferred != data.len() {
let buff = if self.active_toggle {
&mut self.buffer_a
} else {
&mut self.buffer_b
};
let remainder = data.len() - transferred;
if remainder > N {
panic!("The data is larger than the double buffer can process");
}
for i in 0..remainder {
buff[i] = data[transferred + i];
self.active_index += 1;
}
}
return true;
}
return false;
}
}