Bit-Masking Ring Buffer

Documentation Crates.io License

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.

Note, this crate has not been tested in a production environment yet. If you find any bugs, especially ones pertaining to memory safety, please let me know!

Example

```rust use bitmaskring_buf::{BitMaskRingBuf, BitMaskRingBufRef};

// Create a ring buffer with type u32. The data will be // initialized with the default value (0 in this case). // The actual capacity will be set to the next highest // power of 2 if the given capacity is not already // a power of 2. let mut rb = BitMaskRingBuf::::fromcapacity(3); asserteq!(rb.capacity(), 4);

// read/write to buffer by indexing 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 points 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. Only // the latest data will be copied. 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 retreiving 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 = BitMaskRingBufRef::new(&mut stackdata); rbref[-4] = 5; asserteq!(rbref[0], 5); asserteq!(rbref[1], 1); asserteq!(rbref[2], 2); asserteq!(rbref[3], 3); ```