Bit-Masking Ring Buffer
A fast ring buffer implementation with cheap and safe indexing written in Rust. It works by bit-masking an integer index to get the corresponding index in an array/vec whose length is a power of 2. This is best used when indexing the buffer with an isize
value. Copies/reads with slices are implemented with memcpy. This is most useful for high performance algorithms such as audio DSP.
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.
If your use case needs a buffer with a length that is not a power of 2, and the performance of indexing individual elements one at a time does not matter, then take a look at my crate slice_ring_buf
.
Installation
Add bit_mask_ring_buf
as a dependency in your Cargo.toml
:
= 0.5
Example
use ;
// 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 = from_len;
assert_eq!;
// Read/write to buffer by indexing with an `isize`.
rb = 0;
rb = 1;
rb = 2;
rb = 3;
// Cheaply wrap when reading/writing outside of bounds.
assert_eq!;
assert_eq!;
// Memcpy into slices at arbitrary `isize` indexes
// and length.
let mut read_buffer = ;
rb.read_into;
assert_eq!;
// 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.write_latest;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// Read/write by retrieving slices directly.
let = rb.as_slices_len;
assert_eq!;
assert_eq!;
// Aligned/stack data may also be used.
let mut stack_data = ;
let mut rb_ref = new;
rb_ref = 5;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// Get linear interpolation on floating point buffers.
let mut rb = from_len;
rb = 0.0;
rb = 2.0;
rb = 4.0;
rb = 6.0;
assert!;
assert!;
assert!;