Struct CircularBuffer

Source
pub struct CircularBuffer<const N: usize, T> { /* private fields */ }
Expand description

A fixed-size circular buffer.

A CircularBuffer may live on the stack. Wrap the CircularBuffer in a Box using CircularBuffer::boxed() if you need the struct to be heap-allocated.

See the module-level documentation for more details and examples.

Implementations§

Source§

impl<const N: usize, T> CircularBuffer<N, T>

Source

pub const fn new() -> Self

Returns an empty CircularBuffer.

§Examples
use circular_buffer::CircularBuffer;
let buf = CircularBuffer::<16, u32>::new();
assert_eq!(buf, []);
Source

pub fn boxed() -> Box<Self>

Returns an empty heap-allocated CircularBuffer.

§Examples
use circular_buffer::CircularBuffer;
let buf = CircularBuffer::<1024, f64>::boxed();
assert_eq!(buf.len(), 0);
Source

pub const fn len(&self) -> usize

Returns the number of elements in the buffer.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<16, u32>::new();
assert_eq!(buf.len(), 0);

buf.push_back(1);
buf.push_back(2);
buf.push_back(3);
assert_eq!(buf.len(), 3);
Source

pub const fn capacity(&self) -> usize

Returns the capacity of the buffer.

This is the maximum number of elements that the buffer can hold.

This method always returns the generic const parameter N.

§Examples
use circular_buffer::CircularBuffer;
let buf = CircularBuffer::<16, u32>::new();
assert_eq!(buf.capacity(), 16);
Source

pub const fn is_empty(&self) -> bool

Returns true if the buffer contains 0 elements.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<16, u32>::new();
assert!(buf.is_empty());

buf.push_back(1);
assert!(!buf.is_empty());
Source

pub const fn is_full(&self) -> bool

Returns true if the number of elements in the buffer matches the buffer capacity.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, u32>::new();
assert!(!buf.is_full());

buf.push_back(1);
assert!(!buf.is_full());

buf.push_back(2);
buf.push_back(3);
buf.push_back(4);
buf.push_back(5);
assert!(buf.is_full());
Source

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

Returns an iterator over the elements of the buffer.

The iterator advances from front to back. Use .rev() to advance from back to front.

§Examples

Iterate from front to back:

use circular_buffer::CircularBuffer;

let buf = CircularBuffer::<5, char>::from_iter("abc".chars());
let mut it = buf.iter();

assert_eq!(it.next(), Some(&'a'));
assert_eq!(it.next(), Some(&'b'));
assert_eq!(it.next(), Some(&'c'));
assert_eq!(it.next(), None);

Iterate from back to front:

use circular_buffer::CircularBuffer;

let buf = CircularBuffer::<5, char>::from_iter("abc".chars());
let mut it = buf.iter().rev();

assert_eq!(it.next(), Some(&'c'));
assert_eq!(it.next(), Some(&'b'));
assert_eq!(it.next(), Some(&'a'));
assert_eq!(it.next(), None);
Source

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

Returns an iterator over the elements of the buffer that allows modifying each value.

The iterator advances from front to back. Use .rev() to advance from back to front.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, u32>::from([1, 2, 3]);
for elem in buf.iter_mut() {
    *elem += 5;
}
assert_eq!(buf, [6, 7, 8]);
Source

pub fn range<R>(&self, range: R) -> Iter<'_, T>
where R: RangeBounds<usize>,

Returns an iterator over the specified range of elements of the buffer.

The iterator advances from front to back. Use .rev() to advance from back to front.

§Panics

If the start of the range is greater than the end, or if the end is greater than the length of the buffer.

§Examples

Iterate from front to back:

use circular_buffer::CircularBuffer;

let buf = CircularBuffer::<16, char>::from_iter("abcdefghi".chars());
let mut it = buf.range(3..6);

assert_eq!(it.next(), Some(&'d'));
assert_eq!(it.next(), Some(&'e'));
assert_eq!(it.next(), Some(&'f'));
assert_eq!(it.next(), None);

Iterate from back to front:

use circular_buffer::CircularBuffer;

let buf = CircularBuffer::<16, char>::from_iter("abcdefghi".chars());
let mut it = buf.range(3..6).rev();

