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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//! Lock-free style ring buffer for streaming I/O.
//!
//! Provides a generic circular buffer and a byte-specialised variant
//! with slice-oriented push/pop helpers for use in streaming pipelines.
#![allow(dead_code)]
/// A circular (ring) buffer with fixed capacity.
///
/// Items are stored in a pre-allocated `Vec<Option<T>>`. `push` fails when
/// the buffer is full; `pop` removes and returns the oldest item.
pub struct RingBuffer<T> {
data: Vec<Option<T>>,
head: usize,
tail: usize,
capacity: usize,
len: usize,
}
impl<T> RingBuffer<T> {
/// Create a new ring buffer with the given capacity.
///
/// # Panics
///
/// Panics if `capacity` is zero.
pub fn new(capacity: usize) -> Self {
assert!(capacity > 0, "RingBuffer capacity must be > 0");
let mut data = Vec::with_capacity(capacity);
for _ in 0..capacity {
data.push(None);
}
Self {
data,
head: 0,
tail: 0,
capacity,
len: 0,
}
}
/// Push an item onto the back of the buffer.
///
/// Returns `false` if the buffer is full and the item was not inserted.
pub fn push(&mut self, item: T) -> bool {
if self.is_full() {
return false;
}
self.data[self.tail] = Some(item);
self.tail = (self.tail + 1) % self.capacity;
self.len += 1;
true
}
/// Remove and return the oldest item from the front of the buffer.
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
return None;
}
let item = self.data[self.head].take();
self.head = (self.head + 1) % self.capacity;
self.len -= 1;
item
}
/// Peek at the next item without removing it.
#[must_use]
pub fn peek(&self) -> Option<&T> {
if self.is_empty() {
return None;
}
self.data[self.head].as_ref()
}
/// Number of items currently in the buffer
#[must_use]
pub fn len(&self) -> usize {
self.len
}
/// Returns `true` if the buffer contains no items
#[must_use]
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Returns `true` if the buffer is at capacity
#[must_use]
pub fn is_full(&self) -> bool {
self.len == self.capacity
}
/// Maximum number of items the buffer can hold
#[must_use]
pub fn capacity(&self) -> usize {
self.capacity
}
/// Remove all items from the buffer
pub fn clear(&mut self) {
for slot in &mut self.data {
*slot = None;
}
self.head = 0;
self.tail = 0;
self.len = 0;
}
}
impl<T: Clone> RingBuffer<T> {
/// Collect all items into a `Vec` without removing them (front-to-back order)
#[must_use]
pub fn to_vec(&self) -> Vec<T> {
let mut result = Vec::with_capacity(self.len);
let mut idx = self.head;
for _ in 0..self.len {
if let Some(ref item) = self.data[idx] {
result.push(item.clone());
}
idx = (idx + 1) % self.capacity;
}
result
}
}
// ──────────────────────────────────────────────────────────────────────────────
// Byte-specialised ring buffer
// ──────────────────────────────────────────────────────────────────────────────
/// A ring buffer specialised for `u8` data with slice-oriented helpers.
pub struct ByteRingBuffer {
inner: RingBuffer<u8>,
}
impl ByteRingBuffer {
/// Create a new byte ring buffer with the given capacity in bytes
#[must_use]
pub fn new(capacity: usize) -> Self {
Self {
inner: RingBuffer::new(capacity),
}
}
/// Push as many bytes from `data` as will fit.
///
/// Returns the number of bytes actually pushed.
pub fn push_slice(&mut self, data: &[u8]) -> usize {
let mut pushed = 0;
for &byte in data {
if !self.inner.push(byte) {
break;
}
pushed += 1;
}
pushed
}
/// Pop exactly `n` bytes, returning `None` if fewer than `n` are available.
pub fn pop_exact(&mut self, n: usize) -> Option<Vec<u8>> {
if self.inner.len() < n {
return None;
}
let mut result = Vec::with_capacity(n);
for _ in 0..n {
if let Some(b) = self.inner.pop() {
result.push(b);
}
}
Some(result)
}
/// Push a single byte; returns `false` if the buffer is full
pub fn push(&mut self, byte: u8) -> bool {
self.inner.push(byte)
}
/// Pop a single byte
pub fn pop(&mut self) -> Option<u8> {
self.inner.pop()
}
/// Peek at the next byte without removing it
#[must_use]
pub fn peek(&self) -> Option<&u8> {
self.inner.peek()
}
/// Number of bytes currently stored
#[must_use]
pub fn len(&self) -> usize {
self.inner.len()
}
/// Returns `true` if no bytes are stored
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
/// Returns `true` if the buffer is at capacity
#[must_use]
pub fn is_full(&self) -> bool {
self.inner.is_full()
}
/// Maximum byte capacity
#[must_use]
pub fn capacity(&self) -> usize {
self.inner.capacity()
}
}
#[cfg(test)]
mod tests {
use super::*;
// ── RingBuffer<u32> ───────────────────────────────────────────────────────
#[test]
fn test_ring_new_empty() {
let rb: RingBuffer<u32> = RingBuffer::new(4);
assert!(rb.is_empty());
assert!(!rb.is_full());
assert_eq!(rb.len(), 0);
assert_eq!(rb.capacity(), 4);
}
#[test]
fn test_ring_push_and_pop_fifo() {
let mut rb: RingBuffer<u32> = RingBuffer::new(4);
assert!(rb.push(1));
assert!(rb.push(2));
assert!(rb.push(3));
assert_eq!(rb.pop(), Some(1));
assert_eq!(rb.pop(), Some(2));
assert_eq!(rb.pop(), Some(3));
assert_eq!(rb.pop(), None);
}
#[test]
fn test_ring_full_returns_false() {
let mut rb: RingBuffer<u32> = RingBuffer::new(2);
assert!(rb.push(10));
assert!(rb.push(20));
assert!(rb.is_full());
assert!(!rb.push(30)); // must fail
}
#[test]
fn test_ring_peek_does_not_remove() {
let mut rb: RingBuffer<u32> = RingBuffer::new(4);
rb.push(42);
assert_eq!(rb.peek(), Some(&42));
assert_eq!(rb.len(), 1);
assert_eq!(rb.pop(), Some(42));
}
#[test]
fn test_ring_wrap_around() {
let mut rb: RingBuffer<u32> = RingBuffer::new(3);
rb.push(1);
rb.push(2);
rb.push(3);
rb.pop(); // remove 1
rb.push(4); // wrap
assert_eq!(rb.pop(), Some(2));
assert_eq!(rb.pop(), Some(3));
assert_eq!(rb.pop(), Some(4));
}
#[test]
fn test_ring_clear() {
let mut rb: RingBuffer<u32> = RingBuffer::new(4);
rb.push(1);
rb.push(2);
rb.clear();
assert!(rb.is_empty());
assert_eq!(rb.len(), 0);
}
#[test]
fn test_ring_to_vec() {
let mut rb: RingBuffer<u32> = RingBuffer::new(4);
rb.push(10);
rb.push(20);
rb.push(30);
assert_eq!(rb.to_vec(), vec![10, 20, 30]);
}
// ── ByteRingBuffer ────────────────────────────────────────────────────────
#[test]
fn test_byte_ring_push_slice_full() {
let mut brb = ByteRingBuffer::new(4);
let pushed = brb.push_slice(&[1, 2, 3, 4, 5]);
assert_eq!(pushed, 4); // only 4 fit
assert!(brb.is_full());
}
#[test]
fn test_byte_ring_pop_exact_success() {
let mut brb = ByteRingBuffer::new(8);
brb.push_slice(&[10, 20, 30, 40]);
let out = brb.pop_exact(3).unwrap();
assert_eq!(out, vec![10, 20, 30]);
assert_eq!(brb.len(), 1);
}
#[test]
fn test_byte_ring_pop_exact_insufficient() {
let mut brb = ByteRingBuffer::new(8);
brb.push_slice(&[1, 2]);
assert!(brb.pop_exact(5).is_none());
// Data should still be there
assert_eq!(brb.len(), 2);
}
#[test]
fn test_byte_ring_peek() {
let mut brb = ByteRingBuffer::new(8);
brb.push(0xAB);
assert_eq!(brb.peek(), Some(&0xAB));
assert_eq!(brb.len(), 1);
}
#[test]
fn test_byte_ring_wrap_around() {
let mut brb = ByteRingBuffer::new(4);
brb.push_slice(&[1, 2, 3, 4]);
brb.pop();
brb.pop();
let pushed = brb.push_slice(&[5, 6]);
assert_eq!(pushed, 2);
assert_eq!(brb.pop(), Some(3));
assert_eq!(brb.pop(), Some(4));
assert_eq!(brb.pop(), Some(5));
assert_eq!(brb.pop(), Some(6));
}
}