dasp_ring_buffer

Struct Bounded

Source
pub struct Bounded<S> { /* private fields */ }
Expand description

A ring buffer with an upper bound on its length.

AKA Circular buffer, cyclic buffer, FIFO queue.

Elements can be pushed to the back of the buffer and popped from the front.

Elements must be Copy due to the behaviour of the push and pop methods. If you require working with non-Copy elements, the std VecDeque type may be better suited.

A Bounded ring buffer can be created from any type providing a slice to use for pushing and popping elements.

fn main() {
    // From a fixed size array.
    dasp_ring_buffer::Bounded::from([0; 4]);

    // From a Vec.
    dasp_ring_buffer::Bounded::from(vec![0; 4]);

    // From a Boxed slice.
    dasp_ring_buffer::Bounded::from(vec![0; 3].into_boxed_slice());

    // From a mutably borrowed slice.
    let mut slice = [0; 4];
    dasp_ring_buffer::Bounded::from(&mut slice[..]);

    // An immutable ring buffer from an immutable slice.
    let slice = [0; 4];
    dasp_ring_buffer::Bounded::from(&slice[..]);
}

Implementations§

Source§

impl<S> Bounded<S>
where S: Slice, S::Element: Copy,

Source

pub fn from_full(data: S) -> Self

The same as the From implementation, but assumes that the given data is full of valid elements and initialises the ring buffer with a length equal to max_len.

fn main() {
    let mut rb = dasp_ring_buffer::Bounded::from_full([0, 1, 2, 3]);
    assert_eq!(rb.len(), rb.max_len());
    assert_eq!(rb.pop(), Some(0));
    assert_eq!(rb.pop(), Some(1));
    assert_eq!(rb.pop(), Some(2));
    assert_eq!(rb.pop(), Some(3));
    assert_eq!(rb.pop(), None);
}
Source

pub fn max_len(&self) -> usize

The maximum length that the Bounded buffer can be before pushing would overwrite the front of the buffer.

fn main() {
    let mut ring_buffer = dasp_ring_buffer::Bounded::from([0i32; 3]);
    assert_eq!(ring_buffer.max_len(), 3);
}
Source

pub fn len(&self) -> usize

The current length of the ring buffer.

fn main() {
    let mut ring_buffer = dasp_ring_buffer::Bounded::from([0i32; 3]);
    assert_eq!(ring_buffer.len(), 0);
}
Source

pub fn is_empty(&self) -> bool

Whether or not the ring buffer’s length is equal to 0.

Equivalent to self.len() == 0.

fn main() {
    let mut rb = dasp_ring_buffer::Bounded::from([0i32; 2]);
    assert!(rb.is_empty());
    rb.push(0);
    assert!(!rb.is_empty());
}
Source

pub fn is_full(&self) -> bool

Whether or not the ring buffer’s length is equal to the maximum length.

Equivalent to self.len() == self.max_len().

fn main() {
    let mut rb = dasp_ring_buffer::Bounded::from([0i32; 2]);
    assert!(!rb.is_full());
    rb.push(0);
    rb.push(1);
    assert!(rb.is_full());
}
Source

pub fn slices(&self) -> (&[S::Element], &[S::Element])

The start and end slices that make up the ring buffer.

These two slices chained together represent all elements within the buffer in order.

The first slice is always aligned contiguously behind the second slice.

fn main() {
    let mut ring_buffer = dasp_ring_buffer::Bounded::from([0i32; 4]);
    assert_eq!(ring_buffer.slices(), (&[][..], &[][..]));
    ring_buffer.push(1);
    ring_buffer.push(2);
    assert_eq!(ring_buffer.slices(), (&[1, 2][..], &[][..]));
    ring_buffer.push(3);
    ring_buffer.push(4);
    assert_eq!(ring_buffer.slices(), (&[1, 2, 3, 4][..], &[][..]));
    ring_buffer.push(5);
    ring_buffer.push(6);
    assert_eq!(ring_buffer.slices(), (&[3, 4][..], &[5, 6][..]));
}
Source

pub fn slices_mut(&mut self) -> (&mut [S::Element], &mut [S::Element])
where S: SliceMut,

The same as the slices method, but returns mutable slices instead.

Source

pub fn iter(&self) -> Chain<Iter<'_, S::Element>, Iter<'_, S::Element>>

Produce an iterator that yields a reference to each element in the buffer.

This method uses the slices method internally.

fn main() {
    let mut rb = dasp_ring_buffer::Bounded::from([0i32; 3]);
    assert_eq!(rb.iter().count(), 0);
    rb.push(1);
    rb.push(2);
    assert_eq!(rb.iter().cloned().collect::<Vec<_>>(), vec![1, 2]);
}
Source

pub fn iter_mut( &mut self, ) -> Chain<IterMut<'_, S::Element>, IterMut<'_, S::Element>>
where S: SliceMut,

Produce an iterator that yields a mutable reference to each element in the buffer.

This method uses the slices_mut method internally.

Source

pub fn get(&self, index: usize) -> Option<&S::Element>

Borrows the item at the given index.

Returns None if there is no element at the given index.

fn main() {
    let mut rb = dasp_ring_buffer::Bounded::from([0i32; 4]);
    assert_eq!(rb.get(1), None);
    rb.push(0);
    rb.push(1);
    assert_eq!(rb.get(1), Some(&1));
}
Source

