pub struct GrowableAllocRingBuffer<T>(/* private fields */);
Expand description

A growable ringbuffer. Once capacity is reached, the size is doubled. Wrapper of the built-in VecDeque struct.

The reason this is a wrapper, is that we want RingBuffers to implement Index<isize>, which we cannot do for remote types like VecDeque

Implementations§

source§

impl<T> GrowableAllocRingBuffer<T>

source

pub fn new() -> Self

Creates an empty ringbuffer.

source

pub fn with_capacity(capacity: usize) -> Self

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

Methods from Deref<Target = VecDeque<T>>§

1.0.0 · source

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

Provides a reference to the element at the given index.

Element at index 0 is the front of the queue.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(3);
buf.push_back(4);
buf.push_back(5);
buf.push_back(6);
assert_eq!(buf.get(1), Some(&4));
1.0.0 · source

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

Provides a mutable reference to the element at the given index.

Element at index 0 is the front of the queue.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(3);
buf.push_back(4);
buf.push_back(5);
buf.push_back(6);
assert_eq!(buf[1], 4);
if let Some(elem) = buf.get_mut(1) {
    *elem = 7;
}
assert_eq!(buf[1], 7);
1.0.0 · source

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

Swaps elements at 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.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(3);
buf.push_back(4);
buf.push_back(5);
assert_eq!(buf, [3, 4, 5]);
buf.swap(0, 2);
assert_eq!(buf, [5, 4, 3]);
1.0.0 · source

pub fn capacity(&self) -> usize

Returns the number of elements the deque can hold without reallocating.

Examples
use std::collections::VecDeque;

let buf: VecDeque<i32> = VecDeque::with_capacity(10);
assert!(buf.capacity() >= 10);
1.0.0 · source

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

Reserves the minimum capacity for at least additional more elements to be inserted in the given deque. Does nothing if the capacity is already sufficient.

Note that the allocator may give the collection more space than it requests. Therefore capacity can not be relied upon to be precisely minimal. Prefer reserve if future insertions are expected.

Panics

Panics if the new capacity overflows usize.

Examples
use std::collections::VecDeque;

let mut buf: VecDeque<i32> = [1].into();
buf.reserve_exact(10);
assert!(buf.capacity() >= 11);
1.0.0 · source

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

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

Panics

Panics if the new capacity overflows usize.

Examples
use std::collections::VecDeque;

let mut buf: VecDeque<i32> = [1].into();
buf.reserve(10);
assert!(buf.capacity() >= 11);
1.57.0 · source

pub fn try_reserve_exact( &mut self, additional: usize ) -> Result<(), TryReserveError>

Tries to reserve the minimum capacity for at least additional more elements to be inserted in the given deque. After calling try_reserve_exact, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). Does nothing if the capacity is already sufficient.

Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer try_reserve if future insertions are expected.

Errors

If the capacity overflows usize, or the allocator reports a failure, then an error is returned.

Examples
use std::collections::TryReserveError;
use std::collections::VecDeque;

fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
    let mut output = VecDeque::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve_exact(data.len())?;

    // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // very complicated
    }));

    Ok(output)
}
1.57.0 · source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve capacity for at least additional more elements to be inserted in the given deque. The collection may reserve more space to speculatively avoid frequent reallocations. After calling try_reserve, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs.

Errors

If the capacity overflows usize, or the allocator reports a failure, then an error is returned.

Examples
use std::collections::TryReserveError;
use std::collections::VecDeque;

fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
    let mut output = VecDeque::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // very complicated
    }));

    Ok(output)
}
1.5.0 · source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of the deque as much as possible.

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

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::with_capacity(15);
buf.extend(0..4);
assert_eq!(buf.capacity(), 15);
buf.shrink_to_fit();
assert!(buf.capacity() >= 4);
1.56.0 · source

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

Shrinks the capacity of the deque with a lower bound.

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

If the current capacity is less than the lower limit, this is a no-op.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::with_capacity(15);
buf.extend(0..4);
assert_eq!(buf.capacity(), 15);
buf.shrink_to(6);
assert!(buf.capacity() >= 6);
buf.shrink_to(0);
assert!(buf.capacity() >= 4);
1.16.0 · source

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

Shortens the deque, keeping the first len elements and dropping the rest.

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

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(10);
buf.push_back(15);
assert_eq!(buf, [5, 10, 15]);
buf.truncate(1);
assert_eq!(buf, [5]);
source

