pub struct VecDeque<T, A = Global>where
A: Allocator,{ /* private fields */ }
alloc
only.Expand description
alloc
A double-ended growable queue.
Re-exported from [alloc
]::collections::
.
A double-ended queue implemented with a growable ring buffer.
The “default” usage of this type as a queue is to use push_back
to add to
the queue, and pop_front
to remove from the queue. extend
and 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 std::collections::VecDeque;
let deq = VecDeque::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>
impl<T> VecDeque<T>
1.0.0 (const: 1.68.0) · Sourcepub const fn new() -> VecDeque<T>
pub const fn new() -> VecDeque<T>
Creates an empty deque.
§Examples
use std::collections::VecDeque;
let deque: VecDeque<u32> = VecDeque::new();
1.0.0 · Sourcepub fn with_capacity(capacity: usize) -> VecDeque<T>
pub fn with_capacity(capacity: usize) -> VecDeque<T>
Creates an empty deque with space for at least capacity
elements.
§Examples
use std::collections::VecDeque;
let deque: VecDeque<u32> = VecDeque::with_capacity(10);
Sourcepub fn try_with_capacity(
capacity: usize,
) -> Result<VecDeque<T>, TryReserveError> ⓘ
🔬This is a nightly-only experimental API. (try_with_capacity
)
pub fn try_with_capacity( capacity: usize, ) -> Result<VecDeque<T>, TryReserveError> ⓘ
try_with_capacity
)Source§impl<T, A> VecDeque<T, A>where
A: Allocator,
impl<T, A> VecDeque<T, A>where
A: Allocator,
Sourcepub const fn new_in(alloc: A) -> VecDeque<T, A>
🔬This is a nightly-only experimental API. (allocator_api
)
pub const fn new_in(alloc: A) -> VecDeque<T, A>
allocator_api
)Creates an empty deque.
§Examples
use std::collections::VecDeque;
let deque: VecDeque<u32> = VecDeque::new();
Sourcepub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A>
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A>
allocator_api
)Creates an empty deque with space for at least capacity
elements.
§Examples
use std::collections::VecDeque;
let deque: VecDeque<u32> = VecDeque::with_capacity(10);
1.0.0 · Sourcepub fn get(&self, index: usize) -> Option<&T> ⓘ
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 · Sourcepub fn get_mut(&mut self, index: usize) -> Option<&mut T> ⓘ
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 · Sourcepub fn swap(&mut self, i: usize, j: usize)
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 · Sourcepub fn capacity(&self) -> usize ⓘ
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 · Sourcepub fn reserve_exact(&mut self, additional: usize)
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 · Sourcepub fn reserve(&mut self, additional: usize)
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 · Sourcepub fn try_reserve_exact(
&mut self,
additional: usize,
) -> Result<(), TryReserveError> ⓘ
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 · Sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> ⓘ
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 · Sourcepub fn shrink_to_fit(&mut self)
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 · Sourcepub fn shrink_to(&mut self, min_capacity: usize)
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 · Sourcepub fn truncate(&mut self, len: usize)
pub fn truncate(&mut self, len: usize)
Shortens the deque, keeping the first len
elements and dropping
the rest.
If len
is greater or equal to 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]);
Sourcepub fn allocator(&self) -> &A
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn allocator(&self) -> &A
allocator_api
)Returns a reference to the underlying allocator.
1.0.0 · Sourcepub fn iter(&self) -> Iter<'_, T> ⓘ
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 · Sourcepub fn iter_mut(&mut self) -> IterMut<'_, T> ⓘ
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 · Sourcepub fn as_slices(&self) -> (&[T], &[T]) ⓘ
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 · Sourcepub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) ⓘ
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 · Sourcepub fn len(&self) -> usize ⓘ
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 · Sourcepub fn is_empty(&self) -> bool
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 · Sourcepub fn range<R>(&self, range: R) -> Iter<'_, T> ⓘwhere
R: RangeBounds<usize>,
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 · Sourcepub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T> ⓘwhere
R: RangeBounds<usize>,
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 · Sourcepub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> ⓘwhere
R: RangeBounds<usize>,
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 · Sourcepub fn clear(&mut self)
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 · Sourcepub fn contains(&self, x: &T) -> boolwhere
T: PartialEq,
pub fn contains(&self, x: &T) -> boolwhere
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 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 · Sourcepub fn front(&self) -> Option<&T> ⓘ
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 · Sourcepub fn front_mut(&mut self) -> Option<&mut T> ⓘ
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 · Sourcepub fn back(&self) -> Option<&T> ⓘ
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 · Sourcepub fn back_mut(&mut self) -> Option<&mut T> ⓘ
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 · Sourcepub fn pop_front(&mut self) -> Option<T> ⓘ
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 · Sourcepub fn pop_back(&mut self) -> Option<T> ⓘ
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 · Sourcepub fn push_front(&mut self, value: T)
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 · Sourcepub fn push_back(&mut self, value: T)
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 · Sourcepub fn swap_remove_front(&mut self, index: usize) -> Option<T> ⓘ
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 · Sourcepub fn swap_remove_back(&mut self, index: usize) -> Option<T> ⓘ
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 · Sourcepub fn insert(&mut self, index: usize, value: T)
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 strictly 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']);
vec_deque.insert(4, 'e');
assert_eq!(vec_deque, &['a', 'd', 'b', 'c', 'e']);
1.0.0 · Sourcepub fn remove(&mut self, index: usize) -> Option<T> ⓘ
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('a');
buf.push_back('b');
buf.push_back('c');
assert_eq!(buf, ['a', 'b', 'c']);
assert_eq!(buf.remove(1), Some('b'));
assert_eq!(buf, ['a', 'c']);
1.4.0 · Sourcepub fn split_off(&mut self, at: usize) -> VecDeque<T, A>where
A: Clone,
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<_> = ['a', 'b', 'c'].into();
let buf2 = buf.split_off(1);
assert_eq!(buf, ['a']);
assert_eq!(buf2, ['b', 'c']);
1.4.0 · Sourcepub fn append(&mut self, other: &mut VecDeque<T, A>)
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 · Sourcepub fn retain<F>(&mut self, f: F)
pub fn retain<F>(&mut self, f: F)
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 · Sourcepub fn retain_mut<F>(&mut self, f: F)
pub fn retain_mut<F>(&mut self, f: F)
Retains only the elements specified by the predicate.
In other words, remove all elements e
for which f(&mut 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 · Sourcepub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T)
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 · Sourcepub fn make_contiguous(&mut self) -> &mut [T] ⓘ
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 · Sourcepub fn rotate_left(&mut self, n: usize)
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 · Sourcepub fn rotate_right(&mut self, n: usize)
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]);
1.54.0 · Sourcepub fn binary_search(&self, x: &T) -> Result<usize, usize> ⓘwhere
T: Ord,
pub fn binary_search(&self, x: &T) -> Result<usize, usize> ⓘwhere
T: Ord,
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);
// If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
// `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` may allow `insert`
// to shift less elements.
deque.insert(idx, num);
assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.54.0 · Sourcepub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize> ⓘ
pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize> ⓘ
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 · Sourcepub fn binary_search_by_key<'a, B, F>(
&'a self,
b: &B,
f: F,
) -> Result<usize, usize> ⓘ
pub fn binary_search_by_key<'a, B, F>( &'a self, b: &B, f: F, ) -> Result<usize, usize> ⓘ
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 · Sourcepub fn partition_point<P>(&self, pred: P) -> usize ⓘ
pub fn partition_point<P>(&self, pred: P) -> usize ⓘ
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]);
Source§impl<T, A> VecDeque<T, A>
impl<T, A> VecDeque<T, A>
1.16.0 · Sourcepub fn resize(&mut self, new_len: usize, value: T)
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§
§impl<T> Archive for VecDeque<T>where
T: Archive,
impl<T> Archive for VecDeque<T>where
T: Archive,
§type Archived = ArchivedVec<<T as Archive>::Archived>
type Archived = ArchivedVec<<T as Archive>::Archived>
§type Resolver = VecResolver
type Resolver = VecResolver
§fn resolve(
&self,
resolver: <VecDeque<T> as Archive>::Resolver,
out: Place<<VecDeque<T> as Archive>::Archived>,
)
fn resolve( &self, resolver: <VecDeque<T> as Archive>::Resolver, out: Place<<VecDeque<T> as Archive>::Archived>, )
§const COPY_OPTIMIZATION: CopyOptimization<Self> = _
const COPY_OPTIMIZATION: CopyOptimization<Self> = _
serialize
. Read moreSource§impl<T> BitSized<{$PTR_BITS * 3}> for VecDeque<T>
impl<T> BitSized<{$PTR_BITS * 3}> for VecDeque<T>
Source§const BIT_SIZE: usize = _
const BIT_SIZE: usize = _
Source§const MIN_BYTE_SIZE: usize = _
const MIN_BYTE_SIZE: usize = _
§impl Buf for VecDeque<u8>
impl Buf for VecDeque<u8>
§fn remaining(&self) -> usize ⓘ
fn remaining(&self) -> usize ⓘ
§fn chunk(&self) -> &[u8] ⓘ
fn chunk(&self) -> &[u8] ⓘ
Buf::remaining()
. Note that this can return a shorter slice (this
allows non-continuous internal representation). Read more§fn chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize ⓘ
fn chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize ⓘ
§fn has_remaining(&self) -> bool
fn has_remaining(&self) -> bool
§fn copy_to_slice(&mut self, dst: &mut [u8])
fn copy_to_slice(&mut self, dst: &mut [u8])
§fn get_u16(&mut self) -> u16 ⓘ
fn get_u16(&mut self) -> u16 ⓘ
self
in big-endian byte order. Read more§fn get_u16_le(&mut self) -> u16 ⓘ
fn get_u16_le(&mut self) -> u16 ⓘ
self
in little-endian byte order. Read more§fn get_u16_ne(&mut self) -> u16 ⓘ
fn get_u16_ne(&mut self) -> u16 ⓘ
self
in native-endian byte order. Read more§fn get_i16(&mut self) -> i16 ⓘ
fn get_i16(&mut self) -> i16 ⓘ
self
in big-endian byte order. Read more§fn get_i16_le(&mut self) -> i16 ⓘ
fn get_i16_le(&mut self) -> i16 ⓘ
self
in little-endian byte order. Read more§fn get_i16_ne(&mut self) -> i16 ⓘ
fn get_i16_ne(&mut self) -> i16 ⓘ
self
in native-endian byte order. Read more§fn get_u32(&mut self) -> u32 ⓘ
fn get_u32(&mut self) -> u32 ⓘ
self
in the big-endian byte order. Read more§fn get_u32_le(&mut self) -> u32 ⓘ
fn get_u32_le(&mut self) -> u32 ⓘ
self
in the little-endian byte order. Read more§fn get_u32_ne(&mut self) -> u32 ⓘ
fn get_u32_ne(&mut self) -> u32 ⓘ
self
in native-endian byte order. Read more§fn get_i32(&mut self) -> i32 ⓘ
fn get_i32(&mut self) -> i32 ⓘ
self
in big-endian byte order. Read more§fn get_i32_le(&mut self) -> i32 ⓘ
fn get_i32_le(&mut self) -> i32 ⓘ
self
in little-endian byte order. Read more§fn get_i32_ne(&mut self) -> i32 ⓘ
fn get_i32_ne(&mut self) -> i32 ⓘ
self
in native-endian byte order. Read more§fn get_u64(&mut self) -> u64 ⓘ
fn get_u64(&mut self) -> u64 ⓘ
self
in big-endian byte order. Read more§fn get_u64_le(&mut self) -> u64 ⓘ
fn get_u64_le(&mut self) -> u64 ⓘ
self
in little-endian byte order. Read more§fn get_u64_ne(&mut self) -> u64 ⓘ
fn get_u64_ne(&mut self) -> u64 ⓘ
self
in native-endian byte order. Read more§fn get_i64(&mut self) -> i64 ⓘ
fn get_i64(&mut self) -> i64 ⓘ
self
in big-endian byte order. Read more§fn get_i64_le(&mut self) -> i64 ⓘ
fn get_i64_le(&mut self) -> i64 ⓘ
self
in little-endian byte order. Read more§fn get_i64_ne(&mut self) -> i64 ⓘ
fn get_i64_ne(&mut self) -> i64 ⓘ
self
in native-endian byte order. Read more§fn get_u128(&mut self) -> u128 ⓘ
fn get_u128(&mut self) -> u128 ⓘ
self
in big-endian byte order. Read more§fn get_u128_le(&mut self) -> u128 ⓘ
fn get_u128_le(&mut self) -> u128 ⓘ
self
in little-endian byte order. Read more§fn get_u128_ne(&mut self) -> u128 ⓘ
fn get_u128_ne(&mut self) -> u128 ⓘ
self
in native-endian byte order. Read more§fn get_i128(&mut self) -> i128 ⓘ
fn get_i128(&mut self) -> i128 ⓘ
self
in big-endian byte order. Read more§fn get_i128_le(&mut self) -> i128 ⓘ
fn get_i128_le(&mut self) -> i128 ⓘ
self
in little-endian byte order. Read more§fn get_i128_ne(&mut self) -> i128 ⓘ
fn get_i128_ne(&mut self) -> i128 ⓘ
self
in native-endian byte order. Read more§fn get_uint(&mut self, nbytes: usize) -> u64 ⓘ
fn get_uint(&mut self, nbytes: usize) -> u64 ⓘ
self
in big-endian byte order. Read more§fn get_uint_le(&mut self, nbytes: usize) -> u64 ⓘ
fn get_uint_le(&mut self, nbytes: usize) -> u64 ⓘ
self
in little-endian byte order. Read more§fn get_uint_ne(&mut self, nbytes: usize) -> u64 ⓘ
fn get_uint_ne(&mut self, nbytes: usize) -> u64 ⓘ
self
in native-endian byte order. Read more§fn get_int(&mut self, nbytes: usize) -> i64 ⓘ
fn get_int(&mut self, nbytes: usize) -> i64 ⓘ
self
in big-endian byte order. Read more§fn get_int_le(&mut self, nbytes: usize) -> i64 ⓘ
fn get_int_le(&mut self, nbytes: usize) -> i64 ⓘ
self
in little-endian byte order. Read more§fn get_int_ne(&mut self, nbytes: usize) -> i64 ⓘ
fn get_int_ne(&mut self, nbytes: usize) -> i64 ⓘ
self
in native-endian byte order. Read more§fn get_f32(&mut self) -> f32 ⓘ
fn get_f32(&mut self) -> f32 ⓘ
self
in big-endian byte order. Read more§fn get_f32_le(&mut self) -> f32 ⓘ
fn get_f32_le(&mut self) -> f32 ⓘ
self
in little-endian byte order. Read more§fn get_f32_ne(&mut self) -> f32 ⓘ
fn get_f32_ne(&mut self) -> f32 ⓘ
self
in native-endian byte order. Read more§fn get_f64(&mut self) -> f64 ⓘ
fn get_f64(&mut self) -> f64 ⓘ
self
in big-endian byte order. Read more§fn get_f64_le(&mut self) -> f64 ⓘ
fn get_f64_le(&mut self) -> f64 ⓘ
self
in little-endian byte order. Read more§fn get_f64_ne(&mut self) -> f64 ⓘ
fn get_f64_ne(&mut self) -> f64 ⓘ
self
in native-endian byte order. Read more§fn copy_to_bytes(&mut self, len: usize) -> Bytes
fn copy_to_bytes(&mut self, len: usize) -> Bytes
1.75.0 · Source§impl<A> BufRead for VecDeque<u8, A>where
A: Allocator,
BufRead is implemented for VecDeque<u8>
by reading bytes from the front of the VecDeque
.
impl<A> BufRead for VecDeque<u8, A>where
A: Allocator,
BufRead is implemented for VecDeque<u8>
by reading bytes from the front of the VecDeque
.
Source§fn fill_buf(&mut self) -> Result<&[u8], Error> ⓘ
fn fill_buf(&mut self) -> Result<&[u8], Error> ⓘ
Returns the contents of the “front” slice as returned by
as_slices
. If the contained byte slices of the VecDeque
are
discontiguous, multiple calls to fill_buf
will be needed to read the entire content.
Source§fn consume(&mut self, amt: usize)
fn consume(&mut self, amt: usize)
amt
bytes have been consumed from the buffer,
so they should no longer be returned in calls to read
. Read moreSource§fn has_data_left(&mut self) -> Result<bool, Error> ⓘ
fn has_data_left(&mut self) -> Result<bool, Error> ⓘ
buf_read_has_data_left
)Read
has any data left to be read. Read more1.83.0 · Source§fn skip_until(&mut self, byte: u8) -> Result<usize, Error> ⓘ
fn skip_until(&mut self, byte: u8) -> Result<usize, Error> ⓘ
byte
or EOF is reached. Read more1.0.0 · Source§fn read_line(&mut self, buf: &mut String) -> Result<usize, Error> ⓘ
fn read_line(&mut self, buf: &mut String) -> Result<usize, Error> ⓘ
0xA
byte) is reached, and append
them to the provided String
buffer. Read more1.0.0 · Source§impl<T, A> Clone for VecDeque<T, A>
impl<T, A> Clone for VecDeque<T, A>
Source§fn clone_from(&mut self, source: &VecDeque<T, A>)
fn clone_from(&mut self, source: &VecDeque<T, A>)
Overwrites the contents of self
with a clone of the contents of source
.
This method is preferred over simply assigning source.clone()
to self
,
as it avoids reallocation if possible.
Source§impl<T> ConstDefault for VecDeque<T>
impl<T> ConstDefault for VecDeque<T>
Source§impl<T> DataCollection for VecDeque<T>
impl<T> DataCollection for VecDeque<T>
Source§fn collection_capacity(&self) -> Result<usize, NotAvailable> ⓘ
fn collection_capacity(&self) -> Result<usize, NotAvailable> ⓘ
Source§fn collection_len(&self) -> Result<usize, NotAvailable> ⓘ
fn collection_len(&self) -> Result<usize, NotAvailable> ⓘ
Source§fn collection_is_empty(&self) -> Result<bool, NotAvailable> ⓘ
fn collection_is_empty(&self) -> Result<bool, NotAvailable> ⓘ
true
if the collection is empty, false
if it’s not.Source§fn collection_is_full(&self) -> Result<bool, NotAvailable> ⓘ
fn collection_is_full(&self) -> Result<bool, NotAvailable> ⓘ
true
if the collection is full, false
if it’s not.Source§fn collection_contains(
&self,
element: Self::Element,
) -> Result<bool, NotAvailable> ⓘwhere
T: PartialEq,
fn collection_contains(
&self,
element: Self::Element,
) -> Result<bool, NotAvailable> ⓘwhere
T: PartialEq,
true
if the collection contains the given element
.Source§fn collection_count(
&self,
element: &Self::Element,
) -> Result<usize, NotAvailable> ⓘwhere
T: PartialEq,
fn collection_count(
&self,
element: &Self::Element,
) -> Result<usize, NotAvailable> ⓘwhere
T: PartialEq,
element
appears in the collection.Source§impl<T> DataDeque for VecDeque<T>
impl<T> DataDeque for VecDeque<T>
Source§fn queue_pop_back(
&mut self,
) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
fn queue_pop_back( &mut self, ) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
Source§fn queue_push_front(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace> ⓘ
fn queue_push_front( &mut self, element: <Self as DataCollection>::Element, ) -> Result<(), NotEnoughSpace> ⓘ
Source§fn queue_pop_front(
&mut self,
) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
fn queue_pop_front( &mut self, ) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
Source§fn queue_push_back(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace> ⓘ
fn queue_push_back( &mut self, element: <Self as DataCollection>::Element, ) -> Result<(), NotEnoughSpace> ⓘ
queue_push
). Read moreSource§impl<T> DataDesta for VecDeque<T>
impl<T> DataDesta for VecDeque<T>
Source§fn stack_pop_front(
&mut self,
) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
fn stack_pop_front( &mut self, ) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
Source§fn stack_push_front(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace> ⓘ
fn stack_push_front( &mut self, element: <Self as DataCollection>::Element, ) -> Result<(), NotEnoughSpace> ⓘ
Source§fn stack_pop_back(
&mut self,
) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
fn stack_pop_back( &mut self, ) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
DataStack::stack_pop
).Source§fn stack_push_back(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace> ⓘ
fn stack_push_back( &mut self, element: <Self as DataCollection>::Element, ) -> Result<(), NotEnoughSpace> ⓘ
DataStack::stack_push
).Source§impl<T> DataQueue for VecDeque<T>
impl<T> DataQueue for VecDeque<T>
Source§fn queue_pop(
&mut self,
) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
fn queue_pop( &mut self, ) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
Source§fn queue_push(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace> ⓘ
fn queue_push( &mut self, element: <Self as DataCollection>::Element, ) -> Result<(), NotEnoughSpace> ⓘ
Source§impl<T> DataStack for VecDeque<T>
impl<T> DataStack for VecDeque<T>
Source§fn stack_pop(
&mut self,
) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
fn stack_pop( &mut self, ) -> Result<<Self as DataCollection>::Element, NotEnoughElements> ⓘ
Source§fn stack_push(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace> ⓘ
fn stack_push( &mut self, element: <Self as DataCollection>::Element, ) -> Result<(), NotEnoughSpace> ⓘ
Source§impl<'de, T> Deserialize<'de> for VecDeque<T>where
T: Deserialize<'de>,
impl<'de, T> Deserialize<'de> for VecDeque<T>where
T: Deserialize<'de>,
Source§fn deserialize<D>(
deserializer: D,
) -> Result<VecDeque<T>, <D as Deserializer<'de>>::Error> ⓘwhere
D: Deserializer<'de>,
fn deserialize<D>(
deserializer: D,
) -> Result<VecDeque<T>, <D as Deserializer<'de>>::Error> ⓘwhere
D: Deserializer<'de>,
§impl<T, D> Deserialize<VecDeque<T>, D> for ArchivedVec<<T as Archive>::Archived>
impl<T, D> Deserialize<VecDeque<T>, D> for ArchivedVec<<T as Archive>::Archived>
1.2.0 · Source§impl<'a, T, A> Extend<&'a T> for VecDeque<T, A>
impl<'a, T, A> Extend<&'a T> for VecDeque<T, A>
Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a T>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a T>,
Source§fn extend_one(&mut self, _: &'a T)
fn extend_one(&mut self, _: &'a T)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)1.0.0 · Source§impl<T, A> Extend<T> for VecDeque<T, A>where
A: Allocator,
impl<T, A> Extend<T> for VecDeque<T, A>where
A: Allocator,
Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = T>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = T>,
Source§fn extend_one(&mut self, elem: T)
fn extend_one(&mut self, elem: T)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)1.10.0 · Source§impl<T, A> From<VecDeque<T, A>> for Vec<T, A>where
A: Allocator,
impl<T, A> From<VecDeque<T, A>> for Vec<T, A>where
A: Allocator,
Source§fn from(other: VecDeque<T, A>) -> Vec<T, A> ⓘ
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 std::collections::VecDeque;
// This one is *O*(1).
let deque: VecDeque<_> = (1..5).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).collect();
deque.push_front(9);
deque.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);
1.0.0 · Source§impl<T> FromIterator<T> for VecDeque<T>
impl<T> FromIterator<T> for VecDeque<T>
§impl<T> FromParallelIterator<T> for VecDeque<T>where
T: Send,
Collects items from a parallel iterator into a vecdeque.
impl<T> FromParallelIterator<T> for VecDeque<T>where
T: Send,
Collects items from a parallel iterator into a vecdeque.
§fn from_par_iter<I>(par_iter: I) -> VecDeque<T>where
I: IntoParallelIterator<Item = T>,
fn from_par_iter<I>(par_iter: I) -> VecDeque<T>where
I: IntoParallelIterator<Item = T>,
par_iter
. Read more1.0.0 · Source§impl<'a, T, A> IntoIterator for &'a VecDeque<T, A>where
A: Allocator,
impl<'a, T, A> IntoIterator for &'a VecDeque<T, A>where
A: Allocator,
1.0.0 · Source§impl<'a, T, A> IntoIterator for &'a mut VecDeque<T, A>where
A: Allocator,
impl<'a, T, A> IntoIterator for &'a mut VecDeque<T, A>where
A: Allocator,
1.0.0 · Source§impl<T, A> IntoIterator for VecDeque<T, A>where
A: Allocator,
impl<T, A> IntoIterator for VecDeque<T, A>where
A: Allocator,
§impl<'a, T> IntoParallelIterator for &'a VecDeque<T>where
T: Sync,
impl<'a, T> IntoParallelIterator for &'a VecDeque<T>where
T: Sync,
§impl<'a, T> IntoParallelIterator for &'a mut VecDeque<T>where
T: Send,
impl<'a, T> IntoParallelIterator for &'a mut VecDeque<T>where
T: Send,
§impl<T> IntoParallelIterator for VecDeque<T>where
T: Send,
impl<T> IntoParallelIterator for VecDeque<T>where
T: Send,
1.0.0 · Source§impl<T, A> Ord for VecDeque<T, A>
impl<T, A> Ord for VecDeque<T, A>
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
§impl<'a, T> ParallelDrainRange for &'a mut VecDeque<T>where
T: Send,
impl<'a, T> ParallelDrainRange for &'a mut VecDeque<T>where
T: Send,
§type Item = T
type Item = T
IntoParallelIterator::Item
.§fn par_drain<R>(
self,
range: R,
) -> <&'a mut VecDeque<T> as ParallelDrainRange>::Iter ⓘwhere
R: RangeBounds<usize>,
fn par_drain<R>(
self,
range: R,
) -> <&'a mut VecDeque<T> as ParallelDrainRange>::Iter ⓘwhere
R: RangeBounds<usize>,
§impl<'a, T> ParallelExtend<&'a T> for VecDeque<T>
Extends a deque with copied items from a parallel iterator.
impl<'a, T> ParallelExtend<&'a T> for VecDeque<T>
Extends a deque with copied items from a parallel iterator.
§fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = &'a T>,
fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = &'a T>,
par_iter
. Read more§impl<T> ParallelExtend<T> for VecDeque<T>where
T: Send,
Extends a deque with items from a parallel iterator.
impl<T> ParallelExtend<T> for VecDeque<T>where
T: Send,
Extends a deque with items from a parallel iterator.
§fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = T>,
fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = T>,
par_iter
. Read more§impl<T, U> PartialEq<VecDeque<U>> for ArchivedVec<T>where
T: PartialEq<U>,
impl<T, U> PartialEq<VecDeque<U>> for ArchivedVec<T>where
T: PartialEq<U>,
§impl<T> PartialOrd<VecDeque<T>> for ArchivedVec<T>where
T: PartialOrd,
impl<T> PartialOrd<VecDeque<T>> for ArchivedVec<T>where
T: PartialOrd,
1.0.0 · Source§impl<T, A> PartialOrd for VecDeque<T, A>where
T: PartialOrd,
A: Allocator,
impl<T, A> PartialOrd for VecDeque<T, A>where
T: PartialOrd,
A: Allocator,
1.63.0 · Source§impl<A> Read for VecDeque<u8, A>where
A: Allocator,
Read is implemented for VecDeque<u8>
by consuming bytes from the front of the VecDeque
.
impl<A> Read for VecDeque<u8, A>where
A: Allocator,
Read is implemented for VecDeque<u8>
by consuming bytes from the front of the VecDeque
.
Source§fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> ⓘ
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> ⓘ
Fill buf
with the contents of the “front” slice as returned by
as_slices
. If the contained byte slices of the VecDeque
are
discontiguous, multiple calls to read
will be needed to read the entire content.
Source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error> ⓘ
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error> ⓘ
buf
. Read moreSource§fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error> ⓘ
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error> ⓘ
read_buf
)Source§fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error> ⓘ
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error> ⓘ
read_buf
)cursor
. Read moreSource§fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error> ⓘ
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error> ⓘ
buf
. Read moreSource§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error> ⓘ
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error> ⓘ
buf
. Read more1.36.0 · Source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error> ⓘ
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error> ⓘ
read
, except that it reads into a slice of buffers. Read moreSource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector
)1.0.0 · Source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read
. Read moreSource§impl<T> Serialize for VecDeque<T>where
T: Serialize,
impl<T> Serialize for VecDeque<T>where
T: Serialize,
Source§fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> ⓘwhere
S: Serializer,
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> ⓘwhere
S: Serializer,
1.63.0 · Source§impl<A> Write for VecDeque<u8, A>where
A: Allocator,
Write is implemented for VecDeque<u8>
by appending to the VecDeque
, growing it as needed.
impl<A> Write for VecDeque<u8, A>where
A: Allocator,
Write is implemented for VecDeque<u8>
by appending to the VecDeque
, growing it as needed.
Source§fn write(&mut self, buf: &[u8]) -> Result<usize, Error> ⓘ
fn write(&mut self, buf: &[u8]) -> Result<usize, Error> ⓘ
Source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
)Source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error> ⓘ
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error> ⓘ
Source§fn flush(&mut self) -> Result<(), Error> ⓘ
fn flush(&mut self) -> Result<(), Error> ⓘ
Source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error> ⓘ
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error> ⓘ
write_all_vectored
)impl<T, A> Eq for VecDeque<T, A>
Auto Trait Implementations§
impl<T, A> Freeze for VecDeque<T, A>where
A: Freeze,
impl<T, A> RefUnwindSafe for VecDeque<T, A>where
A: RefUnwindSafe,
T: RefUnwindSafe,
impl<T, A> Send for VecDeque<T, A>
impl<T, A> Sync for VecDeque<T, A>
impl<T, A> Unpin for VecDeque<T, A>
impl<T, A> UnwindSafe for VecDeque<T, A>where
A: UnwindSafe,
T: UnwindSafe,
Blanket Implementations§
§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
§type ArchivedMetadata = ()
type ArchivedMetadata = ()
§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata,
) -> <T as Pointee>::Metadata
fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata
§impl<T> ArchiveUnsized for Twhere
T: Archive,
impl<T> ArchiveUnsized for Twhere
T: Archive,
§type Archived = <T as Archive>::Archived
type Archived = <T as Archive>::Archived
Archive
, it may be
unsized. Read more§fn archived_metadata(
&self,
) -> <<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata
fn archived_metadata( &self, ) -> <<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> ByteSized for T
impl<T> ByteSized for T
Source§const BYTE_ALIGN: usize = _
const BYTE_ALIGN: usize = _
Source§fn byte_align(&self) -> usize ⓘ
fn byte_align(&self) -> usize ⓘ
Source§fn ptr_size_ratio(&self) -> [usize; 2]
fn ptr_size_ratio(&self) -> [usize; 2]
Source§impl<T, R> Chain<R> for Twhere
T: ?Sized,
impl<T, R> Chain<R> for Twhere
T: ?Sized,
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.§impl<T> ExecutableCommand for T
impl<T> ExecutableCommand for T
§fn execute(&mut self, command: impl Command) -> Result<&mut T, Error> ⓘ
fn execute(&mut self, command: impl Command) -> Result<&mut T, Error> ⓘ
Executes the given command directly.
The given command its ANSI escape code will be written and flushed onto Self
.
§Arguments
-
The command that you want to execute directly.
§Example
use std::io;
use crossterm::{ExecutableCommand, style::Print};
fn main() -> io::Result<()> {
// will be executed directly
io::stdout()
.execute(Print("sum:\n".to_string()))?
.execute(Print(format!("1 + 1= {} ", 1 + 1)))?;
Ok(())
// ==== Output ====
// sum:
// 1 + 1 = 2
}
Have a look over at the Command API for more details.
§Notes
- In the case of UNIX and Windows 10, ANSI codes are written to the given ‘writer’.
- In case of Windows versions lower than 10, a direct WinAPI call will be made.
The reason for this is that Windows versions lower than 10 do not support ANSI codes,
and can therefore not be written to the given
writer
. Therefore, there is no difference between execute and queue for those old Windows versions.
Source§impl<T> ExtAny for T
impl<T> ExtAny for T
Source§fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
Source§impl<T> ExtMem for Twhere
T: ?Sized,
impl<T> ExtMem for Twhere
T: ?Sized,
Source§const NEEDS_DROP: bool = _
const NEEDS_DROP: bool = _
Source§fn mem_align_of_val(&self) -> usize ⓘ
fn mem_align_of_val(&self) -> usize ⓘ
Source§fn mem_size_of_val(&self) -> usize ⓘ
fn mem_size_of_val(&self) -> usize ⓘ
Source§fn mem_needs_drop(&self) -> bool
fn mem_needs_drop(&self) -> bool
true
if dropping values of this type matters. Read moreSource§fn mem_forget(self)where
Self: Sized,
fn mem_forget(self)where
Self: Sized,
self
without running its destructor. Read moreSource§fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
Source§unsafe fn mem_zeroed<T>() -> T
unsafe fn mem_zeroed<T>() -> T
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSource§unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSource§fn mem_as_bytes(&self) -> &[u8] ⓘ
fn mem_as_bytes(&self) -> &[u8] ⓘ
unsafe_slice
only.§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> Hook for T
impl<T> Hook for T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more§impl<'data, I> IntoParallelRefIterator<'data> for I
impl<'data, I> IntoParallelRefIterator<'data> for I
§type Iter = <&'data I as IntoParallelIterator>::Iter
type Iter = <&'data I as IntoParallelIterator>::Iter
§type Item = <&'data I as IntoParallelIterator>::Item
type Item = <&'data I as IntoParallelIterator>::Item
&'data T
reference type.§fn par_iter(&'data self) -> <I as IntoParallelRefIterator<'data>>::Iter
fn par_iter(&'data self) -> <I as IntoParallelRefIterator<'data>>::Iter
self
into a parallel iterator. Read more§impl<'data, I> IntoParallelRefMutIterator<'data> for I
impl<'data, I> IntoParallelRefMutIterator<'data> for I
§type Iter = <&'data mut I as IntoParallelIterator>::Iter
type Iter = <&'data mut I as IntoParallelIterator>::Iter
§type Item = <&'data mut I as IntoParallelIterator>::Item
type Item = <&'data mut I as IntoParallelIterator>::Item
&'data mut T
reference.§fn par_iter_mut(
&'data mut self,
) -> <I as IntoParallelRefMutIterator<'data>>::Iter
fn par_iter_mut( &'data mut self, ) -> <I as IntoParallelRefMutIterator<'data>>::Iter
self
. Read more§impl<'py, T, I> IntoPyDict<'py> for Iwhere
T: PyDictItem<'py>,
I: IntoIterator<Item = T>,
impl<'py, T, I> IntoPyDict<'py> for Iwhere
T: PyDictItem<'py>,
I: IntoIterator<Item = T>,
§fn into_py_dict(self, py: Python<'py>) -> Result<Bound<'py, PyDict>, PyErr> ⓘ
fn into_py_dict(self, py: Python<'py>) -> Result<Bound<'py, PyDict>, PyErr> ⓘ
PyDict
object pointer. Whether pointer owned or borrowed
depends on implementation.§fn into_py_dict_bound(self, py: Python<'py>) -> Bound<'py, PyDict>
fn into_py_dict_bound(self, py: Python<'py>) -> Bound<'py, PyDict>
IntoPyDict::into_py_dict
IntoPyDict::into_py_dict
.§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
§impl<T> LayoutRaw for T
impl<T> LayoutRaw for T
§fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError> ⓘ
fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError> ⓘ
§impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
§unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
§fn resolve_niched(out: Place<NichedOption<T, N1>>)
fn resolve_niched(out: Place<NichedOption<T, N1>>)
out
indicating that a T
is niched.§impl<T> Pointable for T
impl<T> Pointable for T
§impl<T> QueueableCommand for T
impl<T> QueueableCommand for T
§fn queue(&mut self, command: impl Command) -> Result<&mut T, Error> ⓘ
fn queue(&mut self, command: impl Command) -> Result<&mut T, Error> ⓘ
Queues the given command for further execution.
Queued commands will be executed in the following cases:
- When
flush
is called manually on the given type implementingio::Write
. - The terminal will
flush
automatically if the buffer is full. - Each line is flushed in case of
stdout
, because it is line buffered.
§Arguments
-
The command that you want to queue for later execution.
§Examples
use std::io::{self, Write};
use crossterm::{QueueableCommand, style::Print};
fn main() -> io::Result<()> {
let mut stdout = io::stdout();
// `Print` will executed executed when `flush` is called.
stdout
.queue(Print("foo 1\n".to_string()))?
.queue(Print("foo 2".to_string()))?;
// some other code (no execution happening here) ...
// when calling `flush` on `stdout`, all commands will be written to the stdout and therefore executed.
stdout.flush()?;
Ok(())
// ==== Output ====
// foo 1
// foo 2
}
Have a look over at the Command API for more details.
§Notes
- In the case of UNIX and Windows 10, ANSI codes are written to the given ‘writer’.
- In case of Windows versions lower than 10, a direct WinAPI call will be made.
The reason for this is that Windows versions lower than 10 do not support ANSI codes,
and can therefore not be written to the given
writer
. Therefore, there is no difference between execute and queue for those old Windows versions.
§impl<T, S> SerializeUnsized<S> for T
impl<T, S> SerializeUnsized<S> for T
§impl<W> SynchronizedUpdate for W
impl<W> SynchronizedUpdate for W
§fn sync_update<T>(
&mut self,
operations: impl FnOnce(&mut W) -> T,
) -> Result<T, Error> ⓘ
fn sync_update<T>( &mut self, operations: impl FnOnce(&mut W) -> T, ) -> Result<T, Error> ⓘ
Performs a set of actions within a synchronous update.
Updates will be suspended in the terminal, the function will be executed against self, updates will be resumed, and a flush will be performed.
§Arguments
-
Function
A function that performs the operations that must execute in a synchronized update.
§Examples
use std::io;
use crossterm::{ExecutableCommand, SynchronizedUpdate, style::Print};
fn main() -> io::Result<()> {
let mut stdout = io::stdout();
stdout.sync_update(|stdout| {
stdout.execute(Print("foo 1\n".to_string()))?;
stdout.execute(Print("foo 2".to_string()))?;
// The effects of the print command will not be present in the terminal
// buffer, but not visible in the terminal.
std::io::Result::Ok(())
})?;
// The effects of the commands will be visible.
Ok(())
// ==== Output ====
// foo 1
// foo 2
}
§Notes
This command is performed only using ANSI codes, and will do nothing on terminals that do not support ANSI codes, or this specific extension.
When rendering the screen of the terminal, the Emulator usually iterates through each visible grid cell and renders its current state. With applications updating the screen a at higher frequency this can cause tearing.
This mode attempts to mitigate that.
When the synchronization mode is enabled following render calls will keep rendering the last rendered state. The terminal Emulator keeps processing incoming text and sequences. When the synchronized update mode is disabled again the renderer may fetch the latest screen buffer state again, effectively avoiding the tearing effect by unintentionally rendering in the middle a of an application screen update.