pub fn get_mut(&mut self, index: usize) -> Option<&mut S::Element>
where S: SliceMut,

Mutably borrows the item at the given index.

Returns None if there is no element at the given index.

Source

pub fn push(&mut self, elem: S::Element) -> Option<S::Element>
where S: SliceMut,

Pushes the given element to the back of the buffer.

If the buffer length is currently the max length, this replaces the element at the front of the buffer and returns it.

If the buffer length is less than the max length, this pushes the element to the back of the buffer and increases the length of the buffer by 1. None is returned.

fn main() {
    let mut ring_buffer = dasp_ring_buffer::Bounded::from([0i32; 3]);
    assert_eq!(ring_buffer.push(1), None);
    assert_eq!(ring_buffer.push(2), None);
    assert_eq!(ring_buffer.len(), 2);
    assert_eq!(ring_buffer.push(3), None);
    assert_eq!(ring_buffer.len(), 3);
    assert_eq!(ring_buffer.push(4), Some(1));
    assert_eq!(ring_buffer.len(), 3);
}
Source

pub fn pop(&mut self) -> Option<S::Element>
where S: SliceMut,

Pop an element from the front of the ring buffer.

If the buffer is empty, this returns None.

fn main() {
    let mut rb = dasp_ring_buffer::Bounded::from_full([0, 1, 2]);
    assert_eq!(rb.len(), rb.max_len());
    assert_eq!(rb.pop(), Some(0));
    assert_eq!(rb.pop(), Some(1));
    assert_eq!(rb.push(3), None);
    assert_eq!(rb.pop(), Some(2));
    assert_eq!(rb.pop(), Some(3));
    assert_eq!(rb.pop(), None);
}
Source

pub fn drain(&mut self) -> DrainBounded<'_, S>

Produce an iterator that drains the ring buffer by popping each element one at a time.

Note that only elements yielded by DrainBounded::next will be popped from the ring buffer. That is, all non-yielded elements will remain in the ring buffer.

fn main() {
    let mut rb = dasp_ring_buffer::Bounded::from_full([0, 1, 2, 3]);
    assert_eq!(rb.drain().take(2).collect::<Vec<_>>(), vec![0, 1]);
    assert_eq!(rb.pop(), Some(2));
    assert_eq!(rb.pop(), Some(3));
    assert_eq!(rb.pop(), None);
}
Source

pub fn from_raw_parts(start: usize, len: usize, data: S) -> Self

Creates a Bounded ring buffer from its start index, length and data slice.

The maximum length of the Bounded ring buffer is assumed to the length of the given slice.

Note: Existing elements within the given data’s slice will not be dropped when overwritten by calls to push. Thus, it is safe for the slice to contain uninitialized elements when using this method.

Note: This method should only be necessary if you require specifying the start and initial len.

**Panic!**s if the following conditions are not met:

  • start < data.slice().len()
  • len <= data.slice().len()
Source

pub unsafe fn from_raw_parts_unchecked( start: usize, len: usize, data: S, ) -> Self

Creates a Bounded ring buffer from its start index, len and data slice.

This method is unsafe as there is no guarantee that either:

  • start < data.slice().len() or
  • len <= data.slice().len().
Source

pub unsafe fn into_raw_parts(self) -> (usize, usize, S)

Consumes the Bounded ring buffer and returns its parts:

  • The first usize is an index into the first element of the buffer.
  • The second usize is the length of the ring buffer.
  • S is the buffer data.

This method is unsafe as the returned data may contain uninitialised memory in the case that the ring buffer is not full.

Trait Implementations§

Source§

impl<S: Clone> Clone for Bounded<S>

Source§

fn clone(&self) -> Bounded<S>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<S: Debug> Debug for Bounded<S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<S> From<S> for Bounded<S>
where S: Slice, S::Element: Copy,

Source§

fn from(data: S) -> Self

Construct a Bounded ring buffer from the given data slice.

**Panic!**s if the given data buffer is empty.

Source§

impl<S, T> FromIterator<T> for Bounded<S>
where S: Slice<Element = T> + FromIterator<T>, T: Copy,

Source§

fn from_iter<I>(iter: I) -> Self
where I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
Source§

impl<S: Hash> Hash for Bounded<S>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<S> Index<usize> for Bounded<S>
where S: Slice, S::Element: Copy,

Source§

type Output = <S as Slice>::Element

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<S> IndexMut<usize> for Bounded<S>
where S: SliceMut, S::Element: Copy,

Source§

fn index_mut(&mut self, index: usize) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<S: PartialEq> PartialEq for Bounded<S>

Source§

fn eq(&self, other: &Bounded<S>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<S: Copy> Copy for Bounded<S>

Source§

impl<S: Eq> Eq for Bounded<S>

Source§

impl<S> StructuralPartialEq for Bounded<S>

Auto Trait Implementations§

§

impl<S> Freeze for Bounded<S>
where S: Freeze,

§

impl<S> RefUnwindSafe for Bounded<S>
where S: RefUnwindSafe,

§

impl<S> Send for Bounded<S>
where S: Send,

§

impl<S> Sync for Bounded<S>
where S: Sync,

§

impl<S> Unpin for Bounded<S>
where S: Unpin,

§

impl<S> UnwindSafe for Bounded<S>
where S: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.