GenericArrayDeque

Struct GenericArrayDeque 

Source
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>

Source

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,

Source

pub fn extract_if<F, R>( &mut self, range: R, filter: F, ) -> ExtractIf<'_, T, F, N>
where F: FnMut(&mut T) -> bool, R: RangeBounds<usize>,

Available on crate feature 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>

Source

pub fn pop_front_if( &mut self, predicate: impl FnOnce(&mut T) -> bool, ) -> Option<T>

Available on crate feature 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);
Source

pub fn pop_back_if( &mut self, predicate: impl FnOnce(&mut T) -> bool, ) -> Option<T>

Available on crate feature 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);
Source

pub const fn push_back_mut(&mut self, value: T) -> Result<&mut T, T>

Available on crate feature 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());
Source

pub const fn push_front_mut(&mut self, value: T) -> Result<&mut T, T>

Available on crate feature 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());
Source

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

Available on crate feature 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][..], &[][..]));
Source

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

Available on crate feature 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>

Source

pub fn extend_from_within<R>(&mut self, src: R) -> bool
where R: RangeBounds<usize>,

Available on crate feature 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", "!"]);
Source

pub fn prepend_from_within<R>(&mut self, src: R) -> bool
where R: RangeBounds<usize>,

Available on crate feature 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>

Source

pub fn try_from_vec(vec: Vec<T>) -> Result<Self, Vec<T>>

Available on crate features 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,

Source

pub const fn new() -> Self

Creates an empty deque.

§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::U8};

let deque: GenericArrayDeque<u32, U8> = GenericArrayDeque::new();
Source

pub const fn from_array<const U: usize>(array: [T; U]) -> Self
where 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");
Source

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");
Source

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());
Source

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]);
}
Source

pub fn try_from_exact_iter<I>(iter: I) -> Result<Self, I::IntoIter>
where I: IntoIterator<Item = T>, I::IntoIter: ExactSizeIterator,

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());
Source

pub fn try_extend_from_exact_iter<I>(&mut self, iter: I) -> Option<I::IntoIter>
where I: IntoIterator<Item = T>, I::IntoIter: ExactSizeIterator,

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]);
Source

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::USIZE elements.
§Examples
use generic_arraydeque::{GenericArrayDeque, typenum::{U2, U4}};

let deque = unsafe { GenericArrayDeque::<u32, U4>::from_iter_unchecked(7..10) };
assert_eq!(deque.len(), 3);
Source

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);
Source

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);
Source

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);
Source

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());
Source

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());
Source

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

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

§Panics

Panics if the 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);
Source

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

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

§Panics

Panics if the 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]);
Source

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]);
Source

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]);
Source

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']);
Source

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, []);
Source

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);
Source

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]);
Source

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));
Source

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));
Source

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));
Source

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));
Source

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);
Source

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);
Source

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());
Source

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);
Source

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));
Source

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());
Source

pub const 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 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]);
Source

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 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 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]);
Source

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]);
}
Source

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]);
Source

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());
Source

pub fn contains(&self, x: &T) -> bool
where 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));

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.
Source

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

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)));
Source

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

Binary searches this 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)));
Source

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

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

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

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

See also binary_search, binary_search_by, and binary_search_by_key.

§Examples
use 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.
Source

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]);
Source

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]);
Source

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]);
Source

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']);
Source

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']);
Source

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

Retains only the elements specified by the predicate.

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

§Examples
use 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]);
Source

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

Retains only the elements specified by the predicate.

In other words, remove all elements e for which f(&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,

Source

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]);
Source

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.

Source§

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)

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

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

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

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

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

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

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

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

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

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

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

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

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

impl<T, N> Clone for GenericArrayDeque<T, N>
where T: Clone, N: ArrayLength,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T: Debug, N: ArrayLength> Debug for GenericArrayDeque<T, N>

Source§

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

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

impl<T, N> Default for GenericArrayDeque<T, N>
where N: ArrayLength,

Source§

fn default() -> Self

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

impl<'de, T: Deserialize<'de>, N: ArrayLength> Deserialize<'de> for GenericArrayDeque<T, N>

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T, N> Drop for GenericArrayDeque<T, N>
where N: ArrayLength,

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<T, N: ArrayLength> From<GenericArray<T, N>> for GenericArrayDeque<T, N>

Source§

fn from(arr: GenericArray<T, N>) -> Self

