A ring buffer implementation with cheap indexing written in Rust.
Note, this crate is only beneficial if your algorithm indexes elements one at a time and has buffer sizes that are always a power of two. If your algorithm instead reads chunks of data as slices or requires buffer sizes that are not a power of two, then check out my crate [slice_ring_buf
].
This crate has no consumer/producer logic, and is meant to be used as a raw data structure or a base for other data structures.
Add bit_mask_ring_buf
as a dependency in your Cargo.toml
:
toml
bit_mask_ring_buf = 0.5
```rust use bitmaskring_buf::{BMRingBuf, BMRingBufRef};
// Create a ring buffer with type u32. The data will be
// initialized with the default value (0 in this case).
// The actual length will be set to the next highest
// power of 2 if the given length is not already
// a power of 2.
let mut rb = BMRingBuf::
// Read/write to buffer by indexing with an isize
.
rb[0] = 0;
rb[1] = 1;
rb[2] = 2;
rb[3] = 3;
// Cheaply wrap when reading/writing outside of bounds. asserteq!(rb[-1], 3); asserteq!(rb[10], 2);
// Memcpy into slices at arbitrary isize
indexes
// and length.
let mut readbuffer = [0u32; 7];
rb.readinto(&mut readbuffer, 2);
asserteq!(read_buffer, [2, 3, 0, 1, 2, 3, 0]);
// Memcpy data from a slice into the ring buffer at
// arbitrary isize
indexes. Earlier data will not be
// copied if it will be overwritten by newer data,
// avoiding unecessary memcpy's. The correct placement
// of the newer data will still be preserved.
rb.writelatest(&[0, 2, 3, 4, 1], 0);
asserteq!(rb[0], 1);
asserteq!(rb[1], 2);
asserteq!(rb[2], 3);
assert_eq!(rb[3], 4);
// Read/write by retrieving slices directly. let (s1, s2) = rb.assliceslen(1, 4); asserteq!(s1, &[2, 3, 4]); asserteq!(s2, &[1]);
// Aligned/stack data may also be used. let mut stackdata = [0u32, 1, 2, 3]; let mut rbref = BMRingBufRef::new(&mut stackdata); rbref[-4] = 5; asserteq!(rbref[0], 5); asserteq!(rbref[1], 1); asserteq!(rbref[2], 2); asserteq!(rbref[3], 3);
// Get linear interpolation on floating point buffers.
let mut rb = BMRingBuf::