RingBuffer

Struct RingBuffer 

Source
pub struct RingBuffer<T> { /* private fields */ }
Expand description

A queue that also allows direct index addressing.

This queue trades some features from VecDeque in the std library for the feature of direct indexing. Instead of returning (), push_back returns the index of the new element in the buffer. Methods like get_absolute can then be used for element access.

The index returned by push_back or used by get_absolute may not be the actual index but a higher number that gets wrapped around internally so the indices are still valid after elements get moved around by expanding or shrinking the container.

The features not present in RingBuffer whereas present in VecDeque include:

  • Double ended functionality, including push_front and pop_back
  • append
  • drain
  • insert
  • remove
  • basically anything that messes with the position of elements in the buffer apart from swap

Implementations§

Source§

impl<T> RingBuffer<T>

Source

pub fn new() -> RingBuffer<T>

Creates an empty RingBuffer.

§Example
let buffer: RingBuffer<usize> = RingBuffer::new();
Source

pub fn with_capacity(capacity: usize) -> RingBuffer<T>

Creates an empty RingBuffer with space for at least capacity elements.

§Example
let buffer: RingBuffer<usize> = RingBuffer::with_capacity(10);
assert!(buffer.capacity() >= 10);
Source

pub fn as_slices(&self) -> (&[T], &[T])

Returns a pair of slices which contain, in order, the contents of the RingBuffer.

§Example
let mut buffer = RingBuffer::new();

buffer.push_back(41);
buffer.push_back(42);
buffer.push_back(1);
buffer.push_back(2);

assert_eq!(buffer.len(), 4);
assert_eq!(buffer.capacity(), 4);
assert_eq!(buffer.front(), Some(&41));
assert_eq!(buffer.as_slices(), (&[41, 42, 1, 2][..], &[][..]));

buffer.pop_front();
buffer.pop_front();
buffer.push_back(3);
buffer.push_back(4);

assert_eq!(buffer.as_slices(), (&[1, 2][..], &[3, 4][..]));
Source

pub fn back(&self) -> Option<&T>

Provides a reference to the back element of the queue, or None if the RingBuffer is empty.

§Example
let mut buffer = RingBuffer::new();
assert_eq!(buffer.back(), None);

buffer.push_back(1);
buffer.push_back(2);
assert_eq!(buffer.back(), Some(&2));
Source

pub fn back_mut(&mut self) -> Option<&mut T>

Provides a mutable reference to the back element of the queue, or None if the RingBuffer is empty.

§Example
let mut buffer = RingBuffer::new();
assert_eq!(buffer.back(), None);

buffer.push_back(1);
buffer.push_back(2);
if let Some(x) = buffer.back_mut() {
    *x = 42;
}
assert_eq!(buffer.back(), Some(&42));
Source

pub fn back_absolute_index(&self) -> Option<RingBufferIndex>

Returns the absolute index of the back element of the queue, or None if the RingBuffer is empty.

§Example
let mut buffer = RingBuffer::new();
assert!(buffer.back_absolute_index().is_none());

buffer.push_back(1);
buffer.push_back(2);
let back_index = buffer.back_absolute_index();

assert!(back_index.is_some());
assert_eq!(buffer.get_absolute(back_index.unwrap()), buffer.back());
Source

pub fn capacity(&self) -> usize

Returns the number of elements the RingBuffer can hold without reallocating. For fast wrapping functionality, capacity is always a power of two.

§Example
let buffer: RingBuffer<usize> = RingBuffer::with_capacity(10);
assert!(buffer.capacity() >= 16);
Source

pub fn clear(&mut self)

Clears the RingBuffer, removing all values.

§Example
let mut buffer = RingBuffer::new();
buffer.push_back(1);
buffer.clear();
assert!(buffer.is_empty());
Source

pub fn contains(&self, x: &T) -> bool
where T: PartialEq<T>,

Returns true if the RingBuffer contains an element equal to the given value.

§Example
let mut buffer = RingBuffer::new();

buffer.push_back(0);
buffer.push_back(1);

assert_eq!(buffer.contains(&1), true);
assert_eq!(buffer.contains(&42), false);
Source

pub fn front(&self) -> Option<&T>

Provides a reference to the front element of the queue, or None if the RingBuffer is empty.

§Example
let mut buffer = RingBuffer::new();
assert_eq!(buffer.front(), None);

buffer.push_back(1);
buffer.push_back(2);
assert_eq!(buffer.front(), Some(&1));
Source

pub fn front_mut(&mut self) -> Option<&mut T>

