rune::alloc::vec_deque

Struct VecDeque

Source
pub struct VecDeque<T, A = Global>
where A: Allocator,
{ /* private fields */ }
Expand description

A double-ended queue implemented with a growable ring buffer.

The “default” usage of this type as a queue is to use try_push_back to add to the queue, and pop_front to remove from the queue. try_extend and try_append push onto the back in this manner, and iterating over VecDeque goes front to back.

A VecDeque with a known list of items can be initialized from an array:

use rune::alloc::VecDeque;

let deq = VecDeque::try_from([-1, 0, 1])?;

Since VecDeque is a ring buffer, its elements are not necessarily contiguous in memory. If you want to access the elements as a single slice, such as for efficient sorting, you can use make_contiguous. It rotates the VecDeque so that its elements do not wrap, and returns a mutable slice to the now-contiguous element sequence.

Implementations§

Source§

impl<T> VecDeque<T>

Source

pub const fn new() -> VecDeque<T>

Creates an empty deque.

§Examples
use rune::alloc::VecDeque;

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

pub fn try_with_capacity(capacity: usize) -> Result<VecDeque<T>, Error>

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

§Examples
use rune::alloc::VecDeque;

let deque: VecDeque<u32> = VecDeque::try_with_capacity(10)?;
Source§

impl<T, A> VecDeque<T, A>
where A: Allocator,

Source

pub const fn new_in(alloc: A) -> VecDeque<T, A>

Creates an empty deque.

§Examples
use rune::alloc::VecDeque;

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

pub fn try_with_capacity_in( capacity: usize, alloc: A, ) -> Result<VecDeque<T, A>, Error>

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

§Examples
use rune::alloc::VecDeque;
use rune::alloc::alloc::Global;

let deque: VecDeque<u32> = VecDeque::try_with_capacity_in(10, Global)?;
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 rune::alloc::VecDeque;

let mut buf = VecDeque::new();

buf.try_push_back(3);
buf.try_push_back(4);
buf.try_push_back(5);
buf.try_push_back(6);

assert_eq!(buf.get(1), Some(&4));
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 rune::alloc::VecDeque;

let mut buf = VecDeque::new();

buf.try_push_back(3)?;
buf.try_push_back(4)?;
buf.try_push_back(5)?;
buf.try_push_back(6)?;

assert_eq!(buf[1], 4);

if let Some(elem) = buf.get_mut(1) {
    *elem = 7;
}

assert_eq!(buf[1], 7);
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 rune::alloc::VecDeque;

let mut buf = VecDeque::new();

buf.try_push_back(3)?;
buf.try_push_back(4)?;
buf.try_push_back(5)?;

assert_eq!(buf, [3, 4, 5]);

buf.swap(0, 2);

assert_eq!(buf, [5, 4, 3]);
Source

pub fn capacity(&self) -> usize

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

§Examples
use rune::alloc::VecDeque;

let buf: VecDeque<i32> = VecDeque::try_with_capacity(10)?;
assert!(buf.capacity() >= 10);
Source

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

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 rune::alloc::{VecDeque, Error};
use rune::alloc::prelude::*;

fn process_data(data: &[u32]) -> Result<VecDeque<u32>, Error> {
    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.try_extend(data.iter().map(|&val| {
        val * 2 + 5 // very complicated
    }))?;

    Ok(output)
}
Source

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

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 rune::alloc::{VecDeque, Error};
use rune::alloc::prelude::*;

fn process_data(data: &[u32]) -> Result<VecDeque<u32>, Error> {
    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.try_extend(data.iter().map(|&val| {
        val * 2 + 5 // very complicated
    }))?;

    Ok(output)
}
Source

pub fn try_shrink_to_fit(&mut self) -> Result<(), Error>

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 rune::alloc::VecDeque;
use rune::alloc::prelude::*;

let mut buf = VecDeque::try_with_capacity(15)?;
buf.try_extend(0..4)?;
assert_eq!(buf.capacity(), 15);
buf.try_shrink_to_fit()?;
assert!(buf.capacity() >= 4);
Source

pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), Error>

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 rune::alloc::VecDeque;
use rune::alloc::prelude::*;

let mut buf = VecDeque::try_with_capacity(15)?;
buf.try_extend(0..4)?;
assert_eq!(buf.capacity(), 15);
buf.try_shrink_to(6)?;
assert!(buf.capacity() >= 6);
buf.try_shrink_to(0)?;
assert!(buf.capacity() >= 4);
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 rune::alloc::VecDeque;

let mut buf = VecDeque::new();

buf.try_push_back(5)?;
buf.try_push_back(10)?;
buf.try_push_back(15)?;

assert_eq!(buf, [5, 10, 15]);

buf.truncate(1);

assert_eq!(buf, [5]);
Source

pub fn allocator(&self) -> &A

Returns a reference to the underlying allocator.

Source

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

Returns a front-to-back iterator.

§Examples
use rune::alloc::{Vec, VecDeque};
use rune::alloc::prelude::*;

let mut buf = VecDeque::new();
buf.try_push_back(5)?;
buf.try_push_back(3)?;
buf.try_push_back(4)?;
let b: &[_] = &[&5, &3, &4];
let c: Vec<&i32> = buf.iter().try_collect()?;
assert_eq!(&c[..], b);
Source

pub unsafe fn raw_iter(&self) -> RawIter<T>

Returns a raw front-to-back iterator.

§Safety

The caller must ensure that the iterator doesn’t outlive self.

Source

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

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

§Examples
use rune::alloc::VecDeque;

let mut buf = VecDeque::new();
buf.try_push_back(5)?;
buf.try_push_back(3)?;
buf.try_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);
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 rune::alloc::VecDeque;

let mut deque = VecDeque::new();

deque.try_push_back(0)?;
deque.try_push_back(1)?;
deque.try_push_back(2)?;

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

deque.try_push_front(10)?;
deque.try_push_front(9)?;

assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
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 rune::alloc::VecDeque;

let mut deque = VecDeque::new();

deque.try_push_back(0)?;
deque.try_push_back(1)?;

deque.try_push_front(10)?;
deque.try_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][..]));
Source

pub fn len(&self) -> usize

Returns the number of elements in the deque.

§Examples
use rune::alloc::VecDeque;

let mut deque = VecDeque::new();
assert_eq!(deque.len(), 0);
deque.try_push_back(1)?;
assert_eq!(deque.len(), 1);
Source

pub fn is_empty(&self) -> bool

Returns true if the deque is empty.

§Examples
use rune::alloc::VecDeque;

let mut deque = VecDeque::new();
assert!(deque.is_empty());
deque.try_push_front(1)?;
assert!(!deque.is_empty());
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 rune::alloc::VecDeque;
use rune::alloc::prelude::*;

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

// A full range covers all contents
let all = deque.range(..);
assert_eq!(all.len(), 3);
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 rune::alloc::VecDeque;

let mut deque: VecDeque<_> = [1, 2, 3].try_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]);
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 rune::alloc::VecDeque;
use rune::alloc::prelude::*;

let mut deque: VecDeque<_> = [1, 2, 3].try_into()?;
let drained = deque.drain(2..).try_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());
Source

pub fn clear(&mut self)

Clears the deque, removing all values.

§Examples
use rune::alloc::VecDeque;

let mut deque = VecDeque::new();
deque.try_push_back(1)?;
deque.clear();
assert!(deque.is_empty());
Source

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

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 rune::alloc::VecDeque;

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

deque.try_push_back(0)?;
deque.try_push_back(1)?;

assert_eq!(deque.contains(&1), true);
assert_eq!(deque.contains(&10), false);
Source

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

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

§Examples
use rune::alloc::VecDeque;

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

d.try_push_back(1)?;
d.try_push_back(2)?;
assert_eq!(d.front(), Some(&1));
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 rune::alloc::VecDeque;

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