pub fn allocator(&self) -> &A

🔬This is a nightly-only experimental API. (allocator_api)

Returns a reference to the underlying allocator.

1.0.0 · source

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

Returns a front-to-back iterator.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(3);
buf.push_back(4);
let b: &[_] = &[&5, &3, &4];
let c: Vec<&i32> = buf.iter().collect();
assert_eq!(&c[..], b);
1.0.0 · source

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

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

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(3);
buf.push_back(4);
for num in buf.iter_mut() {
    *num = *num - 2;
}
let b: &[_] = &[&mut 3, &mut 1, &mut 2];
assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1.5.0 · source

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

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

If make_contiguous was previously called, all elements of the deque will be in the first slice and the second slice will be empty.

Examples
use std::collections::VecDeque;

let mut deque = VecDeque::new();

deque.push_back(0);
deque.push_back(1);
deque.push_back(2);

assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..]));

deque.push_front(10);
deque.push_front(9);

assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1.5.0 · source

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

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

If make_contiguous was previously called, all elements of the deque will be in the first slice and the second slice will be empty.

Examples
use std::collections::VecDeque;

let mut deque = VecDeque::new();

deque.push_back(0);
deque.push_back(1);

deque.push_front(10);
deque.push_front(9);

deque.as_mut_slices().0[0] = 42;
deque.as_mut_slices().1[0] = 24;
assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
1.0.0 · source

pub fn len(&self) -> usize

Returns the number of elements in the deque.

Examples
use std::collections::VecDeque;

let mut deque = VecDeque::new();
assert_eq!(deque.len(), 0);
deque.push_back(1);
assert_eq!(deque.len(), 1);
1.0.0 · source

pub fn is_empty(&self) -> bool

Returns true if the deque is empty.

Examples
use std::collections::VecDeque;

let mut deque = VecDeque::new();
assert!(deque.is_empty());
deque.push_front(1);
assert!(!deque.is_empty());
1.51.0 · source

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

Creates an iterator that covers the specified range in the deque.

Panics

Panics if the starting point is greater than the end point or if the end point is greater than the length of the deque.

Examples
use std::collections::VecDeque;

let deque: VecDeque<_> = [1, 2, 3].into();
let range = deque.range(2..).copied().collect::<VecDeque<_>>();
assert_eq!(range, [3]);

// A full range covers all contents
let all = deque.range(..);
assert_eq!(all.len(), 3);
1.51.0 · source

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

Creates an iterator that covers the specified mutable range in the deque.

Panics

Panics if the starting point is greater than the end point or if the end point is greater than the length of the deque.

Examples
use std::collections::VecDeque;

let mut deque: VecDeque<_> = [1, 2, 3].into();
for v in deque.range_mut(2..) {
  *v *= 2;
}
assert_eq!(deque, [1, 2, 6]);

// A full range covers all contents
for v in deque.range_mut(..) {
  *v *= 2;
}
assert_eq!(deque, [2, 4, 12]);
1.6.0 · source

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

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

The returned iterator keeps a mutable borrow on the queue to optimize its implementation.

Panics

Panics if the starting point is greater than the end point or if the end point is greater than the length of the deque.

Leaking

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

Examples
use std::collections::VecDeque;

let mut deque: VecDeque<_> = [1, 2, 3].into();
let drained = deque.drain(2..).collect::<VecDeque<_>>();
assert_eq!(drained, [3]);
assert_eq!(deque, [1, 2]);

// A full range clears all contents, like `clear()` does
deque.drain(..);
assert!(deque.is_empty());
1.0.0 · source

pub fn clear(&mut self)

Clears the deque, removing all values.

Examples
use std::collections::VecDeque;

let mut deque = VecDeque::new();
deque.push_back(1);
deque.clear();
assert!(deque.is_empty());
1.12.0 · source

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

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

This operation is O(n).

Note that if you have a sorted VecDeque, binary_search may be faster.

Examples
use std::collections::VecDeque;

let mut deque: VecDeque<u32> = VecDeque::new();

deque.push_back(0);
deque.push_back(1);

assert_eq!(deque.contains(&1), true);
assert_eq!(deque.contains(&10), false);
1.0.0 · source

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