Provides a mutable reference to the front element of the queue, or None if the RingBuffer is empty.

§Example
let mut buffer = RingBuffer::new();
assert_eq!(buffer.front_mut(), None);

buffer.push_back(1);
buffer.push_back(2);
if let Some(x) = buffer.front_mut() {
    *x = 42;
}
assert_eq!(buffer.front(), Some(&42));
Source

pub fn front_absolute_index(&self) -> Option<RingBufferIndex>

Returns the absolute index of the front element of the queue, or None if the RingBuffer is empty.

§Example
let mut buffer = RingBuffer::new();
assert!(buffer.front_absolute_index().is_none());

buffer.push_back(1);
buffer.push_back(2);

let front_index = buffer.front_absolute_index();

assert!(front_index.is_some());
assert_eq!(buffer.get_absolute(front_index.unwrap()), buffer.front());
Source

pub fn get_absolute(&self, index: RingBufferIndex) -> Option<&T>

Retrieves an element in the RingBuffer by absolute index.

The index provided is the index used by the internal container. This is designed to be used in conjunction with push_back. This also gets wrapped around, supporting expanding and shrinking the container without breaking the access with absolute addresses.

§Example
let mut buffer = RingBuffer::new();

let first = buffer.push_back(1);
buffer.push_back(2);
let second = buffer.push_back(42);

assert_eq!(buffer.get_absolute(first), Some(&1));
assert_eq!(buffer.get_absolute(second), Some(&42));
Source

pub fn get_absolute_mut(&mut self, index: RingBufferIndex) -> Option<&mut T>

Retrieves a mutable element in the RingBuffer by absolute index.

The index provided is the index used by the internal container. This is designed to be used in conjunction with push_back. This also gets wrapped around, supporting expanding and shrinking the container without breaking the access with absolute addresses.

§Example
let mut buffer = RingBuffer::new();

buffer.push_back(1);
let the_answer = buffer.push_back(2);
buffer.push_back(3);

assert_eq!(buffer.get_absolute(the_answer), Some(&2));

if let Some(x) = buffer.get_absolute_mut(the_answer) {
    *x = 42;
}

assert_eq!(buffer.get_absolute(the_answer), Some(&42));
Source

pub unsafe fn get_absolute_unchecked(&self, index: RingBufferIndex) -> &T

Retrieves an element in the RingBuffer by absolute index without checking for validity.

This does the same as get_absolute, but skips any checks. Use this if you really need the performance and can guarantee the accessed element is valid.

§Safety

The caller is responsible for maintaining Rusts ownership guarantees. The validity of a buffer entry also isn’t checked, so while being valid memory, the reference may not point to an object in valid state.

§Example
let mut buffer = RingBuffer::new();

let first = buffer.push_back(1);
buffer.push_back(2);
let second = buffer.push_back(42);

unsafe {
    assert_eq!(buffer.get_absolute_unchecked(first), &1);
    assert_eq!(buffer.get_absolute_unchecked(second), &42);
}
Source

pub unsafe fn get_absolute_mut_unchecked( &mut self, index: RingBufferIndex, ) -> &mut T

Retrieves a mutable element in the RingBuffer by absolute index without checking for validity.

This does the same as get_absolute_mut, but skips any checks. Use this if you really need the performance and can guarantee the accessed element is valid.

§Safety

The caller is responsible for maintaining Rusts ownership guarantees. The validity of a buffer entry also isn’t checked, so while being valid memory, the reference may not point to an object in valid state.

§Example
let mut buffer = RingBuffer::new();

buffer.push_back(1);
let the_answer = buffer.push_back(2);
buffer.push_back(3);

assert_eq!(buffer.get_absolute(the_answer), Some(&2));

unsafe {
    *buffer.get_absolute_mut_unchecked(the_answer) = 42;
}

assert_eq!(buffer.get_absolute(the_answer), Some(&42));
Source

pub fn get_relative(&self, index: usize) -> Option<&T>

Retrieves an element in the RingBuffer by relative index.

Element at index 0 is the front of the queue.

§Example
let mut buffer = RingBuffer::new();
buffer.push_back(3);
buffer.push_back(4);
buffer.push_back(5);
buffer.push_back(6);
assert_eq!(buffer.get_relative(1), Some(&4));
Source

pub fn get_relative_mut(&mut self, index: usize) -> Option<&mut T>

Retrieves an element in the RingBuffer mutably by relative index.

Element at index 0 is the front of the queue.