Converts to this type from the input type.
Source§

impl<T, N: ArrayLength> From<GenericArrayDeque<T, N>> for Vec<T>

Available on crate features std or alloc only.
Source§

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.
Source§

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>

Source§

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

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T, N: ArrayLength> Index<usize> for GenericArrayDeque<T, N>

Source§

type Output = T

The returned type after indexing.
Source§

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

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

impl<T, N: ArrayLength> IndexMut<usize> for GenericArrayDeque<T, N>

Source§

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

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

impl<'a, T, N: ArrayLength> IntoIterator for &'a GenericArrayDeque<T, N>

Source§

type Item = &'a T

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, T>

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

fn into_iter(self) -> Iter<'a, T>

Creates an iterator from a value. Read more
Source§

impl<'a, T, N: ArrayLength> IntoIterator for &'a mut GenericArrayDeque<T, N>

Source§

type Item = &'a mut T

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, T>

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

fn into_iter(self) -> IterMut<'a, T>

Creates an iterator from a value. Read more
Source§

impl<T, N: ArrayLength> IntoIterator for GenericArrayDeque<T, N>

Source§

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

Consumes the deque into a front-to-back iterator yielding elements by value.

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<T, N>

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

impl<T: Ord, N: ArrayLength> Ord for GenericArrayDeque<T, N>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<T, U, L: ArrayLength> PartialEq<&[U]> for GenericArrayDeque<T, L>
where T: PartialEq<U>,

Source§

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

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

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T, U, L: ArrayLength, const N: usize> PartialEq<&[U; N]> for GenericArrayDeque<T, L>
where T: PartialEq<U>,

Source§

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

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

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T, U, L: ArrayLength> PartialEq<&mut [U]> for GenericArrayDeque<T, L>
where T: PartialEq<U>,

Source§

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

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

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T, U, L: ArrayLength, const N: usize> PartialEq<&mut [U; N]> for GenericArrayDeque<T, L>
where T: PartialEq<U>,

Source§

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

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

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T, U, L: ArrayLength, const N: usize> PartialEq<[U; N]> for GenericArrayDeque<T, L>
where T: PartialEq<U>,

Source§

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

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

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: PartialEq, N1: ArrayLength, N2: ArrayLength> PartialEq<GenericArrayDeque<T, N2>> for GenericArrayDeque<T, N1>

Source§

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

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

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T, U, L: ArrayLength> PartialEq<Vec<U>> for GenericArrayDeque<T, L>
where T: PartialEq<U>,

Source§

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

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

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: PartialOrd, N: ArrayLength> PartialOrd for GenericArrayDeque<T, N>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<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.

Source§

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<()>

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

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

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

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

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

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

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

fn is_read_vectored(&self) -> bool

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

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

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

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

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

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

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

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

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

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

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

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

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

impl<T: Serialize, N: ArrayLength> Serialize for GenericArrayDeque<T, N>

Available on crate feature serde only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<T, N: ArrayLength, const SIZE: usize> TryFrom<[T; SIZE]> for GenericArrayDeque<T, N>

Source§

type Error = [T; SIZE]

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

fn try_from(arr: [T; SIZE]) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<T, N: ArrayLength> TryFrom<Vec<T>> for GenericArrayDeque<T, N>

Available on crate features std or alloc only.
Source§

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§

type Error = Vec<T>

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

impl<T, N: ArrayLength> TryFrom<VecDeque<T>> for GenericArrayDeque<T, N>

Available on crate features std or alloc only.
Source§

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§

type Error = VecDeque<T>

The type returned in the event of a conversion error.
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.

Source§

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

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

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

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

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

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

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

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

fn is_write_vectored(&self) -> bool

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

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

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

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

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

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

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

impl<T: Eq, N: ArrayLength> Eq for GenericArrayDeque<T, N>

Auto Trait Implementations§

§

impl<T, N> Freeze for GenericArrayDeque<T, N>

§

impl<T, N> RefUnwindSafe for GenericArrayDeque<T, N>

§

impl<T, N> Send for GenericArrayDeque<T, N>
where T: Send,

§

impl<T, N> Sync for GenericArrayDeque<T, N>
where T: Sync,

§

impl<T, N> Unpin for GenericArrayDeque<T, N>

§

impl<T, N> UnwindSafe for GenericArrayDeque<T, N>

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

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

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,