Provides a reference to the front element, or None if the deque is empty.

Examples
use std::collections::VecDeque;

let mut d = VecDeque::new();
assert_eq!(d.front(), None);

d.push_back(1);
d.push_back(2);
assert_eq!(d.front(), Some(&1));
1.0.0 · source

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

Provides a mutable reference to the front element, or None if the deque is empty.

Examples
use std::collections::VecDeque;

let mut d = VecDeque::new();
assert_eq!(d.front_mut(), None);

d.push_back(1);
d.push_back(2);
match d.front_mut() {
    Some(x) => *x = 9,
    None => (),
}
assert_eq!(d.front(), Some(&9));
1.0.0 · source

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

Provides a reference to the back element, or None if the deque is empty.

Examples
use std::collections::VecDeque;

let mut d = VecDeque::new();
assert_eq!(d.back(), None);

d.push_back(1);
d.push_back(2);
assert_eq!(d.back(), Some(&2));
1.0.0 · source

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

Provides a mutable reference to the back element, or None if the deque is empty.

Examples
use std::collections::VecDeque;

let mut d = VecDeque::new();
assert_eq!(d.back(), None);

d.push_back(1);
d.push_back(2);
match d.back_mut() {
    Some(x) => *x = 9,
    None => (),
}
assert_eq!(d.back(), Some(&9));
1.0.0 · source

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

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

Examples
use std::collections::VecDeque;

let mut d = VecDeque::new();
d.push_back(1);
d.push_back(2);

assert_eq!(d.pop_front(), Some(1));
assert_eq!(d.pop_front(), Some(2));
assert_eq!(d.pop_front(), None);
1.0.0 · source

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

Removes the last element from the deque and returns it, or None if it is empty.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
assert_eq!(buf.pop_back(), None);
buf.push_back(1);
buf.push_back(3);
assert_eq!(buf.pop_back(), Some(3));
1.0.0 · source

pub fn push_front(&mut self, value: T)

Prepends an element to the deque.

Examples
use std::collections::VecDeque;

let mut d = VecDeque::new();
d.push_front(1);
d.push_front(2);
assert_eq!(d.front(), Some(&2));
1.0.0 · source

pub fn push_back(&mut self, value: T)

Appends an element to the back of the deque.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(1);
buf.push_back(3);
assert_eq!(3, *buf.back().unwrap());
1.5.0 · source

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

Removes an element from anywhere in the deque and returns it, replacing it with the first element.

This does not preserve ordering, but is O(1).

Returns None if index is out of bounds.

Element at index 0 is the front of the queue.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
assert_eq!(buf.swap_remove_front(0), None);
buf.push_back(1);
buf.push_back(2);
buf.push_back(3);
assert_eq!(buf, [1, 2, 3]);

assert_eq!(buf.swap_remove_front(2), Some(3));
assert_eq!(buf, [2, 1]);
1.5.0 · source

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

Removes an element from anywhere in the deque and returns it, replacing it with the last element.

This does not preserve ordering, but is O(1).

Returns None if index is out of bounds.

Element at index 0 is the front of the queue.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
assert_eq!(buf.swap_remove_back(0), None);
buf.push_back(1);
buf.push_back(2);
buf.push_back(3);
assert_eq!(buf, [1, 2, 3]);

assert_eq!(buf.swap_remove_back(0), Some(1));
assert_eq!(buf, [3, 2]);
1.5.0 · source

pub fn insert(&mut self, index: usize, value: T)

Inserts an element at index within the deque, shifting all elements with indices greater than or equal to index towards the back.

Element at index 0 is the front of the queue.

Panics

Panics if index is greater than deque’s length

Examples
use std::collections::VecDeque;

let mut vec_deque = VecDeque::new();
vec_deque.push_back('a');
vec_deque.push_back('b');
vec_deque.push_back('c');
assert_eq!(vec_deque, &['a', 'b', 'c']);

vec_deque.insert(1, 'd');
assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1.0.0 · source

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

Removes and returns the element at index from the deque. Whichever end is closer to the removal point will be moved to make room, and all the affected elements will be moved to new positions. Returns None if index is out of bounds.

Element at index 0 is the front of the queue.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(1);
buf.push_back(2);
buf.push_back(3);
assert_eq!(buf, [1, 2, 3]);