§Example
let mut buffer = RingBuffer::new();
buffer.push_back(3);
buffer.push_back(4);
buffer.push_back(5);
buffer.push_back(6);
if let Some(elem) = buffer.get_relative_mut(1) {
    *elem = 7;
}

assert_eq!(buffer.get_relative(1), Some(&7));
Source

pub fn is_empty(&self) -> bool

Returns true if the RingBuffer is empty.

§Example
let mut buffer = RingBuffer::new();
assert!(buffer.is_empty());
buffer.push_back(1);
assert!(!buffer.is_empty());
Source

pub fn is_full(&self) -> bool

Returns true if the buffer is at full capacity.

§Example
let mut buffer = RingBuffer::with_capacity(2);
assert_eq!(buffer.capacity(), 2);
assert!(!buffer.is_full());
buffer.push_back(1);
buffer.push_back(2);
assert!(buffer.is_full());
Source

pub fn iter(&self) -> Iter<'_, T>

Returns a front-to-back iterator.

§Example
let mut buffer = RingBuffer::new();
buffer.push_back(3);
buffer.push_back(4);
buffer.push_back(5);
let b: &[_] = &[&3, &4, &5];
let c: Vec<&usize> = buffer.iter().collect();
assert_eq!(buffer.front(), Some(&3));
assert_eq!(&c[..], b);
Source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns a front-to-back iterator that returns mutable references.

§Example
let mut buffer = RingBuffer::new();
buffer.push_back(3);
buffer.push_back(4);
buffer.push_back(5);
for num in buffer.iter_mut() {
    *num = *num - 2;
}
let b: &[_] = &[&mut 1, &mut 2, &mut 3];
assert_eq!(&buffer.iter_mut().collect::<Vec<&mut usize>>()[..], b);
Source

pub fn len(&self) -> usize

Returns the number of elements in the RingBuffer.

§Example
let mut buffer = RingBuffer::new();
assert_eq!(buffer.len(), 0);
buffer.push_back(1);
assert_eq!(buffer.len(), 1);
Source

pub fn pop_front(&mut self) -> Option<T>

Removes the first element and returns it, or None if the RingBuffer is empty.

§Example
let mut buffer = RingBuffer::new();
buffer.push_back(1);
buffer.push_back(2);

assert_eq!(buffer.pop_front(), Some(1));
assert_eq!(buffer.pop_front(), Some(2));
assert_eq!(buffer.pop_front(), None);
Source

pub fn push_back(&mut self, new_element: T) -> RingBufferIndex

Appends an element to the back of the RingBuffer.

§Examples
let mut buffer = RingBuffer::new();
buffer.push_back(1);
buffer.push_back(42);
assert_eq!(42, *buffer.back().unwrap());
Source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional more elements to be inserted in the given RingBuffer. The collection may reserve more space to avoid frequent reallocations.

§Panics

Panics if the new capacity overflows usize.

§Example
let mut buffer: RingBuffer<usize> = vec![1].into_iter().collect();
buffer.reserve(10);
assert!(buffer.capacity() >= 11);
Source

pub fn shrink_to(&mut self, min_capacity: usize)

Shrinks the capacity of the RingBuffer with a lower bound.

The capacity will remain at least as large as the maximum of the length and the supplied value.

Does nothing if the current capacity is smaller than the supplied minimum capacity.

Also only shrinks if no element position needs to change as to preserve the indices of the allocated elements.

§Example
let mut buffer = RingBuffer::with_capacity(15);
buffer.extend(0..4);
assert!(buffer.capacity() >= 15);
assert!(!(buffer.capacity() < 6));
buffer.shrink_to(6);
assert!(buffer.capacity() >= 6);
assert!(!(buffer.capacity() < 4));
buffer.shrink_to(0);
assert!(buffer.capacity() >= 4);
Source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of the RingBuffer as much as possible.

It will drop down as close as possible to the length but the allocator may still inform the RingBuffer that there is space for a few more elements.

§Example
let mut buffer = RingBuffer::with_capacity(15);
buffer.extend(0..4);
assert!(buffer.capacity() >= 15);
buffer.shrink_to_fit();
assert!(buffer.capacity() >= 4);
Source

pub fn swap_relative(&mut self, i: usize, j: usize)

Swaps elements at relative indices i and j.

i and j may be equal.

Element at index 0 is the front of the queue.

§Panics

Panics if either index is out of bounds.

§Example
let mut buffer = RingBuffer::new();
buffer.push_back(3);
buffer.push_back(4);
buffer.push_back(5);
buffer.push_back(6);
buffer.push_back(7);