d.try_push_back(1)?;
d.try_push_back(2)?;
match d.front_mut() {
    Some(x) => *x = 9,
    None => (),
}
assert_eq!(d.front(), Some(&9));
Source

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

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

§Examples
use rune::alloc::VecDeque;

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

d.try_push_back(1)?;
d.try_push_back(2)?;
assert_eq!(d.back(), Some(&2));
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 rune::alloc::VecDeque;

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

d.try_push_back(1)?;
d.try_push_back(2)?;
match d.back_mut() {
    Some(x) => *x = 9,
    None => (),
}
assert_eq!(d.back(), Some(&9));
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 rune::alloc::VecDeque;

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

assert_eq!(d.pop_front(), Some(1));
assert_eq!(d.pop_front(), Some(2));
assert_eq!(d.pop_front(), None);
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 rune::alloc::VecDeque;

let mut buf = VecDeque::new();
assert_eq!(buf.pop_back(), None);
buf.try_push_back(1)?;
buf.try_push_back(3)?;
assert_eq!(buf.pop_back(), Some(3));
Source

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

Prepends an element to the deque.

§Examples
use rune::alloc::VecDeque;

let mut d = VecDeque::new();
d.try_push_front(1)?;
d.try_push_front(2)?;
assert_eq!(d.front(), Some(&2));
Source

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

Appends an element to the back of the deque.

§Examples
use rune::alloc::VecDeque;

let mut buf = VecDeque::new();
buf.try_push_back(1)?;
buf.try_push_back(3)?;
assert_eq!(3, *buf.back().unwrap());
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 rune::alloc::VecDeque;

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

assert_eq!(buf.swap_remove_front(2), Some(3));
assert_eq!(buf, [2, 1]);
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 rune::alloc::VecDeque;

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

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

pub fn try_insert(&mut self, index: usize, value: T) -> Result<(), Error>

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 rune::alloc::VecDeque;

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

vec_deque.try_insert(1, 'd')?;
assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
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 rune::alloc::VecDeque;

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

assert_eq!(buf.remove(1), Some(2));
assert_eq!(buf, [1, 3]);
Source

pub fn try_split_off(&mut self, at: usize) -> Result<VecDeque<T, A>, Error>
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 rune::alloc::VecDeque;

let mut buf: VecDeque<_> = [1, 2, 3].try_into()?;
let buf2 = buf.try_split_off(1)?;
assert_eq!(buf, [1]);
assert_eq!(buf2, [2, 3]);
Source

pub fn try_append(&mut self, other: &mut VecDeque<T, A>) -> Result<(), Error>

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 rune::alloc::VecDeque;

let mut buf: VecDeque<_> = [1, 2].try_into()?;
let mut buf2: VecDeque<_> = [3, 4].try_into()?;
buf.try_append(&mut buf2)?;
assert_eq!(buf, [1, 2, 3, 4]);
assert_eq!(buf2, []);
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 rune::alloc::VecDeque;
use rune::alloc::prelude::*;

let mut buf = VecDeque::new();
buf.try_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 rune::alloc::VecDeque;
use rune::alloc::prelude::*;

let mut buf = VecDeque::new();
buf.try_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]);
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 rune::alloc::VecDeque;
use rune::alloc::prelude::*;

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

pub fn try_resize_with( &mut self, new_len: usize, generator: impl FnMut() -> T, ) -> Result<(), Error>

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 rune::alloc::VecDeque;

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

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

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

let mut state = 100;
buf.try_resize_with(5, || { state += 1; state })?;
assert_eq!(buf, [5, 10, 101, 102, 103]);
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 rune::alloc::VecDeque;

let mut buf = VecDeque::try_with_capacity(15)?;

buf.try_push_back(2)?;
buf.try_push_back(1)?;
buf.try_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 rune::alloc::VecDeque;

let mut buf = VecDeque::new();

buf.try_push_back(2)?;
buf.try_push_back(1)?;
buf.try_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 &[_]);
}
Source

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

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

Equivalently,

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

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