assert_eq!(buf.remove(1), Some(2));
assert_eq!(buf, [1, 3]);
1.4.0 · source

pub fn split_off(&mut self, at: usize) -> VecDeque<T, A>where A: Clone,

Splits the deque into two at the given index.

Returns a newly allocated VecDeque. self contains elements [0, at), and the returned deque contains elements [at, len).

Note that the capacity of self does not change.

Element at index 0 is the front of the queue.

Panics

Panics if at > len.

Examples
use std::collections::VecDeque;

let mut buf: VecDeque<_> = [1, 2, 3].into();
let buf2 = buf.split_off(1);
assert_eq!(buf, [1]);
assert_eq!(buf2, [2, 3]);
1.4.0 · source

pub fn append(&mut self, other: &mut VecDeque<T, A>)

Moves all the elements of other into self, leaving other empty.

Panics

Panics if the new number of elements in self overflows a usize.

Examples
use std::collections::VecDeque;

let mut buf: VecDeque<_> = [1, 2].into();
let mut buf2: VecDeque<_> = [3, 4].into();
buf.append(&mut buf2);
assert_eq!(buf, [1, 2, 3, 4]);
assert_eq!(buf2, []);
1.4.0 · source

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

Retains only the elements specified by the predicate.

In other words, remove all elements e for which f(&e) returns false. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.extend(1..5);
buf.retain(|&x| x % 2 == 0);
assert_eq!(buf, [2, 4]);

Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.

use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.extend(1..6);

let keep = [false, true, true, false, true];
let mut iter = keep.iter();
buf.retain(|_| *iter.next().unwrap());
assert_eq!(buf, [2, 3, 5]);
1.61.0 · source

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

Retains only the elements specified by the predicate.

In other words, remove all elements e for which f(&e) returns false. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.extend(1..5);
buf.retain_mut(|x| if *x % 2 == 0 {
    *x += 1;
    true
} else {
    false
});
assert_eq!(buf, [3, 5]);
1.33.0 · source

pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T)

Modifies the deque in-place so that len() is equal to new_len, either by removing excess elements from the back or by appending elements generated by calling generator to the back.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(10);
buf.push_back(15);
assert_eq!(buf, [5, 10, 15]);

buf.resize_with(5, Default::default);
assert_eq!(buf, [5, 10, 15, 0, 0]);

buf.resize_with(2, || unreachable!());
assert_eq!(buf, [5, 10]);

let mut state = 100;
buf.resize_with(5, || { state += 1; state });
assert_eq!(buf, [5, 10, 101, 102, 103]);
1.48.0 · source

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

Rearranges the internal storage of this deque so it is one contiguous slice, which is then returned.

This method does not allocate and does not change the order of the inserted elements. As it returns a mutable slice, this can be used to sort a deque.

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.

Examples

Sorting the content of a deque.

use std::collections::VecDeque;

let mut buf = VecDeque::with_capacity(15);

buf.push_back(2);
buf.push_back(1);
buf.push_front(3);

// sorting the deque
buf.make_contiguous().sort();
assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));

// sorting it in reverse order
buf.make_contiguous().sort_by(|a, b| b.cmp(a));
assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));

Getting immutable access to the contiguous slice.

use std::collections::VecDeque;

let mut buf = VecDeque::new();

buf.push_back(2);
buf.push_back(1);
buf.push_front(3);

buf.make_contiguous();
if let (slice, &[]) = buf.as_slices() {
    // we can now be sure that `slice` contains all elements of the deque,
    // while still having immutable access to `buf`.
    assert_eq!(buf.len(), slice.len());
    assert_eq!(slice, &[3, 2, 1] as &[_]);
}
1.36.0 · source

pub fn rotate_left(&mut self, n: usize)

Rotates the double-ended queue n places to the left.

Equivalently,

  • Rotates item n into the first position.
  • Pops the first n items and pushes them to the end.
  • Rotates len() - n places to the right.
Panics

If n is greater than len(). Note that n == len() does not panic and is a no-op rotation.

Complexity

Takes *O*(min(n, len() - n)) time and no extra space.

Examples
use std::collections::VecDeque;

let mut buf: VecDeque<_> = (0..10).collect();

buf.rotate_left(3);
assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);

for i in 1..10 {
    assert_eq!(i * 3 % 10, buf[0]);
    buf.rotate_left(3);
}
assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1.36.0 · source