assert_eq!(buffer.get_relative(0), Some(&3));
assert_eq!(buffer.get_relative(2), Some(&5));

buffer.swap_relative(0, 2);

assert_eq!(buffer.get_relative(0), Some(&5));
assert_eq!(buffer.get_relative(2), Some(&3));
Source

pub fn swap_absolute(&mut self, i: RingBufferIndex, j: RingBufferIndex)

Swaps elements at absolute indices i and j.

i and j may be equal.

This is designed to be used in conjunction with push_back.

§Panics

Panics if either index is out of bounds.

§Example
let mut buffer = RingBuffer::new();
buffer.push_back(3);
let first = buffer.push_back(4);
buffer.push_back(5);
let second = buffer.push_back(6);
buffer.push_back(7);

assert_eq!(buffer.get_absolute(first), Some(&4));
assert_eq!(buffer.get_absolute(second), Some(&6));

buffer.swap_absolute(first, second);

assert_eq!(buffer.get_absolute(first), Some(&6));
assert_eq!(buffer.get_absolute(second), Some(&4));
Source

pub fn truncate(&mut self, len: usize)

Shortens the RingBuffer, dropping excess elements from the back.

If len is greater than the RingBuffer’s current length, this has no effect.

§Example
let mut buffer = RingBuffer::new();
buffer.push_back(5);
buffer.push_back(10);
buffer.push_back(15);
assert_eq!(buffer.len(), 3);
buffer.truncate(1);
assert_eq!(buffer.len(), 1);
assert_eq!(buffer.get_relative(0), Some(&15));

Trait Implementations§

Source§

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

Source§

fn clone(&self) -> RingBuffer<T>

Returns a duplicate 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<T> Debug for RingBuffer<T>
where T: Debug,

Source§

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

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

impl<T> Default for RingBuffer<T>

Source§

fn default() -> RingBuffer<T>

Returns the “default value” for a type. Read more
Source§

impl<T> Drop for RingBuffer<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<'a, T> Extend<&'a T> for RingBuffer<T>
where T: 'a + Copy,

Source§

fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<T> Extend<T> for RingBuffer<T>

Source§

fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<T> From<RingBuffer<T>> for VecDeque<T>

Source§

fn from(buffer: RingBuffer<T>) -> Self

Converts to this type from the input type.
Source§

impl<T> From<Vec<T>> for RingBuffer<T>

Source§

fn from(other: Vec<T>) -> Self

Converts to this type from the input type.
Source§

impl<T> FromIterator<T> for RingBuffer<T>

Source§

fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> RingBuffer<T>

Creates a value from an iterator. Read more
Source§

impl<T> Hash for RingBuffer<T>
where T: Hash,

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<T> Index<RingBufferIndex> for RingBuffer<T>

Source§

type Output = T

The returned type after indexing.
Source§

fn index(&self, index: RingBufferIndex) -> &T

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

impl<T> IndexMut<RingBufferIndex> for RingBuffer<T>

Source§

fn index_mut(&mut self, index: RingBufferIndex) -> &mut T

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

impl<'a, T> IntoIterator for &'a RingBuffer<T>

Source§

type Item = &'a T

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, T> IntoIterator for &'a mut RingBuffer<T>

Source§

type Item = &'a mut T

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T> IntoIterator for RingBuffer<T>

Source§

fn into_iter(self) -> Self::IntoIter

Consumes the RingBuffer into a front-to-back iterator yielding elements by value.

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
Source§

impl<T> Ord for RingBuffer<T>
where T: Ord,

Source§

fn cmp(&self, other: &RingBuffer<T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<T> PartialEq for RingBuffer<T>
where T: PartialEq,

Source§

fn eq(&self, other: &RingBuffer<T>) -> 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<T> PartialOrd for RingBuffer<T>
where T: PartialOrd,

Source§

fn partial_cmp(&self, other: &RingBuffer<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T> Eq for RingBuffer<T>
where T: Eq,

Source§

impl<T> Send for RingBuffer<T>
where T: Send,

Source§

impl<T> Sync for RingBuffer<T>
where T: Sync,

Auto Trait Implementations§

§

impl<T> Freeze for RingBuffer<T>

§

impl<T> RefUnwindSafe for RingBuffer<T>
where T: RefUnwindSafe,

§

impl<T> Unpin for RingBuffer<T>
where T: Unpin,

§

impl<T> UnwindSafe for RingBuffer<T>

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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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.