pub struct GenericArrayDeque<T, N>where
N: ArrayLength,{ /* private fields */ }Expand description
A fixed-capacity, stack-allocated double-ended queue (deque) backed by GenericArray.
GenericArrayDeque provides a ring buffer implementation with O(1) insertion and removal
at both ends. Unlike std::collections::VecDeque, it has a compile-time fixed capacity
and is entirely stack-allocated, making it suitable for no_std environments and
performance-critical code where heap allocation should be avoided.
§Capacity
The capacity is fixed at compile time and cannot be changed. Attempting to push elements beyond the capacity will return the element back without inserting it.
§Examples
Basic usage:
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
// Create a deque with capacity 8
let mut deque = GenericArrayDeque::<i32, U8>::new();
// Add elements to the back
assert!(deque.push_back(1).is_none());
assert!(deque.push_back(2).is_none());
// Add elements to the front
assert!(deque.push_front(0).is_none());
assert_eq!(deque.len(), 3);
assert_eq!(deque[0], 0);
assert_eq!(deque[1], 1);
assert_eq!(deque[2], 2);
// Remove elements
assert_eq!(deque.pop_front(), Some(0));
assert_eq!(deque.pop_back(), Some(2));
assert_eq!(deque.len(), 1);Using as a ring buffer:
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buffer = GenericArrayDeque::<_, U4>::new();
// Fill the buffer
for i in 0..4 {
assert!(buffer.push_back(i).is_none());
}
assert_eq!(buffer.len(), 4);
assert!(buffer.is_full());
// Attempting to push when full returns the element
assert_eq!(buffer.push_back(100), Some(100));
// Remove and add to maintain size
buffer.pop_front();
buffer.push_back(4);Iterating over elements:
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<_, U8>::new();
deque.push_back(1);
deque.push_back(2);
deque.push_back(3);
let sum: i32 = deque.iter().sum();
assert_eq!(sum, 6);
// Mutable iteration
for item in deque.iter_mut() {
*item *= 2;
}
assert_eq!(deque.iter().sum::<i32>(), 12);Implementations§
Source§impl<T, N: ArrayLength> GenericArrayDeque<T, N>
impl<T, N: ArrayLength> GenericArrayDeque<T, N>
Sourcepub fn drain<R>(&mut self, range: R) -> Drain<'_, T, N>where
R: RangeBounds<usize>,
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, N>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 range has start_bound > end_bound, or, if the range is
bounded on either end and past 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());Source§impl<T, N> GenericArrayDeque<T, N>where
N: ArrayLength,
impl<T, N> GenericArrayDeque<T, N>where
N: ArrayLength,
Sourcepub fn extract_if<F, R>(
&mut self,
range: R,
filter: F,
) -> ExtractIf<'_, T, F, N> ⓘ
Available on crate feature unstable only.
pub fn extract_if<F, R>( &mut self, range: R, filter: F, ) -> ExtractIf<'_, T, F, N> ⓘ
unstable only.Creates an iterator which uses a closure to determine if an element in the range should be removed.
If the closure returns true, the element is removed from the deque and yielded. If the closure
returns false, or panics, the element remains in the deque and will not be yielded.
Only elements that fall in the provided range are considered for extraction, but any elements after the range will still have to be moved if any element has been extracted.
If the returned ExtractIf is not exhausted, e.g. because it is dropped without iterating
or the iteration short-circuits, then the remaining elements will be retained.
Use retain_mut with a negated predicate if you do not need the returned iterator.
Using this method is equivalent to the following code:
let mut i = range.start;
let end_items = deq.len() - range.end;
while i < deq.len() - end_items {
if some_predicate(&mut deq[i]) {
let val = deq.remove(i).unwrap();
// your code here
} else {
i += 1;
}
}
But extract_if is easier to use. extract_if is also more efficient,
because it can backshift the elements of the array in bulk.
The iterator also lets you mutate the value of each element in the closure, regardless of whether you choose to keep or remove it.
§Panics
If range is out of bounds.
§Examples
Splitting a deque into even and odd values, reusing the original deque:
use generic_arraydeque::{GenericArrayDeque, typenum::U16};
let mut numbers = GenericArrayDeque::<_, U16>::try_from_iter([
1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15,
]).unwrap();
let mut evens = GenericArrayDeque::<_, U16>::new();
numbers.extract_if(.., |x| *x % 2 == 0).for_each(|value| {
assert!(evens.push_back(value).is_none());
});
let odds = numbers;
assert_eq!(
evens,
GenericArrayDeque::<_, U16>::try_from_iter([2, 4, 6, 8, 14]).unwrap()
);
assert_eq!(
odds,
GenericArrayDeque::<_, U16>::try_from_iter([1, 3, 5, 9, 11, 13, 15]).unwrap()
);Using the range argument to only process a part of the deque:
use generic_arraydeque::{GenericArrayDeque, typenum::U16};
let mut items = GenericArrayDeque::<_, U16>::try_from_iter([
0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2,
]).unwrap();
let mut ones = GenericArrayDeque::<_, U16>::new();
items.extract_if(7.., |x| *x == 1).for_each(|value| {
assert!(ones.push_back(value).is_none());
});
assert_eq!(
items,
GenericArrayDeque::<_, U16>::try_from_iter([0, 0, 0, 0, 0, 0, 0, 2, 2, 2]).unwrap()
);
assert_eq!(ones.len(), 3);Source§impl<T, N: ArrayLength> GenericArrayDeque<T, N>
impl<T, N: ArrayLength> GenericArrayDeque<T, N>
Sourcepub fn pop_front_if(
&mut self,
predicate: impl FnOnce(&mut T) -> bool,
) -> Option<T>
Available on crate feature unstable only.
pub fn pop_front_if( &mut self, predicate: impl FnOnce(&mut T) -> bool, ) -> Option<T>
unstable only.Removes and returns the first element from the deque if the predicate
returns true, or None if the predicate returns false or the deque
is empty (the predicate will not be called in that case).
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<i32, U8>::new();
for value in 0..5 {
assert!(deque.push_back(value).is_none());
}
let pred = |x: &mut i32| *x % 2 == 0;
assert_eq!(deque.pop_front_if(pred), Some(0));
assert_eq!(deque.front(), Some(&1));
assert_eq!(deque.pop_front_if(pred), None);Sourcepub fn pop_back_if(
&mut self,
predicate: impl FnOnce(&mut T) -> bool,
) -> Option<T>
Available on crate feature unstable only.
pub fn pop_back_if( &mut self, predicate: impl FnOnce(&mut T) -> bool, ) -> Option<T>
unstable only.Removes and returns the last element from the deque if the predicate
returns true, or None if the predicate returns false or the deque
is empty (the predicate will not be called in that case).
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<i32, U8>::new();
for value in 0..5 {
assert!(deque.push_back(value).is_none());
}
let pred = |x: &mut i32| *x % 2 == 0;
assert_eq!(deque.pop_back_if(pred), Some(4));
assert_eq!(deque.back(), Some(&3));
assert_eq!(deque.pop_back_if(pred), None);Sourcepub const fn push_back_mut(&mut self, value: T) -> Result<&mut T, T>
Available on crate feature unstable only.
pub const fn push_back_mut(&mut self, value: T) -> Result<&mut T, T>
unstable only.Appends an element to the back of the deque, returning a mutable reference to it if successful.
If the deque is at full capacity, returns the element back without modifying the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U2};
let mut deque: GenericArrayDeque<u32, U2> = GenericArrayDeque::new();
let elem_ref = deque.push_back_mut(10).unwrap();
*elem_ref += 5;
assert_eq!(*deque.get(0).unwrap(), 15);
let _ = deque.push_back_mut(20).unwrap();
assert!(deque.push_back_mut(30).is_err());Sourcepub const fn push_front_mut(&mut self, value: T) -> Result<&mut T, T>
Available on crate feature unstable only.
pub const fn push_front_mut(&mut self, value: T) -> Result<&mut T, T>
unstable only.Prepends an element to the front of the deque, returning a mutable reference to it if successful.
If the deque is at full capacity, returns the element back without modifying the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U2};
let mut deque: GenericArrayDeque<u32, U2> = GenericArrayDeque::new();
let elem_ref = deque.push_front_mut(10).unwrap();
*elem_ref += 5;
assert_eq!(*deque.get(0).unwrap(), 15);
let _ = deque.push_front_mut(20).unwrap();
assert!(deque.push_front_mut(30).is_err());Sourcepub fn truncate_front(&mut self, len: usize)
Available on crate feature unstable only.
pub fn truncate_front(&mut self, len: usize)
unstable only.Shortens the deque, keeping the last len elements and dropping
the rest.
If len is greater or equal to the deque’s current length, this has
no effect.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buf = GenericArrayDeque::<u32, U4>::new();
assert!(buf.push_front(5).is_none());
assert!(buf.push_front(10).is_none());
assert!(buf.push_front(15).is_none());
assert_eq!(buf.as_slices(), (&[15, 10, 5][..], &[][..]));
buf.truncate_front(1);
assert_eq!(buf.as_slices(), (&[5][..], &[][..]));Sourcepub const fn insert_mut(&mut self, index: usize, value: T) -> Result<&mut T, T>
Available on crate feature unstable only.
pub const fn insert_mut(&mut self, index: usize, value: T) -> Result<&mut T, T>
unstable only.Inserts an element at index within the deque, shifting all elements
with indices greater than or equal to index towards the back, and
returning a reference to it.
Returns Err(value) if index is strictly greater than the deque’s length or if
the deque is full.
Element at index 0 is the front of the queue.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<i32, U8>::try_from_iter([1, 2, 3]).unwrap();
let x = deque.insert_mut(1, 5).unwrap();
*x += 7;
assert_eq!(deque.into_iter().collect::<Vec<_>>(), vec![1, 12, 2, 3]);Source§impl<T: Clone, N: ArrayLength> GenericArrayDeque<T, N>
impl<T: Clone, N: ArrayLength> GenericArrayDeque<T, N>
Sourcepub fn extend_from_within<R>(&mut self, src: R) -> boolwhere
R: RangeBounds<usize>,
Available on crate feature unstable only.
pub fn extend_from_within<R>(&mut self, src: R) -> boolwhere
R: RangeBounds<usize>,
unstable only.Clones the elements at the range src and appends them to the end.
§Panics
Panics if the starting index is greater than the end index or if either index is greater than the length of the vector.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U20};
let mut characters = GenericArrayDeque::<_, U20>::try_from_exact_iter(['a', 'b', 'c', 'd', 'e']).unwrap();
characters.extend_from_within(2..);
assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
let mut numbers = GenericArrayDeque::<_, U20>::try_from_exact_iter([0, 1, 2, 3, 4]).unwrap();
numbers.extend_from_within(..2);
assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
let mut strings = GenericArrayDeque::<_, U20>::try_from_exact_iter([String::from("hello"), String::from("world"), String::from("!")]).unwrap();
strings.extend_from_within(1..=2);
assert_eq!(strings, ["hello", "world", "!", "world", "!"]);Sourcepub fn prepend_from_within<R>(&mut self, src: R) -> boolwhere
R: RangeBounds<usize>,
Available on crate feature unstable only.
pub fn prepend_from_within<R>(&mut self, src: R) -> boolwhere
R: RangeBounds<usize>,
unstable only.Clones the elements at the range src and prepends them to the front.
§Panics
Panics if the starting index is greater than the end index or if either index is greater than the length of the vector.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U20};
let mut characters = GenericArrayDeque::<_, U20>::try_from_exact_iter(['a'.to_string(), 'b'.to_string(), 'c'.to_string(), 'd'.to_string(), 'e'.to_string()]).unwrap();
characters.prepend_from_within(2..);
assert_eq!(characters, ['c'.to_string(), 'd'.to_string(), 'e'.to_string(), 'a'.to_string(), 'b'.to_string(), 'c'.to_string(), 'd'.to_string(), 'e'.to_string()]);
let mut numbers = GenericArrayDeque::<_, U20>::try_from_exact_iter(["0".to_string(), "1".to_string(), "2".to_string(), "3".to_string(), "4".to_string()]).unwrap();
numbers.prepend_from_within(..2);
assert_eq!(numbers, ["0".to_string(), "1".to_string(), "0".to_string(), "1".to_string(), "2".to_string(), "3".to_string(), "4".to_string()]);
let mut strings = GenericArrayDeque::<_, U20>::try_from_exact_iter([String::from("hello"), String::from("world"), String::from("!")]).unwrap();
strings.prepend_from_within(1..=2);
assert_eq!(strings, ["world", "!", "hello", "world", "!"]);Source§impl<T, N: ArrayLength> GenericArrayDeque<T, N>
impl<T, N: ArrayLength> GenericArrayDeque<T, N>
Sourcepub fn try_from_vec(vec: Vec<T>) -> Result<Self, Vec<T>>
Available on crate features std or alloc only.
pub fn try_from_vec(vec: Vec<T>) -> Result<Self, Vec<T>>
std or alloc only.Tries to create a deque from a vector.
If the vector contains more elements than the capacity of the deque,
the vector will be returned as an Err value.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::{U2, U4}};
let deque = GenericArrayDeque::<u32, U4>::try_from_vec(vec![1, 2]).unwrap();
assert_eq!(deque.len(), 2);
let result = GenericArrayDeque::<u32, U2>::try_from_vec(vec![1, 2, 3]);
assert!(result.is_err());
let deque = GenericArrayDeque::<String, U4>::try_from_vec(vec![String::from("1"), String::from("2"), String::from("3")]).unwrap();
assert_eq!(deque.len(), 3);
assert_eq!(deque[0].as_str(), "1");
assert_eq!(deque[1].as_str(), "2");
assert_eq!(deque[2].as_str(), "3");Source§impl<T, N> GenericArrayDeque<T, N>where
N: ArrayLength,
impl<T, N> GenericArrayDeque<T, N>where
N: ArrayLength,
Sourcepub const fn new() -> Self
pub const fn new() -> Self
Creates an empty deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let deque: GenericArrayDeque<u32, U8> = GenericArrayDeque::new();Sourcepub const fn from_array<const U: usize>(array: [T; U]) -> Selfwhere
Const<U>: IntoArrayLength<ArrayLength = N>,
pub const fn from_array<const U: usize>(array: [T; U]) -> Selfwhere
Const<U>: IntoArrayLength<ArrayLength = N>,
Convert a native array into GenericArrayDeque of the same length and type.
This is equivalent to using the standard From/Into trait methods, but avoids
constructing an intermediate GenericArrayDeque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
use std::string::String;
let deque = GenericArrayDeque::<String, U4>::from_array(["10".to_string(), "20".to_string(), "30".to_string(), "40".to_string()]);
assert_eq!(deque.len(), 4);
assert_eq!(deque[0].as_str(), "10");
assert_eq!(deque[1].as_str(), "20");
assert_eq!(deque[2].as_str(), "30");
assert_eq!(deque[3].as_str(), "40");Sourcepub const fn try_from_array<const SIZE: usize>(
arr: [T; SIZE],
) -> Result<Self, [T; SIZE]>
pub const fn try_from_array<const SIZE: usize>( arr: [T; SIZE], ) -> Result<Self, [T; SIZE]>
Tries to create a deque from an array.
If the array contains more elements than the capacity of the deque,
the array will be returned as an Err value.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::{U4, U2}};
let deque = GenericArrayDeque::<u32, U4>::try_from_array([1, 2, 3, 4]).unwrap();
assert_eq!(deque.len(), 4);
let err = GenericArrayDeque::<u32, U2>::try_from_array([1, 2, 3]);
assert!(err.is_err());
let deque = GenericArrayDeque::<String, U4>::try_from_array([
"one".to_string(),
"two".to_string(),
]).unwrap();
assert_eq!(deque.len(), 2);
assert_eq!(deque[0].as_str(), "one");
assert_eq!(deque[1].as_str(), "two");Sourcepub fn try_from_iter<I: IntoIterator<Item = T>>(
iter: I,
) -> Result<Self, (Self, Chain<Once<T>, I::IntoIter>)>
pub fn try_from_iter<I: IntoIterator<Item = T>>( iter: I, ) -> Result<Self, (Self, Chain<Once<T>, I::IntoIter>)>
Tries to create a deque from an iterator.
If the iterator yields more elements than the capacity of the deque,
the remaining elements will be returned as an Err value.
See also [try_from_exact_iter] which requires the iterator to yield exactly
the same number of elements as the capacity of the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::{U2, U4}};
let deque = GenericArrayDeque::<u32, U4>::try_from_iter([10, 20, 30]).unwrap();
assert_eq!(deque.len(), 3);
let result = GenericArrayDeque::<u32, U2>::try_from_iter(0..5);
assert!(result.is_err());Sourcepub fn try_extend_from_iter<I: IntoIterator<Item = T>>(
&mut self,
iter: I,
) -> Option<Chain<Once<T>, I::IntoIter>>
pub fn try_extend_from_iter<I: IntoIterator<Item = T>>( &mut self, iter: I, ) -> Option<Chain<Once<T>, I::IntoIter>>
Tries to extend the deque from an iterator.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut deque = GenericArrayDeque::<u32, U4>::new();
assert!(deque.try_extend_from_iter(0..2).is_none());
assert_eq!(deque.into_iter().collect::<Vec<_>>(), vec![0, 1]);
let mut deque = GenericArrayDeque::<u32, U4>::new();
if let Some(leftovers) = deque.try_extend_from_iter(0..5) {
assert_eq!(deque.len(), 4);
assert_eq!(leftovers.collect::<Vec<_>>(), vec![4]);
}Sourcepub fn try_from_exact_iter<I>(iter: I) -> Result<Self, I::IntoIter>
pub fn try_from_exact_iter<I>(iter: I) -> Result<Self, I::IntoIter>
Tries to create a deque from an iterator that knows its exact length.
If the iterator reports a length greater than the deque’s capacity,
the iterator will be returned as an Err value.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::{U2, U4}};
let deque = GenericArrayDeque::<u32, U4>::try_from_exact_iter(0..4).unwrap();
assert_eq!(deque.len(), 4);
let result = GenericArrayDeque::<u32, U4>::try_from_exact_iter(0..5);
assert!(result.is_err());Sourcepub fn try_extend_from_exact_iter<I>(&mut self, iter: I) -> Option<I::IntoIter>
pub fn try_extend_from_exact_iter<I>(&mut self, iter: I) -> Option<I::IntoIter>
Tries to extend the deque from an iterator that knows its exact length.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut deque = GenericArrayDeque::<u32, U4>::new();
assert!(deque.try_extend_from_exact_iter([0, 1, 2, 3]).is_none());
assert_eq!(deque.len(), 4);
let mut deque = GenericArrayDeque::<u32, U4>::new();
let leftovers = deque.try_extend_from_exact_iter([0, 1, 2, 3, 4]).unwrap();
assert_eq!(leftovers.collect::<Vec<_>>(), vec![0, 1, 2, 3, 4]);Sourcepub unsafe fn from_iter_unchecked<I: IntoIterator<Item = T>>(iter: I) -> Self
pub unsafe fn from_iter_unchecked<I: IntoIterator<Item = T>>(iter: I) -> Self
Creates a deque from an iterator without checking the number of elements and capacity of the deque.
§Safety
- The iterator must yield at most
N::USIZEelements.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::{U2, U4}};
let deque = unsafe { GenericArrayDeque::<u32, U4>::from_iter_unchecked(7..10) };
assert_eq!(deque.len(), 3);Sourcepub const fn capacity(&self) -> usize
pub const fn capacity(&self) -> usize
Returns the capacity of the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let deque: GenericArrayDeque<u32, U8> = GenericArrayDeque::new();
assert_eq!(deque.capacity(), 8);Sourcepub const fn len(&self) -> usize
pub const fn len(&self) -> usize
Returns the number of elements in the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<u32, U8>::new();
assert_eq!(deque.len(), 0);
deque.push_back(1);
assert_eq!(deque.len(), 1);Sourcepub const fn remaining_capacity(&self) -> usize
pub const fn remaining_capacity(&self) -> usize
Returns how many more elements the deque can store without reallocating.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut deque = GenericArrayDeque::<u32, U4>::new();
assert_eq!(deque.remaining_capacity(), 4);
assert!(deque.push_back(10).is_none());
assert_eq!(deque.remaining_capacity(), 3);Sourcepub const fn is_empty(&self) -> bool
pub const fn is_empty(&self) -> bool
Returns true if the deque is empty.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<u32, U8>::new();
assert!(deque.is_empty());
deque.push_front(1);
assert!(!deque.is_empty());Sourcepub const fn is_full(&self) -> bool
pub const fn is_full(&self) -> bool
Returns true if the deque is at full capacity.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U2};
let mut deque: GenericArrayDeque<u32, U2> = GenericArrayDeque::new();
assert!(!deque.is_full());
assert!(deque.push_back(10).is_none());
assert!(!deque.is_full());
assert!(deque.push_back(20).is_none());
assert!(deque.is_full());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 range has start_bound > end_bound, or, if the range is
bounded on either end and past the length of the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let deque: GenericArrayDeque<_, U4> = [1, 2, 3].try_into().unwrap();
let range: GenericArrayDeque<_, U4> = GenericArrayDeque::try_from_iter(deque.range(2..).copied()).unwrap();
assert_eq!(range, [3]);
// A full range covers all contents
let all = deque.range(..);
assert_eq!(all.len(), 3);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 range has start_bound > end_bound, or, if the range is
bounded on either end and past the length of the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut deque: GenericArrayDeque<_, U4> = [1, 2, 3].try_into().unwrap();
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]);Sourcepub fn iter(&self) -> Iter<'_, T> ⓘ
pub fn iter(&self) -> Iter<'_, T> ⓘ
Returns a front-to-back iterator.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buf = GenericArrayDeque::<i32, U4>::new();
assert!(buf.push_back(5).is_none());
assert!(buf.push_back(3).is_none());
assert!(buf.push_back(4).is_none());
let collected: Vec<&i32> = buf.iter().collect();
assert_eq!(collected, vec![&5, &3, &4]);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 generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buf = GenericArrayDeque::<i32, U4>::new();
assert!(buf.push_back(5).is_none());
assert!(buf.push_back(3).is_none());
assert!(buf.push_back(4).is_none());
for value in buf.iter_mut() {
*value -= 2;
}
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![3, 1, 2]);Sourcepub const fn split_off(&mut self, at: usize) -> Self
pub const fn split_off(&mut self, at: usize) -> Self
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 generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buf: GenericArrayDeque<_, U4> = ['a', 'b', 'c'].try_into().unwrap();
let buf2 = buf.split_off(1);
assert_eq!(buf, ['a']);
assert_eq!(buf2, ['b', 'c']);Sourcepub const fn append(&mut self, other: &mut Self) -> bool
pub const fn append(&mut self, other: &mut Self) -> bool
Moves all the elements of other into self, leaving other empty.
This operation is no-op if the combined length of both deques exceeds the capacity of self.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buf: GenericArrayDeque<_, U4> = [1, 2].try_into().unwrap();
let mut buf2: GenericArrayDeque<_, U4> = [3, 4].try_into().unwrap();
assert!(buf.append(&mut buf2));
assert_eq!(buf, [1, 2, 3, 4]);
assert_eq!(buf2, []);Sourcepub const fn as_slices(&self) -> (&[T], &[T])
pub const 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.
Otherwise, the exact split point depends on implementation details
and is not guaranteed.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<u32, U8>::new();
deque.push_back(0);
deque.push_back(1);
deque.push_back(2);
let expected = [0, 1, 2];
let (front, back) = deque.as_slices();
assert_eq!(&expected[..front.len()], front);
assert_eq!(&expected[front.len()..], back);
deque.push_front(10);
deque.push_front(9);
let expected = [9, 10, 0, 1, 2];
let (front, back) = deque.as_slices();
assert_eq!(&expected[..front.len()], front);
assert_eq!(&expected[front.len()..], back);Sourcepub const fn as_mut_slices(&mut self) -> (&mut [T], &mut [T])
pub const 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.
Otherwise, the exact split point depends on implementation details
and is not guaranteed.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<u32, U8>::new();
deque.push_back(0);
deque.push_back(1);
deque.push_front(10);
deque.push_front(9);
// Since the split point is not guaranteed, we may need to update
// either slice.
let mut update_nth = |index: usize, val: u32| {
let (front, back) = deque.as_mut_slices();
if index > front.len() - 1 {
back[index - front.len()] = val;
} else {
front[index] = val;
}
};
update_nth(0, 42);
update_nth(2, 24);
let v: Vec<_> = deque.into_iter().collect();
assert_eq!(v, [42, 10, 24, 1]);Sourcepub const fn front(&self) -> Option<&T>
pub const fn front(&self) -> Option<&T>
Provides a reference to the front element, or None if the deque is
empty.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut d = GenericArrayDeque::<u32, U8>::new();
assert_eq!(d.front(), None);
d.push_back(1);
d.push_back(2);
assert_eq!(d.front(), Some(&1));Sourcepub const fn front_mut(&mut self) -> Option<&mut T>
pub const 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 generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut d = GenericArrayDeque::<u32, U8>::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));Sourcepub const fn back(&self) -> Option<&T>
pub const fn back(&self) -> Option<&T>
Provides a reference to the back element, or None if the deque is
empty.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut d = GenericArrayDeque::<u32, U8>::new();
assert_eq!(d.back(), None);
d.push_back(1);
d.push_back(2);
assert_eq!(d.back(), Some(&2));Sourcepub const fn back_mut(&mut self) -> Option<&mut T>
pub const 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 generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut d = GenericArrayDeque::<u32, U8>::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));Sourcepub const fn get(&self, index: usize) -> Option<&T>
pub const fn get(&self, index: usize) -> Option<&T>
Provides a reference to the element at the given index.
Elements at index 0 is the front of the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque: GenericArrayDeque<u32, U8> = GenericArrayDeque::new();
assert!(deque.push_back(10).is_none());
assert!(deque.push_back(20).is_none());
assert_eq!(*deque.get(0).unwrap(), 10);
assert_eq!(*deque.get(1).unwrap(), 20);Sourcepub const fn get_mut(&mut self, index: usize) -> Option<&mut T>
pub const fn get_mut(&mut self, index: usize) -> Option<&mut T>
Provides a mutable reference to the element at the given index.
Elements at index 0 is the front of the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque: GenericArrayDeque<u32, U8> = GenericArrayDeque::new();
assert!(deque.push_back(10).is_none());
assert!(deque.push_back(20).is_none());
*deque.get_mut(0).unwrap() += 5;
assert_eq!(*deque.get(0).unwrap(), 15);Sourcepub const fn push_back(&mut self, value: T) -> Option<T>
pub const fn push_back(&mut self, value: T) -> Option<T>
Appends an element to the back of the deque, returning None if successful.
If the deque is at full capacity, returns the element back without modifying the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U2};
let mut deque: GenericArrayDeque<u32, U2> = GenericArrayDeque::new();
assert!(deque.push_back(10).is_none());
assert!(deque.push_back(20).is_none());
assert!(deque.push_back(30).is_some());Sourcepub const fn pop_front(&mut self) -> Option<T>
pub const fn pop_front(&mut self) -> Option<T>
Removes the first element and returns it, or None if the deque is
empty.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut d = GenericArrayDeque::<u32, U8>::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);Sourcepub const fn pop_back(&mut self) -> Option<T>
pub const 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 generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut buf = GenericArrayDeque::<u32, U8>::new();
assert_eq!(buf.pop_back(), None);
buf.push_back(1);
buf.push_back(3);
assert_eq!(buf.pop_back(), Some(3));Sourcepub const fn push_front(&mut self, value: T) -> Option<T>
pub const fn push_front(&mut self, value: T) -> Option<T>
Prepends an element to the front of the deque, returning None if successful.
If the deque is at full capacity, returns the element back without modifying the deque.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U2};
let mut deque: GenericArrayDeque<u32, U2> = GenericArrayDeque::new();
assert!(deque.push_front(10).is_none());
assert!(deque.push_front(20).is_none());
assert!(deque.push_front(30).is_some());Sourcepub const fn rotate_left(&mut self, n: usize)
pub const fn rotate_left(&mut self, n: usize)
Rotates the double-ended queue n places to the left.
Equivalently,
- Rotates item
ninto the first position. - Pops the first
nitems and pushes them to the end. - Rotates
len() - nplaces 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 generic_arraydeque::{GenericArrayDeque, typenum::U10};
let mut buf: GenericArrayDeque<u32, U10> = GenericArrayDeque::new();
for value in 0..10 {
assert!(buf.push_back(value).is_none());
}
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]);Sourcepub const fn rotate_right(&mut self, n: usize)
pub const 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
nitems and pushes them to the front. - Rotates
len() - nplaces 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 generic_arraydeque::{GenericArrayDeque, typenum::U10};
let mut buf: GenericArrayDeque<u32, U10> = GenericArrayDeque::new();
for value in 0..10 {
assert!(buf.push_back(value).is_none());
}
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]);Sourcepub const fn make_contiguous(&mut self) -> &mut [T]
pub const 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 generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut buf = GenericArrayDeque::<i32, U8>::new();
assert!(buf.push_back(2).is_none());
assert!(buf.push_back(1).is_none());
assert!(buf.push_front(3).is_none());
buf.make_contiguous().sort();
assert_eq!(buf.as_slices(), (&[1, 2, 3][..], &[][..]));
buf.make_contiguous().sort_by(|a, b| b.cmp(a));
assert_eq!(buf.as_slices(), (&[3, 2, 1][..], &[][..]));Getting immutable access to the contiguous slice.
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut buf = GenericArrayDeque::<i32, U8>::new();
assert!(buf.push_back(2).is_none());
assert!(buf.push_back(1).is_none());
assert!(buf.push_front(3).is_none());
buf.make_contiguous();
if let (slice, &[]) = buf.as_slices() {
assert_eq!(buf.len(), slice.len());
assert_eq!(slice, &[3, 2, 1]);
}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 generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut buf = GenericArrayDeque::<u32, U8>::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 clear(&mut self)
pub fn clear(&mut self)
Clears the deque, removing all values.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<u32, U8>::new();
deque.push_back(1);
deque.clear();
assert!(deque.is_empty());Sourcepub fn contains(&self, x: &T) -> boolwhere
T: PartialEq<T>,
pub fn contains(&self, x: &T) -> boolwhere
T: PartialEq<T>,
Returns true if the deque contains an element equal to the
given value.
This operation is O(n).
Note that if you have a sorted deque, binary_search may be faster.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut deque = GenericArrayDeque::<u32, U4>::new();
assert!(deque.push_back(0).is_none());
assert!(deque.push_back(1).is_none());
assert!(deque.contains(&1));
assert!(!deque.contains(&10));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 deque for a given element. If the deque 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 generic_arraydeque::{GenericArrayDeque, typenum::U16};
let deque = GenericArrayDeque::<i32, U16>::try_from_iter([
0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
]).unwrap();
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 generic_arraydeque::{GenericArrayDeque, typenum::U16};
let deque = GenericArrayDeque::<i32, U16>::try_from_iter([
0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
]).unwrap();
let num = 42;
let idx = deque.partition_point(|&x| x <= num);
// `idx` can now be used with `insert` to keep the deque sorted.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 deque 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 deque is not sorted or if the comparator function does not
implement an order consistent with the sort order of the underlying
deque, 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 generic_arraydeque::{GenericArrayDeque, typenum::U16};
let deque = GenericArrayDeque::<i32, U16>::try_from_iter([
0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
]).unwrap();
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)));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 deque 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 generic_arraydeque::{GenericArrayDeque, typenum::U16};
let deque = GenericArrayDeque::<(i32, i32), U16>::try_from_iter([
(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),
]).unwrap();
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)));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 generic_arraydeque::{GenericArrayDeque, typenum::U8};
let deque = GenericArrayDeque::<i32, U8>::try_from_iter([1, 2, 3, 3, 5, 6, 7]).unwrap();
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 generic_arraydeque::{GenericArrayDeque, typenum::U16};
let deque = GenericArrayDeque::<i32, U16>::try_from_iter([
0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
]).unwrap();
let num = 42;
let idx = deque.partition_point(|&x| x < num);
// The returned index indicates where `num` should be inserted.Sourcepub const fn swap(&mut self, i: usize, j: usize)
pub const 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 generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buf = GenericArrayDeque::<i32, U4>::new();
assert!(buf.push_back(3).is_none());
assert!(buf.push_back(4).is_none());
assert!(buf.push_back(5).is_none());
buf.swap(0, 2);
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 4, 3]);Sourcepub const fn swap_remove_front(&mut self, index: usize) -> Option<T>
pub const 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 generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buf = GenericArrayDeque::<i32, U4>::new();
assert_eq!(buf.swap_remove_front(0), None);
assert!(buf.push_back(1).is_none());
assert!(buf.push_back(2).is_none());
assert!(buf.push_back(3).is_none());
assert_eq!(buf.swap_remove_front(2), Some(3));
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![2, 1]);Sourcepub const fn swap_remove_back(&mut self, index: usize) -> Option<T>
pub const 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 generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buf = GenericArrayDeque::<i32, U4>::new();
assert_eq!(buf.swap_remove_back(0), None);
assert!(buf.push_back(1).is_none());
assert!(buf.push_back(2).is_none());
assert!(buf.push_back(3).is_none());
assert_eq!(buf.swap_remove_back(0), Some(1));
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![3, 2]);Sourcepub const fn insert(&mut self, index: usize, value: T) -> Option<T>
pub const fn insert(&mut self, index: usize, value: T) -> Option<T>
Inserts an element at index within the deque, shifting all elements
with indices greater than or equal to index towards the back.
Returns Some(value) if index is strictly greater than the deque’s length or if
the deque is full.
Element at index 0 is the front of the queue.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut deque = GenericArrayDeque::<char, U8>::new();
deque.push_back('a');
deque.push_back('b');
deque.push_back('c');
deque.insert(1, 'd');
deque.insert(4, 'e');
assert_eq!(deque.into_iter().collect::<Vec<_>>(), vec!['a', 'd', 'b', 'c', 'e']);Sourcepub const fn remove(&mut self, index: usize) -> Option<T>
pub const 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 generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut buf = GenericArrayDeque::<char, U4>::new();
assert!(buf.push_back('a').is_none());
assert!(buf.push_back('b').is_none());
assert!(buf.push_back('c').is_none());
assert_eq!(buf.remove(1), Some('b'));
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec!['a', 'c']);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 generic_arraydeque::{GenericArrayDeque, typenum::U10};
let mut buf = GenericArrayDeque::<i32, U10>::new();
for value in 1..5 {
assert!(buf.push_back(value).is_none());
}
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 generic_arraydeque::{GenericArrayDeque, typenum::U10};
let mut buf = GenericArrayDeque::<i32, U10>::new();
for value in 1..6 {
assert!(buf.push_back(value).is_none());
}
let keep = [false, true, true, false, true];
let mut iter = keep.iter();
buf.retain(|_| *iter.next().unwrap());
assert_eq!(buf, [2, 3, 5]);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 generic_arraydeque::{GenericArrayDeque, typenum::U10};
let mut buf = GenericArrayDeque::<i32, U10>::new();
for value in 1..5 {
assert!(buf.push_back(value).is_none());
}
buf.retain_mut(|x| if *x % 2 == 0 {
*x += 1;
true
} else {
false
});
assert_eq!(buf, [3, 5]);Source§impl<T, N> GenericArrayDeque<T, N>where
N: ArrayLength,
T: Clone,
impl<T, N> GenericArrayDeque<T, N>where
N: ArrayLength,
T: Clone,
Sourcepub fn resize(&mut self, new_len: usize, value: T) -> Option<T>
pub fn resize(&mut self, new_len: usize, value: T) -> Option<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.
If the deque is full and needs to be extended, returns Some(value) back, the
deque is not modified in that case.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut buf = GenericArrayDeque::<u32, U8>::new();
assert!(buf.push_back(5).is_none());
assert!(buf.push_back(10).is_none());
assert!(buf.push_back(15).is_none());
buf.resize(2, 0);
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10]);
let mut buf = GenericArrayDeque::<u32, U8>::new();
assert!(buf.push_back(5).is_none());
assert!(buf.push_back(10).is_none());
buf.resize(5, 20);
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10, 20, 20, 20]);Sourcepub fn resize_with(
&mut self,
new_len: usize,
generator: impl FnMut() -> T,
) -> bool
pub fn resize_with( &mut self, new_len: usize, generator: impl FnMut() -> T, ) -> bool
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.
If the deque is full and needs to be extended, returns false, the
deque is not modified in that case.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};
let mut buf = GenericArrayDeque::<u32, U8>::new();
assert!(buf.push_back(5).is_none());
assert!(buf.push_back(10).is_none());
assert!(buf.push_back(15).is_none());
buf.resize_with(5, Default::default);
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10, 15, 0, 0]);
let mut buf = GenericArrayDeque::<u32, U8>::new();
assert!(buf.push_back(5).is_none());
assert!(buf.push_back(10).is_none());
assert!(buf.push_back(15).is_none());
buf.resize_with(2, || unreachable!());
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10]);
let mut buf = GenericArrayDeque::<u32, U8>::new();
assert!(buf.push_back(5).is_none());
assert!(buf.push_back(10).is_none());
let mut state = 100;
buf.resize_with(5, || {
state += 1;
state
});
assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10, 101, 102, 103]);Trait Implementations§
Source§impl<N: ArrayLength> BufRead for GenericArrayDeque<u8, N>
Available on crate feature std only.BufRead is implemented for GenericArrayDeque<u8> by reading bytes from the front of the GenericArrayDeque.
impl<N: ArrayLength> BufRead for GenericArrayDeque<u8, N>
std only.BufRead is implemented for GenericArrayDeque<u8> by reading bytes from the front of the GenericArrayDeque.
Source§fn fill_buf(&mut self) -> Result<&[u8]>
fn fill_buf(&mut self) -> Result<&[u8]>
Returns the contents of the “front” slice as returned by
as_slices. If the contained byte slices of the GenericArrayDeque 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)
amount of additional bytes from the internal buffer as having been read.
Subsequent calls to read only return bytes that have not been marked as read. Read 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. 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 moreSource§impl<T, N> Clone for GenericArrayDeque<T, N>where
T: Clone,
N: ArrayLength,
impl<T, N> Clone for GenericArrayDeque<T, N>where
T: Clone,
N: ArrayLength,
Source§impl<T: Debug, N: ArrayLength> Debug for GenericArrayDeque<T, N>
impl<T: Debug, N: ArrayLength> Debug for GenericArrayDeque<T, N>
Source§impl<T, N> Default for GenericArrayDeque<T, N>where
N: ArrayLength,
impl<T, N> Default for GenericArrayDeque<T, N>where
N: ArrayLength,
Source§impl<'de, T: Deserialize<'de>, N: ArrayLength> Deserialize<'de> for GenericArrayDeque<T, N>
Available on crate feature serde only.
impl<'de, T: Deserialize<'de>, N: ArrayLength> Deserialize<'de> for GenericArrayDeque<T, N>
serde only.Source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Source§impl<T, N> Drop for GenericArrayDeque<T, N>where
N: ArrayLength,
impl<T, N> Drop for GenericArrayDeque<T, N>where
N: ArrayLength,
Source§impl<T, N: ArrayLength> From<GenericArray<T, N>> for GenericArrayDeque<T, N>
impl<T, N: ArrayLength> From<GenericArray<T, N>> for GenericArrayDeque<T, N>
Source§fn from(arr: GenericArray<T, N>) -> Self
fn from(arr: GenericArray<T, N>) -> Self
Source§impl<T, N: ArrayLength> From<GenericArrayDeque<T, N>> for Vec<T>
Available on crate features std or alloc only.
impl<T, N: ArrayLength> From<GenericArrayDeque<T, N>> for Vec<T>
std or alloc only.Source§fn from(deq: GenericArrayDeque<T, N>) -> Self
fn from(deq: GenericArrayDeque<T, N>) -> Self
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
let mut deque = GenericArrayDeque::<i32, U4>::new();
deque.push_back(10);
deque.push_back(20);
deque.push_back(30);
let vec: Vec<i32> = Vec::from(deque);
assert_eq!(vec, vec![10, 20, 30]);Source§impl<T, N: ArrayLength> From<GenericArrayDeque<T, N>> for VecDeque<T>
Available on crate features std or alloc only.
impl<T, N: ArrayLength> From<GenericArrayDeque<T, N>> for VecDeque<T>
std or alloc only.Source§fn from(deq: GenericArrayDeque<T, N>) -> Self
fn from(deq: GenericArrayDeque<T, N>) -> Self
use generic_arraydeque::{GenericArrayDeque, typenum::U4};
use std::collections::VecDeque;
let mut deque = GenericArrayDeque::<i32, U4>::new();
deque.push_back(10);
deque.push_back(20);
deque.push_back(30);
let vec_deque: VecDeque<i32> = VecDeque::from(deque);
assert_eq!(vec_deque, VecDeque::from(vec![10, 20, 30]));Source§impl<T: Hash, N: ArrayLength> Hash for GenericArrayDeque<T, N>
impl<T: Hash, N: ArrayLength> Hash for GenericArrayDeque<T, N>
Source§impl<T, N: ArrayLength> Index<usize> for GenericArrayDeque<T, N>
impl<T, N: ArrayLength> Index<usize> for GenericArrayDeque<T, N>
Source§impl<T, N: ArrayLength> IndexMut<usize> for GenericArrayDeque<T, N>
impl<T, N: ArrayLength> IndexMut<usize> for GenericArrayDeque<T, N>
Source§impl<'a, T, N: ArrayLength> IntoIterator for &'a GenericArrayDeque<T, N>
impl<'a, T, N: ArrayLength> IntoIterator for &'a GenericArrayDeque<T, N>
Source§impl<'a, T, N: ArrayLength> IntoIterator for &'a mut GenericArrayDeque<T, N>
impl<'a, T, N: ArrayLength> IntoIterator for &'a mut GenericArrayDeque<T, N>
Source§impl<T, N: ArrayLength> IntoIterator for GenericArrayDeque<T, N>
impl<T, N: ArrayLength> IntoIterator for GenericArrayDeque<T, N>
Source§impl<T: Ord, N: ArrayLength> Ord for GenericArrayDeque<T, N>
impl<T: Ord, N: ArrayLength> Ord for GenericArrayDeque<T, N>
Source§impl<T, U, L: ArrayLength> PartialEq<&[U]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
impl<T, U, L: ArrayLength> PartialEq<&[U]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
Source§impl<T, U, L: ArrayLength, const N: usize> PartialEq<&[U; N]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
impl<T, U, L: ArrayLength, const N: usize> PartialEq<&[U; N]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
Source§impl<T, U, L: ArrayLength> PartialEq<&mut [U]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
impl<T, U, L: ArrayLength> PartialEq<&mut [U]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
Source§impl<T, U, L: ArrayLength, const N: usize> PartialEq<&mut [U; N]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
impl<T, U, L: ArrayLength, const N: usize> PartialEq<&mut [U; N]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
Source§impl<T, U, L: ArrayLength, const N: usize> PartialEq<[U; N]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
impl<T, U, L: ArrayLength, const N: usize> PartialEq<[U; N]> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
Source§impl<T: PartialEq, N1: ArrayLength, N2: ArrayLength> PartialEq<GenericArrayDeque<T, N2>> for GenericArrayDeque<T, N1>
impl<T: PartialEq, N1: ArrayLength, N2: ArrayLength> PartialEq<GenericArrayDeque<T, N2>> for GenericArrayDeque<T, N1>
Source§impl<T, U, L: ArrayLength> PartialEq<Vec<U>> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
impl<T, U, L: ArrayLength> PartialEq<Vec<U>> for GenericArrayDeque<T, L>where
T: PartialEq<U>,
Source§impl<T: PartialOrd, N: ArrayLength> PartialOrd for GenericArrayDeque<T, N>
impl<T: PartialOrd, N: ArrayLength> PartialOrd for GenericArrayDeque<T, N>
Source§impl<N: ArrayLength> Read for GenericArrayDeque<u8, N>
Available on crate feature std only.Read is implemented for GenericArrayDeque<u8> by consuming bytes from the front of the GenericArrayDeque.
impl<N: ArrayLength> Read for GenericArrayDeque<u8, N>
std only.Read is implemented for GenericArrayDeque<u8> by consuming bytes from the front of the GenericArrayDeque.
Source§fn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
Fill buf with the contents of the “front” slice as returned by
as_slices. If the contained byte slices of the GenericArrayDeque are
discontiguous, multiple calls to read will be needed to read the entire content.
Source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
buf. Read moreSource§fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
buf. Read moreSource§fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
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)Source§fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf(&mut self, buf: 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 more1.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, N: ArrayLength> Serialize for GenericArrayDeque<T, N>
Available on crate feature serde only.
impl<T: Serialize, N: ArrayLength> Serialize for GenericArrayDeque<T, N>
serde only.Source§impl<T, N: ArrayLength, const SIZE: usize> TryFrom<[T; SIZE]> for GenericArrayDeque<T, N>
impl<T, N: ArrayLength, const SIZE: usize> TryFrom<[T; SIZE]> for GenericArrayDeque<T, N>
Source§impl<T, N: ArrayLength> TryFrom<Vec<T>> for GenericArrayDeque<T, N>
Available on crate features std or alloc only.
impl<T, N: ArrayLength> TryFrom<Vec<T>> for GenericArrayDeque<T, N>
std or alloc only.Source§fn try_from(vec: Vec<T>) -> Result<Self, Self::Error>
fn try_from(vec: Vec<T>) -> Result<Self, Self::Error>
use generic_arraydeque::{GenericArrayDeque, typenum::{U4, U2}};
use std::vec::Vec;
let deque = GenericArrayDeque::<i32, U4>::try_from(vec![1, 2, 3]).unwrap();
assert_eq!(deque.len(), 3);
let result = GenericArrayDeque::<i32, U2>::try_from(vec![1, 2, 3]);
assert!(result.is_err());Source§impl<T, N: ArrayLength> TryFrom<VecDeque<T>> for GenericArrayDeque<T, N>
Available on crate features std or alloc only.
impl<T, N: ArrayLength> TryFrom<VecDeque<T>> for GenericArrayDeque<T, N>
std or alloc only.Source§fn try_from(vec_deq: VecDeque<T>) -> Result<Self, Self::Error>
fn try_from(vec_deq: VecDeque<T>) -> Result<Self, Self::Error>
use generic_arraydeque::{GenericArrayDeque, typenum::{U4, U2}};
use std::collections::VecDeque;
let deque = GenericArrayDeque::<i32, U4>::try_from(VecDeque::from(vec![1, 2, 3])).unwrap();
assert_eq!(deque.len(), 3);
let result = GenericArrayDeque::<i32, U2>::try_from(VecDeque::from(vec![1, 2, 3]));
assert!(result.is_err());Source§impl<N: ArrayLength> Write for GenericArrayDeque<u8, N>
Available on crate feature std only.Write is implemented for GenericArrayDeque<u8> by appending to the GenericArrayDeque, growing it as needed.
impl<N: ArrayLength> Write for GenericArrayDeque<u8, N>
std only.Write is implemented for GenericArrayDeque<u8> by appending to the GenericArrayDeque, growing it as needed.
Source§fn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
Source§fn write_all(&mut self, buf: &[u8]) -> Result<()>
fn write_all(&mut self, buf: &[u8]) -> Result<()>
Source§fn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
Source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector)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)