pub fn rotate_right(&mut self, n: usize)

Rotates the double-ended queue n places to the right.

Equivalently,

  • Rotates the first item into position n.
  • Pops the last n items and pushes them to the front.
  • Rotates len() - n places to the left.
Panics

If n is greater than len(). Note that n == len() does not panic and is a no-op rotation.

Complexity

Takes *O*(min(n, len() - n)) time and no extra space.

Examples
use std::collections::VecDeque;

let mut buf: VecDeque<_> = (0..10).collect();

buf.rotate_right(3);
assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);

for i in 1..10 {
    assert_eq!(0, buf[i * 3 % 10]);
    buf.rotate_right(3);
}
assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

Binary searches this VecDeque for a given element. If the VecDeque is not sorted, the returned result is unspecified and meaningless.

If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found then Result::Err is returned, containing the index where a matching element could be inserted while maintaining sorted order.

See also binary_search_by, binary_search_by_key, and partition_point.

Examples

Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in [1, 4].

use std::collections::VecDeque;

let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();

assert_eq!(deque.binary_search(&13),  Ok(9));
assert_eq!(deque.binary_search(&4),   Err(7));
assert_eq!(deque.binary_search(&100), Err(13));
let r = deque.binary_search(&1);
assert!(matches!(r, Ok(1..=4)));

If you want to insert an item to a sorted deque, while maintaining sort order, consider using partition_point:

use std::collections::VecDeque;

let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
let num = 42;
let idx = deque.partition_point(|&x| x < num);
// The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
deque.insert(idx, num);
assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.54.0 · source

pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where F: FnMut(&'a T) -> Ordering,

Binary searches this VecDeque with a comparator function.

The comparator function should return an order code that indicates whether its argument is Less, Equal or Greater the desired target. If the VecDeque is not sorted or if the comparator function does not implement an order consistent with the sort order of the underlying VecDeque, the returned result is unspecified and meaningless.

If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found then Result::Err is returned, containing the index where a matching element could be inserted while maintaining sorted order.

See also binary_search, binary_search_by_key, and partition_point.

Examples

Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in [1, 4].

use std::collections::VecDeque;

let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();

assert_eq!(deque.binary_search_by(|x| x.cmp(&13)),  Ok(9));
assert_eq!(deque.binary_search_by(|x| x.cmp(&4)),   Err(7));
assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
let r = deque.binary_search_by(|x| x.cmp(&1));
assert!(matches!(r, Ok(1..=4)));
1.54.0 · source

pub fn binary_search_by_key<'a, B, F>( &'a self, b: &B, f: F ) -> Result<usize, usize>where F: FnMut(&'a T) -> B, B: Ord,

Binary searches this VecDeque with a key extraction function.

Assumes that the deque is sorted by the key, for instance with make_contiguous().sort_by_key() using the same key extraction function. If the deque is not sorted by the key, the returned result is unspecified and meaningless.

If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found then Result::Err is returned, containing the index where a matching element could be inserted while maintaining sorted order.

See also binary_search, binary_search_by, and partition_point.

Examples

Looks up a series of four elements in a slice of pairs sorted by their second elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in [1, 4].

use std::collections::VecDeque;

let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
         (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
         (1, 21), (2, 34), (4, 55)].into();

assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
let r = deque.binary_search_by_key(&1, |&(a, b)| b);
assert!(matches!(r, Ok(1..=4)));
1.54.0 · source

pub fn partition_point<P>(&self, pred: P) -> usizewhere P: FnMut(&T) -> bool,

Returns the index of the partition point according to the given predicate (the index of the first element of the second partition).

The deque is assumed to be partitioned according to the given predicate. This means that all elements for which the predicate returns true are at the start of the deque and all elements for which the predicate returns false are at the end. For example, [7, 15, 3, 5, 4, 12, 6] is partitioned under the predicate x % 2 != 0 (all odd numbers are at the start, all even at the end).

If the deque is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search.

See also binary_search, binary_search_by, and binary_search_by_key.

Examples
use std::collections::VecDeque;

let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
let i = deque.partition_point(|&x| x < 5);

assert_eq!(i, 4);
assert!(deque.iter().take(i).all(|&x| x < 5));
assert!(deque.iter().skip(i).all(|&x| !(x < 5)));

If you want to insert an item to a sorted deque, while maintaining sort order:

use std::collections::VecDeque;

let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
let num = 42;
let idx = deque.partition_point(|&x| x < num);
deque.insert(idx, num);
assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.16.0 · source

pub fn resize(&mut self, new_len: usize, value: T)

Modifies the deque in-place so that len() is equal to new_len, either by removing excess elements from the back or by appending clones of value to the back.

Examples
use std::collections::VecDeque;

let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(10);
buf.push_back(15);
assert_eq!(buf, [5, 10, 15]);

buf.resize(2, 0);
assert_eq!(buf, [5, 10]);

buf.resize(5, 20);
assert_eq!(buf, [5, 10, 20, 20, 20]);

Trait Implementations§

source§

impl<T> AsRef<VecDeque<T, Global>> for GrowableAllocRingBuffer<T>

source§

fn as_ref(&self) -> &VecDeque<T>

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T: Clone> Clone for GrowableAllocRingBuffer<T>

source§

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

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<T: Debug> Debug for GrowableAllocRingBuffer<T>

source§

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

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

impl<T> Default for GrowableAllocRingBuffer<T>

source§

fn default() -> Self

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

impl<T> Deref for GrowableAllocRingBuffer<T>

§

type Target = VecDeque<T, Global>

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl<T> DerefMut for GrowableAllocRingBuffer<T>

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl<T> Extend<T> for GrowableAllocRingBuffer<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: Clone> From<&[T]> for GrowableAllocRingBuffer<T>

source§

fn from(value: &[T]) -> Self

Converts to this type from the input type.
source§

impl<T: Clone, const N: usize> From<&[T; N]> for GrowableAllocRingBuffer<T>

source§

fn from(value: &[T; N]) -> Self

Converts to this type from the input type.
source§

impl<T: Clone> From<&mut [T]> for GrowableAllocRingBuffer<T>

source§

fn from(value: &mut [T]) -> Self

Converts to this type from the input type.
source§

impl<T: Clone, const CAP: usize> From<&mut [T; CAP]> for GrowableAllocRingBuffer<T>

source§

fn from(value: &mut [T; CAP]) -> Self

Converts to this type from the input type.
source§

impl From<&str> for GrowableAllocRingBuffer<char>

source§

fn from(value: &str) -> Self

Converts to this type from the input type.
source§

impl<T, const N: usize> From<[T; N]> for GrowableAllocRingBuffer<T>

source§

fn from(value: [T; N]) -> Self

Converts to this type from the input type.
source§

impl<T> From<AllocRingBuffer<T>> for GrowableAllocRingBuffer<T>

source§

fn from(v: AllocRingBuffer<T>) -> GrowableAllocRingBuffer<T>

Converts to this type from the input type.
source§

impl<T, const CAP: usize> From<ConstGenericRingBuffer<T, CAP>> for GrowableAllocRingBuffer<T>

source§

fn from(value: ConstGenericRingBuffer<T, CAP>) -> Self

Converts to this type from the input type.
source§

impl<T> From<GrowableAllocRingBuffer<T>> for AllocRingBuffer<T>

source§

fn from(v: GrowableAllocRingBuffer<T>) -> AllocRingBuffer<T>

Converts to this type from the input type.
source§

impl<T, const CAP: usize> From<GrowableAllocRingBuffer<T>> for ConstGenericRingBuffer<T, CAP>

source§

fn from(value: GrowableAllocRingBuffer<T>) -> Self

Converts to this type from the input type.
source§

impl<T> From<LinkedList<T, Global>> for GrowableAllocRingBuffer<T>

source§

fn from(value: LinkedList<T>) -> Self

Converts to this type from the input type.
source§

impl From<String> for GrowableAllocRingBuffer<char>

source§

fn from(value: String) -> Self

Converts to this type from the input type.
source§

impl<T> From<Vec<T, Global>> for GrowableAllocRingBuffer<T>

source§

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

Converts to this type from the input type.
source§

impl<T> From<VecDeque<T, Global>> for GrowableAllocRingBuffer<T>

source§

fn from(value: VecDeque<T>) -> Self

Converts to this type from the input type.
source§

impl<T> FromIterator<T> for GrowableAllocRingBuffer<T>

source§

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

Creates a value from an iterator. Read more
source§

impl<T> Index<usize> for GrowableAllocRingBuffer<T>

§

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<T> IndexMut<usize> for GrowableAllocRingBuffer<T>

source§

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

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

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

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = RingBufferIterator<'a, T, GrowableAllocRingBuffer<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 GrowableAllocRingBuffer<T>

§

type Item = &'a mut T

The type of the elements being iterated over.
§

type IntoIter = RingBufferMutIterator<'a, T, GrowableAllocRingBuffer<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 GrowableAllocRingBuffer<T>

§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = RingBufferIntoIterator<T, GrowableAllocRingBuffer<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: PartialEq> PartialEq<GrowableAllocRingBuffer<T>> for GrowableAllocRingBuffer<T>

source§

fn eq(&self, other: &GrowableAllocRingBuffer<T>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T> RingBuffer<T> for GrowableAllocRingBuffer<T>

source§

fn dequeue(&mut self) -> Option<T>

dequeues the top item off the ringbuffer, and moves this item out.
source§

fn push(&mut self, value: T)

Pushes a value onto the buffer. Cycles around if capacity is reached.
source§

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

Sets every element in the ringbuffer to the value returned by f.
source§

fn clear(&mut self)

Empties the buffer entirely. Sets the length to 0 but keeps the capacity allocated.
source§

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

Gets a value relative to the current index. 0 is the next index to be written to with push.
source§

fn get_signed(&self, index: isize) -> Option<&T>

Gets a value relative to the current index. 0 is the next index to be written to with push. -1 and down are the last elements pushed and 0 and up are the items that were pushed the longest ago.
source§

fn len(&self) -> usize

Returns the length of the internal buffer. This length grows up to the capacity and then stops growing. This is because when the length is reached, new items are appended at the start.
source§

fn is_empty(&self) -> bool

Returns true if the buffer is entirely empty.
source§

fn is_full(&self) -> bool

Returns true when the length of the ringbuffer equals the capacity. This happens whenever more elements than capacity have been pushed to the buffer.
source§

fn capacity(&self) -> usize

Returns the capacity of the buffer.
source§

fn buffer_size(&self) -> usize

Returns the number of elements allocated for this ringbuffer (can be larger than capacity).
source§

fn enqueue(&mut self, value: T)

alias for push, forming a more natural counterpart to dequeue
source§

fn skip(&mut self)

dequeues the top item off the queue, but does not return it. Instead it is dropped. If the ringbuffer is empty, this function is a nop.
source§

fn drain(&mut self) -> RingBufferDrainingIterator<'_, T, Self>

Returns an iterator over the elements in the ringbuffer, dequeueing elements as they are iterated over. Read more
source§

fn get_mut_signed(&mut self, index: isize) -> Option<&mut T>

Gets a value relative to the current index mutably. 0 is the next index to be written to with push. -1 and down are the last elements pushed and 0 and up are the items that were pushed the longest ago.
source§

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

Gets a value relative to the current index mutably. 0 is the next index to be written to with push.
source§

fn peek(&self) -> Option<&T>

Returns the value at the current index. This is the value that will be overwritten by the next push and also the value pushed the longest ago. (alias of Self::front)
source§

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

Returns the value at the front of the queue. This is the value that will be overwritten by the next push and also the value pushed the longest ago. (alias of peek)
source§

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

Returns a mutable reference to the value at the back of the queue. This is the value that will be overwritten by the next push. (alias of peek)
source§

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

Returns the value at the back of the queue. This is the item that was pushed most recently.
source§

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

Returns a mutable reference to the value at the back of the queue. This is the item that was pushed most recently.
source§

fn iter_mut(&mut self) -> RingBufferMutIterator<'_, T, Self>

Creates a mutable iterator over the buffer starting from the item pushed the longest ago, and ending at the element most recently pushed.
source§

fn iter(&self) -> RingBufferIterator<'_, T, Self>

Creates an iterator over the buffer starting from the item pushed the longest ago, and ending at the element most recently pushed.
source§

impl<T: Eq> Eq for GrowableAllocRingBuffer<T>

source§

impl<T> StructuralEq for GrowableAllocRingBuffer<T>

source§

impl<T> StructuralPartialEq for GrowableAllocRingBuffer<T>

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. 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 Twhere 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 Twhere T: Clone,

§

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 Twhere U: Into<T>,

§

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 Twhere U: TryFrom<T>,

§

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.