assert_eq!(it.next(), Some(&'f'));
assert_eq!(it.next(), Some(&'e'));
assert_eq!(it.next(), Some(&'d'));
assert_eq!(it.next(), None);
Source

pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
where R: RangeBounds<usize>,

Returns an iterator over the specified range of elements of the buffer that allows modifying each value.

The iterator advances from front to back. Use .rev() to advance from back to front.

§Panics

If the start of the range is greater than the end, or if the end is greater than the length of the buffer.

§Examples

Iterate from front to back:

use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<16, i32>::from_iter([1, 2, 3, 4, 5, 6]);
for elem in buf.range_mut(..3) {
    *elem *= -1;
}
assert_eq!(buf, [-1, -2, -3, 4, 5, 6]);
Source

pub fn drain<R>(&mut self, range: R) -> Drain<'_, N, T>
where R: RangeBounds<usize>,

Removes the specified range from the buffer in bulk, returning the removed elements as an iterator. If the iterator is dropped before being fully consumed, it drops the remaining removed elements.

§Panics

If the start of the range is greater than the end, or if the end is greater than the length of the buffer.

§Leaking

If the returned iterator goes out of scope without being dropped (for example, due to calling mem::forget() on it), the buffer may have lost and leaked arbitrary elements, including elements outside of the range.

The current implementation leaks all the elements of the buffer if the iterator is leaked, but this behavior may change in the future.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<6, char>::from_iter("abcdef".chars());
let drained = buf.drain(3..).collect::<Vec<char>>();

assert_eq!(drained, ['d', 'e', 'f']);
assert_eq!(buf, ['a', 'b', 'c']);

Not consuming the draining iterator still removes the range of elements:

use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<6, char>::from_iter("abcdef".chars());
buf.drain(3..);

assert_eq!(buf, ['a', 'b', 'c']);
Source

pub fn make_contiguous(&mut self) -> &mut [T]

Rearranges the internal memory of the buffer so that all elements are in a contiguous slice, which is then returned.

This method does not allocate and does not change the order of the inserted elements. Because it returns a mutable slice, any slice methods may be called on the elements of the buffer, such as sorting methods.

Once the internal storage is contiguous, the as_slices() and as_mut_slices() methods will return the entire contents of the deque in a single slice. Adding new elements to the buffer may make the buffer disjoint (not contiguous).

§Complexity

If the buffer is disjoint (not contiguous), this method takes O(N) time, where N is the capacity of the buffer.

If the buffer is already contiguous, this method takes O(1) time.

This means that this method may be called multiple times on the same buffer without a performance penalty (provided that no new elements are added to the buffer in between calls).

§Examples
use circular_buffer::CircularBuffer;

// Create a new buffer, adding more elements than its capacity
let mut buf = CircularBuffer::<4, u32>::from_iter([1, 4, 3, 0, 2, 5]);
assert_eq!(buf, [3, 0, 2, 5]);

// The buffer is disjoint: as_slices() returns two non-empty slices
assert_eq!(buf.as_slices(), (&[3, 0][..], &[2, 5][..]));

// Make the buffer contiguous
assert_eq!(buf.make_contiguous(), &mut [3, 0, 2, 5]);
// as_slices() now returns a single non-empty slice
assert_eq!(buf.as_slices(), (&[3, 0, 2, 5][..], &[][..]));
// The order of the elements in the buffer did not get modified
assert_eq!(buf, [3, 0, 2, 5]);

// Make the buffer contiguous and sort its elements
buf.make_contiguous().sort();
assert_eq!(buf, [0, 2, 3, 5]);
Source

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

Returns a pair of slices which contain the elements of this buffer.

The second slice may be empty if the internal buffer is contiguous.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<4, char>::new();
buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
buf.push_back('d');

// Buffer is contiguous; second slice is empty
assert_eq!(buf.as_slices(), (&['a', 'b', 'c', 'd'][..], &[][..]));

buf.push_back('e');
buf.push_back('f');

// Buffer is disjoint; both slices are non-empty
assert_eq!(buf.as_slices(), (&['c', 'd'][..], &['e', 'f'][..]));
Source

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

Returns a pair of mutable slices which contain the elements of this buffer.

These slices can be used to modify or replace the elements in the buffer.

The second slice may be empty if the internal buffer is contiguous.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<4, char>::new();
buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
buf.push_back('d');
buf.push_back('e');
buf.push_back('f');

