Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/rust/comment_heavy.txt

2.1 KiB, 1 run

created by r1870400018:12042, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// This module implements a simple ring buffer for fixed-size messages.
2//
3// The buffer is backed by a contiguous allocation. Reads and writes
4// wrap around the end of the buffer. The implementation does not
5// support concurrent access; callers must synchronise externally.
6//
7// Design constraints:
8// - Fixed capacity, set at construction.
9// - Messages are fixed-size byte arrays.
10// - No heap allocation after construction.
11// - O(1) push and pop.
12
13/// Ring buffer for fixed-size messages.
14pub struct RingBuffer {
15 // The backing storage.
16 buf: Vec<u8>,
17 // Size of each message in bytes.
18 msg_size: usize,
19 // Read position (index into buf).
20 read_pos: usize,
21 // Write position (index into buf).
22 write_pos: usize,
23 // Number of messages currently stored.
24 count: usize,
25 // Maximum number of messages.
26 capacity: usize,
27}
28
29impl RingBuffer {
30 /// Create a ring buffer that holds `capacity` messages of
31 /// `msg_size` bytes each.
32 pub fn new(capacity: usize, msg_size: usize) -> Self {
33 Self {
34 buf: vec![0u8; capacity * msg_size],
35 msg_size,
36 read_pos: 0,
37 write_pos: 0,
38 count: 0,
39 capacity,
40 }
41 }
42
43 /// Push a message. Returns false if the buffer is full.
44 pub fn push(&mut self, msg: &[u8]) -> bool {
45 if msg.len() != self.msg_size || self.count == self.capacity {
46 return false;
47 }
48 // Copy message into the write slot.
49 let start = self.write_pos * self.msg_size;
50 self.buf[start..start + self.msg_size].copy_from_slice(msg);
51 // Advance write position, wrapping around.
52 self.write_pos = (self.write_pos + 1) % self.capacity;
53 self.count += 1;
54 true
55 }
56
57 /// Pop a message. Returns None if the buffer is empty.
58 pub fn pop(&mut self) -> Option<Vec<u8>> {
59 if self.count == 0 {
60 return None;
61 }
62 let start = self.read_pos * self.msg_size;
63 let msg = self.buf[start..start + self.msg_size].to_vec();
64 self.read_pos = (self.read_pos + 1) % self.capacity;
65 self.count -= 1;
66 Some(msg)
67 }
68}