§Complexity

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

§Examples
use rune::alloc::VecDeque;
use rune::alloc::prelude::*;

let mut buf: VecDeque<_> = (0..10).try_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]);
Source

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

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

Equivalently,

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

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

§Complexity

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

§Examples
use rune::alloc::VecDeque;
use rune::alloc::prelude::*;

let mut buf: VecDeque<_> = (0..10).try_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 rune::alloc::VecDeque;

let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].try_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 rune::alloc::VecDeque;

let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].try_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.try_insert(idx, num)?;
assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
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 rune::alloc::VecDeque;

let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].try_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)));
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 rune::alloc::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)].try_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)));
Source

pub fn partition_point<P>(&self, pred: P) -> usize
where 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 rune::alloc::VecDeque;

let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].try_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 rune::alloc::VecDeque;

let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].try_into()?;
let num = 42;
let idx = deque.partition_point(|&x| x < num);
deque.try_insert(idx, num)?;
assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
Source§

impl<T, A> VecDeque<T, A>
where T: TryClone, A: Allocator,

Source

pub fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), Error>

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 rune::alloc::VecDeque;

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

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

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

Trait Implementations§

Source§

impl<T, A> Debug for VecDeque<T, A>
where T: Debug, A: Allocator,

Source§

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

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

impl<T> Default for VecDeque<T>

Source§

fn default() -> VecDeque<T>

Creates an empty deque.

Source§

impl<T, A> Drop for VecDeque<T, A>
where A: Allocator,

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<T, A> From<Vec<T, A>> for VecDeque<T, A>
where A: Allocator,

Source§

fn from(other: Vec<T, A>) -> VecDeque<T, A>

Turn a Vec<T> into a VecDeque<T>.

This conversion is guaranteed to run in O(1) time and to not re-allocate the Vec’s buffer or allocate any additional memory.

Source§

impl<T, A> From<VecDeque<T, A>> for Vec<T, A>
where A: Allocator,

Source§

fn from(other: VecDeque<T, A>) -> Vec<T, A>

Turn a VecDeque<T> into a Vec<T>.

This never needs to re-allocate, but does need to do O(n) data movement if the circular buffer doesn’t happen to be at the beginning of the allocation.

§Examples
use rune::alloc::{VecDeque, Vec};
use rune::alloc::prelude::*;

// This one is *O*(1).
let deque: VecDeque<_> = (1..5).try_collect()?;
let ptr = deque.as_slices().0.as_ptr();
let vec = Vec::from(deque);
assert_eq!(vec, [1, 2, 3, 4]);
assert_eq!(vec.as_ptr(), ptr);

// This one needs data rearranging.
let mut deque: VecDeque<_> = (1..5).try_collect()?;
deque.try_push_front(9)?;
deque.try_push_front(8)?;
let ptr = deque.as_slices().1.as_ptr();
let vec = Vec::from(deque);
assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
assert_eq!(vec.as_ptr(), ptr);
Source§

impl<T, A> Hash for VecDeque<T, A>
where T: Hash, A: Allocator,

Source§

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

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, A> Index<usize> for VecDeque<T, A>
where A: Allocator,

Source§

type Output = T

The returned type after indexing.
Source§

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

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

impl<T, A> IndexMut<usize> for VecDeque<T, A>
where A: Allocator,

Source§

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

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

impl<'a, T, A> IntoIterator for &'a VecDeque<T, A>
where A: Allocator,

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) -> Iter<'a, T>

Creates an iterator from a value. Read more
Source§

impl<'a, T, A> IntoIterator for &'a mut VecDeque<T, A>
where A: Allocator,

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) -> IterMut<'a, T>

Creates an iterator from a value. Read more
Source§

impl<T, A> IntoIterator for VecDeque<T, A>
where A: Allocator,

Source§

fn into_iter(self) -> IntoIter<T, A>

Consumes the deque 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, A>

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

impl<T, A> Ord for VecDeque<T, A>
where T: Ord, A: Allocator,