assert_eq!(buf, ['c', 'd', 'e', 'f']);

let (left, right) = buf.as_mut_slices();
assert_eq!(left, &mut ['c', 'd'][..]);
assert_eq!(right, &mut ['e', 'f'][..]);

left[0] = 'z';

assert_eq!(buf, ['z', 'd', 'e', 'f']);
Source

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

Returns a reference to the back element, or None if the buffer is empty.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<4, char>::new();
assert_eq!(buf.back(), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
assert_eq!(buf.back(), Some(&'c'));
Source

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

Returns a mutable reference to the back element, or None if the buffer is empty.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<4, char>::new();
assert_eq!(buf.back_mut(), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
match buf.back_mut() {
    None => (),
    Some(x) => *x = 'z',
}
assert_eq!(buf, ['a', 'b', 'z']);
Source

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

Returns a reference to the front element, or None if the buffer is empty.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<4, char>::new();
assert_eq!(buf.front(), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
assert_eq!(buf.front(), Some(&'a'));
Source

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

Returns a mutable reference to the front element, or None if the buffer is empty.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<4, char>::new();
assert_eq!(buf.front_mut(), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
match buf.front_mut() {
    None => (),
    Some(x) => *x = 'z',
}
assert_eq!(buf, ['z', 'b', 'c']);
Source

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

Returns a reference to the element at the given index from the front of the buffer, or None if the element does not exist.

Element at index 0 is the front of the queue.

This is the same as nth_front().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, char>::new();
assert_eq!(buf.get(1), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
buf.push_back('d');
assert_eq!(buf.get(1), Some(&'b'));
Source

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

Returns a mutable reference to the element at the given index, or None if the element does not exist.

Element at index 0 is the front of the queue.

This is the same as nth_front_mut().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, char>::new();
assert_eq!(buf.get_mut(1), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
buf.push_back('d');
match buf.get_mut(1) {
    None => (),
    Some(x) => *x = 'z',
}
assert_eq!(buf, ['a', 'z', 'c', 'd']);
Source

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

Returns a reference to the element at the given index from the front of the buffer, or None if the element does not exist.

Like most indexing operations, the count starts from zero, so nth_front(0) returns the first value, nth_front(1) the second, and so on. Element at index 0 is the front of the queue.

This is the same as get().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, char>::new();
assert_eq!(buf.nth_front(1), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
buf.push_back('d');
assert_eq!(buf.nth_front(1), Some(&'b'));
Source

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

Returns a mutable reference to the element at the given index from the front of the buffer, or None if the element does not exist.

Like most indexing operations, the count starts from zero, so nth_front_mut(0) returns the first value, nth_front_mut(1) the second, and so on. Element at index 0 is the front of the queue.

This is the same as get_mut().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, char>::new();
assert_eq!(buf.nth_front_mut(1), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
buf.push_back('d');
match buf.nth_front_mut(1) {
    None => (),
    Some(x) => *x = 'z',
}
assert_eq!(buf, ['a', 'z', 'c', 'd']);
Source

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

Returns a reference to the element at the given index from the back of the buffer, or None if the element does not exist.

Like most indexing operations, the count starts from zero, so nth_back(0) returns the first value, nth_back(1) the second, and so on. Element at index 0 is the back of the queue.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, char>::new();
assert_eq!(buf.nth_back(1), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
buf.push_back('d');
assert_eq!(buf.nth_back(1), Some(&'c'));
Source

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

Returns a mutable reference to the element at the given index from the back of the buffer, or None if the element does not exist.

Like most indexing operations, the count starts from zero, so nth_back_mut(0) returns the first value, nth_back_mut(1) the second, and so on. Element at index 0 is the back of the queue.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, char>::new();
assert_eq!(buf.nth_back_mut(1), None);

buf.push_back('a');
buf.push_back('b');
buf.push_back('c');
buf.push_back('d');
match buf.nth_back_mut(1) {
    None => (),
    Some(x) => *x = 'z',
}
assert_eq!(buf, ['a', 'b', 'z', 'd']);
Source

pub fn push_back(&mut self, item: T) -> Option<T>

Appends an element to the back of the buffer.

If the buffer is full, the element at the front of the buffer is overwritten and returned.

See also try_push_back() for a non-overwriting version of this method.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<3, char>::new();

assert_eq!(buf.push_back('a'), None);
assert_eq!(buf, ['a']);

assert_eq!(buf.push_back('b'), None);
assert_eq!(buf, ['a', 'b']);

assert_eq!(buf.push_back('c'), None);
assert_eq!(buf, ['a', 'b', 'c']);

// The buffer is now full; adding more values causes the front elements to be removed and
// returned
assert_eq!(buf.push_back('d'), Some('a'));
assert_eq!(buf, ['b', 'c', 'd']);

assert_eq!(buf.push_back('e'), Some('b'));
assert_eq!(buf, ['c', 'd', 'e']);

assert_eq!(buf.push_back('f'), Some('c'));
assert_eq!(buf, ['d', 'e', 'f']);
Source

pub fn try_push_back(&mut self, item: T) -> Result<(), T>

Appends an element to the back of the buffer.

If the buffer is full, the buffer is not modified and the given element is returned as an error.

See also push_back() for a version of this method that overwrites the front of the buffer when full.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<3, char>::new();

assert_eq!(buf.try_push_back('a'), Ok(()));
assert_eq!(buf, ['a']);

assert_eq!(buf.try_push_back('b'), Ok(()));
assert_eq!(buf, ['a', 'b']);

assert_eq!(buf.try_push_back('c'), Ok(()));
assert_eq!(buf, ['a', 'b', 'c']);

// The buffer is now full; adding more values results in an error
assert_eq!(buf.try_push_back('d'), Err('d'))
Source

pub fn push_front(&mut self, item: T) -> Option<T>

Appends an element to the front of the buffer.

If the buffer is full, the element at the back of the buffer is overwritten and returned.

See also try_push_front() for a non-overwriting version of this method.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<3, char>::new();

assert_eq!(buf.push_front('a'), None);
assert_eq!(buf, ['a']);

assert_eq!(buf.push_front('b'), None);
assert_eq!(buf, ['b', 'a']);

assert_eq!(buf.push_front('c'), None);
assert_eq!(buf, ['c', 'b', 'a']);

// The buffer is now full; adding more values causes the back elements to be dropped
assert_eq!(buf.push_front('d'), Some('a'));
assert_eq!(buf, ['d', 'c', 'b']);

assert_eq!(buf.push_front('e'), Some('b'));
assert_eq!(buf, ['e', 'd', 'c']);

assert_eq!(buf.push_front('f'), Some('c'));
assert_eq!(buf, ['f', 'e', 'd']);
Source

pub fn try_push_front(&mut self, item: T) -> Result<(), T>

Appends an element to the front of the buffer.

If the buffer is full, the buffer is not modified and the given element is returned as an error.

See also push_front() for a version of this method that overwrites the back of the buffer when full.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<3, char>::new();

assert_eq!(buf.try_push_front('a'), Ok(()));
assert_eq!(buf, ['a']);

assert_eq!(buf.try_push_front('b'), Ok(()));
assert_eq!(buf, ['b', 'a']);

assert_eq!(buf.try_push_front('c'), Ok(()));
assert_eq!(buf, ['c', 'b', 'a']);

// The buffer is now full; adding more values results in an error
assert_eq!(buf.try_push_front('d'), Err('d'));
Source

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

Removes and returns an element from the back of the buffer.

If the buffer is empty, None is returned.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<3, char>::from(['a', 'b', 'c']);

assert_eq!(buf.pop_back(), Some('c'));
assert_eq!(buf.pop_back(), Some('b'));
assert_eq!(buf.pop_back(), Some('a'));
assert_eq!(buf.pop_back(), None);
Source

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

Removes and returns an element from the front of the buffer.

If the buffer is empty, None is returned.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<3, char>::from(['a', 'b', 'c']);

assert_eq!(buf.pop_front(), Some('a'));
assert_eq!(buf.pop_front(), Some('b'));
assert_eq!(buf.pop_front(), Some('c'));
assert_eq!(buf.pop_front(), None);
Source

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

Removes and returns an element at the specified index.

If the index is out of bounds, None is returned.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<3, char>::from(['a', 'b', 'c']);

assert_eq!(buf.remove(1), Some('b'));
assert_eq!(buf, ['a', 'c']);

assert_eq!(buf.remove(5), None);
Source

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

Swap the element at index i with the element at index j.

§Panics

If either i or j is out of bounds.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, char>::from(['a', 'b', 'c', 'd']);
assert_eq!(buf, ['a', 'b', 'c', 'd']);

buf.swap(0, 3);
assert_eq!(buf, ['d', 'b', 'c', 'a']);

Trying to swap an invalid index panics:

use circular_buffer::CircularBuffer;
let mut buf = CircularBuffer::<5, char>::from(['a', 'b', 'c', 'd']);
buf.swap(0, 7);
Source

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

Removes the element at index and returns it, replacing it with the back of the buffer.

Returns None if index is out-of-bounds.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, char>::from(['a', 'b', 'c', 'd']);
assert_eq!(buf, ['a', 'b', 'c', 'd']);

assert_eq!(buf.swap_remove_back(2), Some('c'));
assert_eq!(buf, ['a', 'b', 'd']);

assert_eq!(buf.swap_remove_back(7), None);
Source

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

Removes the element at index and returns it, replacing it with the front of the buffer.

Returns None if index is out-of-bounds.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<5, char>::from(['a', 'b', 'c', 'd']);
assert_eq!(buf, ['a', 'b', 'c', 'd']);

assert_eq!(buf.swap_remove_front(2), Some('c'));
assert_eq!(buf, ['b', 'a', 'd']);

assert_eq!(buf.swap_remove_front(7), None);
Source

pub fn fill(&mut self, value: T)
where T: Clone,

Fills the entire capacity of self with elements by cloning value.

The elements already present in the buffer (if any) are all replaced by clones of value, and the spare capacity of the buffer is also filled with clones of value.

This is equivalent to clearing the buffer and adding clones of value until reaching the maximum capacity.

If you want to replace only the existing elements of the buffer, without affecting the spare capacity, use as_mut_slices() and call slice::fill() on the resulting slices.

See also: fill_with(), fill_spare(), fill_spare_with().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<10, u32>::from([1, 2, 3]);
assert_eq!(buf, [1, 2, 3]);

buf.fill(9);
assert_eq!(buf, [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]);

If you want to replace existing elements only:

use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<10, u32>::from([1, 2, 3]);
assert_eq!(buf, [1, 2, 3]);

let (front, back) = buf.as_mut_slices();
front.fill(9);
back.fill(9);
assert_eq!(buf, [9, 9, 9]);
Source

pub fn fill_with<F>(&mut self, f: F)
where F: FnMut() -> T,

Fills the entire capacity of self with elements by calling a closure.

The elements already present in the buffer (if any) are all replaced by the result of the closure, and the spare capacity of the buffer is also filled with the result of the closure.

This is equivalent to clearing the buffer and adding the result of the closure until reaching the maximum capacity.

If you want to replace only the existing elements of the buffer, without affecting the spare capacity, use as_mut_slices() and call slice::fill_with() on the resulting slices.

See also: fill(), fill_spare(), fill_spare_with().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<10, u32>::from([1, 2, 3]);
assert_eq!(buf, [1, 2, 3]);

let mut x = 2;
buf.fill_with(|| {
    x *= 2;
    x
});
assert_eq!(buf, [4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]);

If you want to replace existing elements only:

use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<10, u32>::from([1, 2, 3]);
assert_eq!(buf, [1, 2, 3]);

let mut x = 2;
let (front, back) = buf.as_mut_slices();
front.fill_with(|| {
    x *= 2;
    x
});
back.fill_with(|| {
    x *= 2;
    x
});
assert_eq!(buf, [4, 8, 16]);
Source

pub fn fill_spare(&mut self, value: T)
where T: Clone,

Fills the spare capacity of self with elements by cloning value.

The elements already present in the buffer (if any) are unaffected.

This is equivalent to adding clones of value to the buffer until reaching the maximum capacity.

See also: fill(), fill_with(), fill_spare_with().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<10, u32>::from([1, 2, 3]);
assert_eq!(buf, [1, 2, 3]);

buf.fill_spare(9);
assert_eq!(buf, [1, 2, 3, 9, 9, 9, 9, 9, 9, 9]);
Source

pub fn fill_spare_with<F>(&mut self, f: F)
where F: FnMut() -> T,

Fills the spare capacity of self with elements by calling a closure.

The elements already present in the buffer (if any) are unaffected.

This is equivalent adding the result of the closure to the buffer until reaching the maximum capacity.

See also: fill(), fill_with(), fill_spare().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<10, u32>::from([1, 2, 3]);
assert_eq!(buf, [1, 2, 3]);

let mut x = 2;
buf.fill_spare_with(|| {
    x *= 2;
    x
});
assert_eq!(buf, [1, 2, 3, 4, 8, 16, 32, 64, 128, 256]);
Source

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

Shortens the buffer, keeping only the front len elements and dropping the rest.

If len is equal or greater to the buffer’s current length, this has no effect.

Calling truncate_back(0) is equivalent to clear().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<4, u32>::from([10, 20, 30]);

buf.truncate_back(1);
assert_eq!(buf, [10]);

// Truncating to a length that is greater than the buffer's length has no effect
buf.truncate_back(8);
assert_eq!(buf, [10]);
Source

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

Shortens the buffer, keeping only the back len elements and dropping the rest.

If len is equal or greater to the buffer’s current length, this has no effect.

Calling truncate_front(0) is equivalent to clear().

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<4, u32>::from([10, 20, 30]);

buf.truncate_front(1);
assert_eq!(buf, [30]);

// Truncating to a length that is greater than the buffer's length has no effect
buf.truncate_front(8);
assert_eq!(buf, [30]);
Source

pub fn clear(&mut self)

Drops all the elements in the buffer.

§Examples
use circular_buffer::CircularBuffer;

let mut buf = CircularBuffer::<4, u32>::from([10, 20, 30]);
assert_eq!(buf, [10, 20, 30]);
buf.clear();
assert_eq!(buf, []);
Source§

impl<const N: usize, T> CircularBuffer<N, T>
where T: Clone,

Source

pub fn extend_from_slice(&mut self, other: &[T])

Clones and appends all the elements from the slice to the back of the buffer.

This is an optimized version of extend() for slices.

If slice contains more values than the available capacity, the elements at the front of the buffer are dropped.

§Examples
use circular_buffer::CircularBuffer;

let mut buf: CircularBuffer<5, u32> = CircularBuffer::from([1, 2, 3]);
buf.extend_from_slice(&[4, 5, 6, 7]);
assert_eq!(buf, [3, 4, 5, 6, 7]);
Source

pub fn to_vec(&self) -> Vec<T>

Clones the elements of the buffer into a new Vec, leaving the buffer unchanged.

§Examples
use circular_buffer::CircularBuffer;

let buf: CircularBuffer<5, u32> = CircularBuffer::from([1, 2, 3]);
let vec: Vec<u32> = buf.to_vec();

assert_eq!(buf, [1, 2, 3]);
assert_eq!(vec, [1, 2, 3]);

Trait Implementations§

Source§

impl<const N: usize> BufRead for CircularBuffer<N, u8>

Source§

fn fill_buf(&mut self) -> Result<&[u8]>

Returns the contents of the internal buffer, filling it with more data, via Read methods, if empty. Read more
Source§

fn consume(&mut self, amt: usize)

Marks the given amount of additional bytes from the internal buffer as having been read. Subsequent calls to read only return bytes that have not been marked as read. Read more
Source§

fn has_data_left(&mut self) -> Result<bool, Error>

🔬This is a nightly-only experimental API. (buf_read_has_data_left)
Checks if there is any data left to be read. Read more
1.0.0 · Source§

fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes into buf until the delimiter byte or EOF is reached. Read more
1.83.0 · Source§

fn skip_until(&mut self, byte: u8) -> Result<usize, Error>

Skips all bytes until the delimiter byte or EOF is reached. Read more
1.0.0 · Source§

fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until a newline (the 0xA byte) is reached, and append them to the provided String buffer. Read more
1.0.0 · Source§

fn split(self, byte: u8) -> Split<Self>
where Self: Sized,

Returns an iterator over the contents of this reader split on the byte byte. Read more
1.0.0 · Source§

fn lines(self) -> Lines<Self>
where Self: Sized,

Returns an iterator over the lines of this reader. Read more
Source§

impl<const N: usize, T> Clone for CircularBuffer<N, T>
where T: Clone,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
Source§

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

Performs copy-assignment from source. Read more
Source§

impl<const N: usize, T> Debug for CircularBuffer<N, T>
where T: Debug,

Source§

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

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

impl<const N: usize, T> Default for CircularBuffer<N, T>

Source§

fn default() -> Self

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

impl<const N: usize, T> Drop for CircularBuffer<N, T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<'a, const N: usize, T> Extend<&'a T> for CircularBuffer<N, T>
where T: Copy,

Source§

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

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<const N: usize, T> Extend<T> for CircularBuffer<N, T>

Source§

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

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<const N: usize, const M: usize, T> From<[T; M]> for CircularBuffer<N, T>

Source§

fn from(arr: [T; M]) -> Self

Converts to this type from the input type.
Source§

impl<const N: usize, T> FromIterator<T> for CircularBuffer<N, T>

Source§

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

Creates a value from an iterator. Read more
Source§

impl<const N: usize, T> Hash for CircularBuffer<N, 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<const N: usize, T> Index<usize> for CircularBuffer<N, T>

Source§

type Output = T

The returned type after indexing.
Source§

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

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

impl<const N: usize, T> IndexMut<usize> for CircularBuffer<N, T>

Source§

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

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

impl<'a, const N: usize, T> IntoIterator for &'a CircularBuffer<N, 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<const N: usize, T> IntoIterator for CircularBuffer<N, T>

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<N, 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<const N: usize, T> Ord for CircularBuffer<N, T>
where T: Ord,

Source§

fn cmp(&self, other: &Self) -> 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<'a, const N: usize, T, U> PartialEq<&'a [U]> for CircularBuffer<N, T>
where T: PartialEq<U>,

Source§

fn eq(&self, other: &&'a [U]) -> bool

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

const 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<'a, const N: usize, const M: usize, T, U> PartialEq<&'a [U; M]> for CircularBuffer<N, T>
where T: PartialEq<U>,

Source§

fn eq(&self, other: &&'a [U; M]) -> bool

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

const 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<'a, const N: usize, T, U> PartialEq<&'a mut [U]> for CircularBuffer<N, T>
where T: PartialEq<U>,

Source§

fn eq(&self, other: &&'a mut [U]) -> bool

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

const 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<'a, const N: usize, const M: usize, T, U> PartialEq<&'a mut [U; M]> for CircularBuffer<N, T>
where T: PartialEq<U>,

Source§

fn eq(&self, other: &&'a mut [U; M]) -> bool

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

const 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<const N: usize, T, U> PartialEq<[U]> for CircularBuffer<N, T>
where T: PartialEq<U>,

Source§

fn eq(&self, other: &[U]) -> bool

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

const 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<const N: usize, const M: usize, T, U> PartialEq<[U; M]> for CircularBuffer<N, T>
where T: PartialEq<U>,

Source§

fn eq(&self, other: &[U; M]) -> bool

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

const 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<const N: usize, const M: usize, T, U> PartialEq<CircularBuffer<M, U>> for CircularBuffer<N, T>
where T: PartialEq<U>,

Source§

fn eq(&self, other: &CircularBuffer<M, U>) -> bool

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

const 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<const N: usize, const M: usize, T, U> PartialOrd<CircularBuffer<M, U>> for CircularBuffer<N, T>
where T: PartialOrd<U>,

Source§

fn partial_cmp(&self, other: &CircularBuffer<M, U>) -> 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<const N: usize> Read for CircularBuffer<N, u8>

Source§

fn read(&mut self, dst: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
1.36.0 · Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

impl<const N: usize> Write for CircularBuffer<N, u8>

Source§

fn write(&mut self, src: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more
Source§

impl<const N: usize, T> Eq for CircularBuffer<N, T>
where T: Eq,

Auto Trait Implementations§

§

impl<const N: usize, T> Freeze for CircularBuffer<N, T>
where T: Freeze,

§

impl<const N: usize, T> RefUnwindSafe for CircularBuffer<N, T>
where T: RefUnwindSafe,

§

impl<const N: usize, T> Send for CircularBuffer<N, T>
where T: Send,

§

impl<const N: usize, T> Sync for CircularBuffer<N, T>
where T: Sync,

§

impl<const N: usize, T> Unpin for CircularBuffer<N, T>
where T: Unpin,

§

impl<const N: usize, T> UnwindSafe for CircularBuffer<N, T>
where T: 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, 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.