Source§

fn cmp(&self, other: &VecDeque<T, A>) -> 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, U, A> PartialEq<&[U]> for VecDeque<T, A>
where A: Allocator, 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§

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, U, A, const N: usize> PartialEq<&[U; N]> for VecDeque<T, A>
where A: Allocator, T: PartialEq<U>,

Source§

fn eq(&self, other: &&[U; N]) -> 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, U, A> PartialEq<&mut [U]> for VecDeque<T, A>
where A: Allocator, T: PartialEq<U>,

Source§

fn eq(&self, other: &&mut [U]) -> 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, U, A, const N: usize> PartialEq<&mut [U; N]> for VecDeque<T, A>
where A: Allocator, T: PartialEq<U>,

Source§

fn eq(&self, other: &&mut [U; N]) -> 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, U, A, const N: usize> PartialEq<[U; N]> for VecDeque<T, A>
where A: Allocator, T: PartialEq<U>,

Source§

fn eq(&self, other: &[U; N]) -> 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, U, A> PartialEq<Vec<U, A>> for VecDeque<T, A>
where A: Allocator, T: PartialEq<U>,

Source§

fn eq(&self, other: &Vec<U, A>) -> 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, A> PartialEq for VecDeque<T, A>
where T: PartialEq, A: Allocator,

Source§

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

Source§

fn partial_cmp(&self, other: &VecDeque<T, A>) -> 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, A> TryClone for VecDeque<T, A>
where T: TryClone, A: Allocator + Clone,

Source§

fn try_clone(&self) -> Result<VecDeque<T, A>, Error>

Try to clone the current value, raising an allocation error if it’s unsuccessful.
Source§

fn try_clone_from(&mut self, other: &VecDeque<T, A>) -> Result<(), Error>

Performs copy-assignment from source. Read more
Source§

impl<T, A> TryExtend<T> for VecDeque<T, A>
where A: Allocator,

Source§

fn try_extend<I>(&mut self, iter: I) -> Result<(), Error>
where I: IntoIterator<Item = T>,

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

impl<T, const N: usize> TryFrom<[T; N]> for VecDeque<T>

Source§

fn try_from( arr: [T; N], ) -> Result<VecDeque<T>, <VecDeque<T> as TryFrom<[T; N]>>::Error>

Converts a [T; N] into a VecDeque<T>.

use rune::alloc::VecDeque;

let deq1 = VecDeque::try_from([1, 2, 3, 4])?;
let deq2: VecDeque<_> = [1, 2, 3, 4].try_into()?;
assert_eq!(deq1, deq2);
Source§

type Error = Error

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

impl<T, A> TryFromIteratorIn<T, A> for VecDeque<T, A>
where A: Allocator,

Source§

fn try_from_iter_in<I>(iter: I, alloc: A) -> Result<VecDeque<T, A>, Error>
where I: IntoIterator<Item = T>,

Creates a value from an iterator within an allocator.
Source§

impl<T, A> Eq for VecDeque<T, A>
where T: Eq, A: Allocator,

Auto Trait Implementations§

§

impl<T, A> Freeze for VecDeque<T, A>
where A: Freeze,

§

impl<T, A> RefUnwindSafe for VecDeque<T, A>

§

impl<T, A> Send for VecDeque<T, A>
where A: Send, T: Send,

§

impl<T, A> Sync for VecDeque<T, A>
where A: Sync, T: Sync,

§

impl<T, A> Unpin for VecDeque<T, A>
where A: Unpin, T: Unpin,

§

impl<T, A> UnwindSafe for VecDeque<T, A>

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<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> Same for T

Source§

type Output = T

Should always be Self
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> TryFromIterator<T> for U

Source§

fn try_from_iter<I>(iter: I) -> Result<U, Error>
where I: IntoIterator<Item = T>,

Creates a value from an iterator within an allocator.
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.
Source§

impl<T> TryToOwned for T
where T: TryClone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn try_to_owned(&self) -> Result<T, Error>

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

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T