Skip to main content

generic_arraydeque/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(not(feature = "std"), no_std)]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4#![cfg_attr(docsrs, allow(unused_attributes))]
5#![deny(missing_docs)]
6
7#[cfg(all(not(feature = "std"), feature = "alloc"))]
8extern crate alloc as std;
9
10#[cfg(feature = "std")]
11extern crate std;
12
13use core::{
14  cmp::Ordering,
15  fmt,
16  hash::{Hash, Hasher},
17  iter::{Chain, Once, once, repeat_with},
18  mem::{self, ManuallyDrop, MaybeUninit},
19  ops::{self, Index, IndexMut, Range, RangeBounds},
20  ptr, slice,
21};
22use generic_array::GenericArray;
23use macros::*;
24
25pub use generic_array::{ArrayLength, ConstArrayLength, IntoArrayLength, typenum};
26pub use into_iter::IntoIter;
27pub use iter::Iter;
28pub use iter_mut::IterMut;
29
30#[cfg(feature = "unstable")]
31#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
32pub use unstable::ExtractIf;
33
34mod drain;
35
36mod into_iter;
37#[cfg(feature = "std")]
38mod io;
39mod iter;
40mod iter_mut;
41#[cfg(feature = "serde")]
42#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
43mod serde;
44
45#[cfg(all(test, any(feature = "std", feature = "alloc")))]
46mod heap_tests;
47#[cfg(test)]
48mod tests;
49
50#[cfg(feature = "unstable")]
51#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
52mod unstable;
53
54mod macros;
55
56/// Re-export of the `generic_array` crate for better interoperability.
57pub use generic_array as array;
58
59/// [`ArrayDeque`] with a const-generic `usize` length, using the [`ConstArrayLength`] type alias for `N`.
60///
61/// To construct from a literal array, use [`from_array`](ArrayDeque::from_array).
62///
63/// Note that not all `N` values are valid due to limitations inherent to `typenum` and Rust. You
64/// may need to combine [Const] with other typenum operations to get the desired length.
65pub type ConstArrayDeque<T, const N: usize> = ArrayDeque<T, ConstArrayLength<N>>;
66
67/// A fixed-capacity, stack-allocated double-ended queue (deque) backed by [`GenericArray`].
68///
69/// `ArrayDeque` provides a ring buffer implementation with O(1) insertion and removal
70/// at both ends. Unlike [`std::collections::VecDeque`], it has a compile-time fixed capacity
71/// and is entirely stack-allocated, making it suitable for `no_std` environments and
72/// performance-critical code where heap allocation should be avoided.
73///
74/// # Capacity
75///
76/// The capacity is fixed at compile time and cannot be changed. Attempting to push elements
77/// beyond the capacity will return the element back without inserting it.
78///
79/// ## Examples
80///
81/// Basic usage:
82///
83/// ```rust
84/// use generic_arraydeque::{ArrayDeque, typenum::U8};
85///
86/// // Create a deque with capacity 8
87/// let mut deque = ArrayDeque::<i32, U8>::new();
88///
89/// // Add elements to the back
90/// assert!(deque.push_back(1).is_none());
91/// assert!(deque.push_back(2).is_none());
92///
93/// // Add elements to the front
94/// assert!(deque.push_front(0).is_none());
95///
96/// assert_eq!(deque.len(), 3);
97/// assert_eq!(deque[0], 0);
98/// assert_eq!(deque[1], 1);
99/// assert_eq!(deque[2], 2);
100///
101/// // Remove elements
102/// assert_eq!(deque.pop_front(), Some(0));
103/// assert_eq!(deque.pop_back(), Some(2));
104/// assert_eq!(deque.len(), 1);
105/// ```
106///
107/// Using as a ring buffer:
108///
109/// ```rust
110/// use generic_arraydeque::{ArrayDeque, typenum::U4};
111///
112/// let mut buffer = ArrayDeque::<_, U4>::new();
113///
114/// // Fill the buffer
115/// for i in 0..4 {
116///     assert!(buffer.push_back(i).is_none());
117/// }
118///
119/// assert_eq!(buffer.len(), 4);
120/// assert!(buffer.is_full());
121///
122/// // Attempting to push when full returns the element
123/// assert_eq!(buffer.push_back(100), Some(100));
124///
125/// // Remove and add to maintain size
126/// buffer.pop_front();
127/// buffer.push_back(4);
128/// ```
129///
130/// Iterating over elements:
131///
132/// ```rust
133/// use generic_arraydeque::{ArrayDeque, typenum::U8};
134///
135/// let mut deque = ArrayDeque::<_, U8>::new();
136/// deque.push_back(1);
137/// deque.push_back(2);
138/// deque.push_back(3);
139///
140/// let sum: i32 = deque.iter().sum();
141/// assert_eq!(sum, 6);
142///
143/// // Mutable iteration
144/// for item in deque.iter_mut() {
145///     *item *= 2;
146/// }
147/// assert_eq!(deque.iter().sum::<i32>(), 12);
148/// ```
149///
150/// [`std::collections::VecDeque`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html
151/// [`GenericArray`]: https://docs.rs/generic-array/latest/generic_array/struct.GenericArray.html
152pub struct ArrayDeque<T, N>
153where
154  N: ArrayLength,
155{
156  array: GenericArray<MaybeUninit<T>, N>,
157  head: usize,
158  len: usize,
159}
160
161impl<T, N> Clone for ArrayDeque<T, N>
162where
163  T: Clone,
164  N: ArrayLength,
165{
166  fn clone(&self) -> Self {
167    let mut deq = Self::new();
168    // Clone each initialized element into a fresh, contiguous deque.
169    // With `head == 0`, logical index == physical index, so writing at
170    // `deq.len` is correct. Incrementing `len` only after a successful
171    // `write` keeps `deq` in a valid, drop-safe state if a user `Clone`
172    // impl panics mid-way.
173    for item in self.iter() {
174      let cloned = item.clone();
175      // SAFETY: self.len <= N::USIZE, deq.len < self.len here, so the
176      // slot is within the array.
177      unsafe {
178        deq.ptr_mut().add(deq.len).write(MaybeUninit::new(cloned));
179      }
180      deq.len += 1;
181    }
182    deq
183  }
184
185  fn clone_from(&mut self, source: &Self) {
186    // Drop whatever we currently hold, then clone source element-by-element.
187    // This matches the semantics of `*self = source.clone()` but avoids
188    // allocating an intermediate deque.
189    self.clear();
190    for item in source.iter() {
191      let cloned = item.clone();
192      // SAFETY: self.len < source.len <= N::USIZE, so the slot is in bounds.
193      unsafe {
194        self.ptr_mut().add(self.len).write(MaybeUninit::new(cloned));
195      }
196      self.len += 1;
197    }
198  }
199}
200
201impl<T, N> Default for ArrayDeque<T, N>
202where
203  N: ArrayLength,
204{
205  #[inline(always)]
206  fn default() -> Self {
207    Self::new()
208  }
209}
210
211impl<T: fmt::Debug, N: ArrayLength> fmt::Debug for ArrayDeque<T, N> {
212  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213    f.debug_list().entries(self.iter()).finish()
214  }
215}
216
217impl<T: PartialEq, N1: ArrayLength, N2: ArrayLength> PartialEq<ArrayDeque<T, N2>>
218  for ArrayDeque<T, N1>
219{
220  fn eq(&self, other: &ArrayDeque<T, N2>) -> bool {
221    if self.len != other.len() {
222      return false;
223    }
224    let (sa, sb) = self.as_slices();
225    let (oa, ob) = other.as_slices();
226    if sa.len() == oa.len() {
227      sa == oa && sb == ob
228    } else if sa.len() < oa.len() {
229      // Always divisible in three sections, for example:
230      // self:  [a b c|d e f]
231      // other: [0 1 2 3|4 5]
232      // front = 3, mid = 1,
233      // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
234      let front = sa.len();
235      let mid = oa.len() - front;
236
237      let (oa_front, oa_mid) = oa.split_at(front);
238      let (sb_mid, sb_back) = sb.split_at(mid);
239      debug_assert_eq!(sa.len(), oa_front.len());
240      debug_assert_eq!(sb_mid.len(), oa_mid.len());
241      debug_assert_eq!(sb_back.len(), ob.len());
242      sa == oa_front && sb_mid == oa_mid && sb_back == ob
243    } else {
244      let front = oa.len();
245      let mid = sa.len() - front;
246
247      let (sa_front, sa_mid) = sa.split_at(front);
248      let (ob_mid, ob_back) = ob.split_at(mid);
249      debug_assert_eq!(sa_front.len(), oa.len());
250      debug_assert_eq!(sa_mid.len(), ob_mid.len());
251      debug_assert_eq!(sb.len(), ob_back.len());
252      sa_front == oa && sa_mid == ob_mid && sb == ob_back
253    }
254  }
255}
256
257impl<T: Eq, N: ArrayLength> Eq for ArrayDeque<T, N> {}
258
259macro_rules! __impl_slice_eq1 {
260    ([$($vars:tt)*] $lhs:ty, $rhs:ty, $($constraints:tt)*) => {
261        impl<T, U, L: ArrayLength, $($vars)*> PartialEq<$rhs> for $lhs
262        where
263            T: PartialEq<U>,
264            $($constraints)*
265        {
266            fn eq(&self, other: &$rhs) -> bool {
267                if self.len() != other.len() {
268                    return false;
269                }
270                let (sa, sb) = self.as_slices();
271                let (oa, ob) = other[..].split_at(sa.len());
272                sa == oa && sb == ob
273            }
274        }
275    }
276}
277#[cfg(any(feature = "std", feature = "alloc"))]
278__impl_slice_eq1! { [] ArrayDeque<T, L>, std::vec::Vec<U>, }
279__impl_slice_eq1! { [] ArrayDeque<T, L>, &[U], }
280__impl_slice_eq1! { [] ArrayDeque<T, L>, &mut [U], }
281__impl_slice_eq1! { [const N: usize] ArrayDeque<T, L>, [U; N], }
282__impl_slice_eq1! { [const N: usize] ArrayDeque<T, L>, &[U; N], }
283__impl_slice_eq1! { [const N: usize] ArrayDeque<T, L>, &mut [U; N], }
284
285impl<T: PartialOrd, N: ArrayLength> PartialOrd for ArrayDeque<T, N> {
286  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
287    self.iter().partial_cmp(other.iter())
288  }
289}
290
291impl<T: Ord, N: ArrayLength> Ord for ArrayDeque<T, N> {
292  #[inline]
293  fn cmp(&self, other: &Self) -> Ordering {
294    self.iter().cmp(other.iter())
295  }
296}
297
298impl<T: Hash, N: ArrayLength> Hash for ArrayDeque<T, N> {
299  fn hash<H: Hasher>(&self, state: &mut H) {
300    state.write_usize(self.len);
301    // It's not possible to use Hash::hash_slice on slices
302    // returned by as_slices method as their length can vary
303    // in otherwise identical deques.
304    //
305    // Hasher only guarantees equivalence for the exact same
306    // set of calls to its methods.
307    self.iter().for_each(|elem| elem.hash(state));
308  }
309}
310
311impl<T, N: ArrayLength> Index<usize> for ArrayDeque<T, N> {
312  type Output = T;
313
314  #[inline]
315  fn index(&self, index: usize) -> &T {
316    self.get(index).expect("Out of bounds access")
317  }
318}
319
320impl<T, N: ArrayLength> IndexMut<usize> for ArrayDeque<T, N> {
321  #[inline]
322  fn index_mut(&mut self, index: usize) -> &mut T {
323    self.get_mut(index).expect("Out of bounds access")
324  }
325}
326
327impl<T, N: ArrayLength> IntoIterator for ArrayDeque<T, N> {
328  type Item = T;
329  type IntoIter = IntoIter<T, N>;
330
331  /// Consumes the deque into a front-to-back iterator yielding elements by
332  /// value.
333  fn into_iter(self) -> IntoIter<T, N> {
334    IntoIter::new(self)
335  }
336}
337
338impl<'a, T, N: ArrayLength> IntoIterator for &'a ArrayDeque<T, N> {
339  type Item = &'a T;
340  type IntoIter = Iter<'a, T>;
341
342  fn into_iter(self) -> Iter<'a, T> {
343    self.iter()
344  }
345}
346
347impl<'a, T, N: ArrayLength> IntoIterator for &'a mut ArrayDeque<T, N> {
348  type Item = &'a mut T;
349  type IntoIter = IterMut<'a, T>;
350
351  fn into_iter(self) -> IterMut<'a, T> {
352    self.iter_mut()
353  }
354}
355
356impl<T, N: ArrayLength, const SIZE: usize> TryFrom<[T; SIZE]> for ArrayDeque<T, N> {
357  type Error = [T; SIZE];
358
359  #[inline(always)]
360  fn try_from(arr: [T; SIZE]) -> Result<Self, Self::Error> {
361    Self::try_from_array(arr)
362  }
363}
364
365impl<T, N: ArrayLength> From<GenericArray<T, N>> for ArrayDeque<T, N> {
366  fn from(arr: GenericArray<T, N>) -> Self {
367    let mut deq = Self::new();
368    let arr = ManuallyDrop::new(arr);
369    if mem::size_of::<T>() != 0 {
370      // SAFETY: ensures that there is enough capacity.
371      unsafe {
372        ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr_mut() as _, N::USIZE);
373      }
374    }
375    deq.head = 0;
376    deq.len = N::USIZE;
377    deq
378  }
379}
380
381#[cfg(any(feature = "std", feature = "alloc"))]
382#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
383const _: () = {
384  #[allow(unused_imports)]
385  use std::{collections::VecDeque, vec::Vec};
386
387  impl<T, N: ArrayLength> ArrayDeque<T, N> {
388    /// Tries to create a deque from a vector.
389    ///
390    /// If the vector contains more elements than the capacity of the deque,
391    /// the vector will be returned as an `Err` value.
392    ///
393    /// ## Examples
394    ///
395    /// ```
396    /// use generic_arraydeque::{ArrayDeque, typenum::{U2, U4}};
397    ///
398    /// # use std::string::String;
399    ///
400    /// let deque = ArrayDeque::<u32, U4>::try_from_vec(vec![1, 2]).unwrap();
401    /// assert_eq!(deque.len(), 2);
402    ///
403    /// let result = ArrayDeque::<u32, U2>::try_from_vec(vec![1, 2, 3]);
404    /// assert!(result.is_err());
405    ///
406    /// let deque = ArrayDeque::<String, U4>::try_from_vec(vec![String::from("1"), String::from("2"), String::from("3")]).unwrap();
407    /// assert_eq!(deque.len(), 3);
408    ///
409    /// assert_eq!(deque[0].as_str(), "1");
410    /// assert_eq!(deque[1].as_str(), "2");
411    /// assert_eq!(deque[2].as_str(), "3");
412    /// ```
413    pub fn try_from_vec(vec: Vec<T>) -> Result<Self, Vec<T>> {
414      if vec.len() > N::USIZE {
415        return Err(vec);
416      }
417
418      let mut vec = ManuallyDrop::new(vec);
419      let ptr = vec.as_mut_ptr();
420      let len = vec.len();
421      let cap = vec.capacity();
422
423      let mut deq = GenericArray::uninit();
424      // SAFETY: capacity check above guarantees `len <= N::USIZE`, so the
425      // destination buffer is large enough. Elements are copied into
426      // `MaybeUninit<T>` storage and considered initialized immediately after.
427      unsafe {
428        ptr::copy_nonoverlapping(ptr, deq.as_mut_slice().as_mut_ptr() as *mut T, len);
429        // Reclaim the original allocation without dropping the moved elements.
430        drop(Vec::from_raw_parts(ptr, 0, cap));
431      }
432
433      Ok(Self {
434        array: deq,
435        head: 0,
436        len,
437      })
438    }
439  }
440
441  impl<T, N: ArrayLength> TryFrom<Vec<T>> for ArrayDeque<T, N> {
442    type Error = Vec<T>;
443
444    /// ```
445    /// use generic_arraydeque::{ArrayDeque, typenum::{U4, U2}};
446    ///
447    /// use std::vec::Vec;
448    ///
449    /// let deque = ArrayDeque::<i32, U4>::try_from(vec![1, 2, 3]).unwrap();
450    /// assert_eq!(deque.len(), 3);
451    ///
452    /// let result = ArrayDeque::<i32, U2>::try_from(vec![1, 2, 3]);
453    /// assert!(result.is_err());
454    /// ```
455    #[inline(always)]
456    fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
457      Self::try_from_vec(vec)
458    }
459  }
460
461  impl<T, N: ArrayLength> TryFrom<VecDeque<T>> for ArrayDeque<T, N> {
462    type Error = VecDeque<T>;
463
464    /// ```
465    /// use generic_arraydeque::{ArrayDeque, typenum::{U4, U2}};
466    ///
467    /// use std::collections::VecDeque;
468    ///
469    /// let deque = ArrayDeque::<i32, U4>::try_from(VecDeque::from(vec![1, 2, 3])).unwrap();
470    /// assert_eq!(deque.len(), 3);
471    ///
472    /// let result = ArrayDeque::<i32, U2>::try_from(VecDeque::from(vec![1, 2, 3]));
473    /// assert!(result.is_err());
474    /// ```
475    #[inline(always)]
476    fn try_from(vec_deq: VecDeque<T>) -> Result<Self, Self::Error> {
477      if vec_deq.len() > N::USIZE {
478        return Err(vec_deq);
479      }
480
481      let mut deq = GenericArray::uninit();
482      let len = vec_deq.len();
483
484      for (i, item) in vec_deq.into_iter().enumerate() {
485        deq[i].write(item);
486      }
487
488      Ok(Self {
489        array: deq,
490        head: 0,
491        len,
492      })
493    }
494  }
495
496  impl<T, N: ArrayLength> From<ArrayDeque<T, N>> for Vec<T> {
497    /// ```
498    /// use generic_arraydeque::{ArrayDeque, typenum::U4};
499    ///
500    /// let mut deque = ArrayDeque::<i32, U4>::new();
501    /// deque.push_back(10);
502    /// deque.push_back(20);
503    /// deque.push_back(30);
504    ///
505    /// let vec: Vec<i32> = Vec::from(deque);
506    /// assert_eq!(vec, vec![10, 20, 30]);
507    /// ```
508    #[inline(always)]
509    fn from(deq: ArrayDeque<T, N>) -> Self {
510      let mut vec = Vec::with_capacity(deq.len());
511      for item in deq.into_iter() {
512        vec.push(item);
513      }
514      vec
515    }
516  }
517
518  impl<T, N: ArrayLength> From<ArrayDeque<T, N>> for VecDeque<T> {
519    /// ```
520    /// use generic_arraydeque::{ArrayDeque, typenum::U4};
521    /// use std::collections::VecDeque;
522    ///
523    /// let mut deque = ArrayDeque::<i32, U4>::new();
524    /// deque.push_back(10);
525    /// deque.push_back(20);
526    /// deque.push_back(30);
527    ///
528    /// let vec_deque: VecDeque<i32> = VecDeque::from(deque);
529    /// assert_eq!(vec_deque, VecDeque::from(vec![10, 20, 30]));
530    /// ```
531    #[inline(always)]
532    fn from(deq: ArrayDeque<T, N>) -> Self {
533      let mut vec = VecDeque::with_capacity(deq.len());
534      for item in deq.into_iter() {
535        vec.push_back(item);
536      }
537      vec
538    }
539  }
540};
541
542impl<T, N> ArrayDeque<T, N>
543where
544  N: ArrayLength,
545{
546  /// Creates an empty deque.
547  ///
548  /// ## Examples
549  ///
550  /// ```
551  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
552  ///
553  /// let deque: ArrayDeque<u32, U8> = ArrayDeque::new();
554  /// ```
555  #[inline(always)]
556  pub const fn new() -> Self {
557    Self {
558      array: GenericArray::uninit(),
559      head: 0,
560      len: 0,
561    }
562  }
563
564  /// Convert a native array into `ArrayDeque` of the same length and type.
565  ///
566  /// This is equivalent to using the standard [`From`]/[`Into`] trait methods, but avoids
567  /// constructing an intermediate `ArrayDeque`.
568  ///
569  /// ## Examples
570  ///
571  /// ```
572  /// # #[cfg(feature = "std")] {
573  ///
574  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
575  /// use std::string::String;
576  ///
577  /// let deque = ArrayDeque::<String, U4>::from_array(["10".to_string(), "20".to_string(), "30".to_string(), "40".to_string()]);
578  /// assert_eq!(deque.len(), 4);
579  /// assert_eq!(deque[0].as_str(), "10");
580  /// assert_eq!(deque[1].as_str(), "20");
581  /// assert_eq!(deque[2].as_str(), "30");
582  /// assert_eq!(deque[3].as_str(), "40");
583  /// # }
584  /// ```
585  #[inline(always)]
586  pub const fn from_array<const U: usize>(array: [T; U]) -> Self
587  where
588    typenum::Const<U>: IntoArrayLength<ArrayLength = N>,
589  {
590    let ptr = array.as_slice().as_ptr();
591    mem::forget(array);
592
593    Self {
594      array: GenericArray::from_array(unsafe { ptr.cast::<[MaybeUninit<T>; U]>().read() }),
595      head: 0,
596      len: U,
597    }
598  }
599
600  /// Tries to create a deque from an array.
601  ///
602  /// If the array contains more elements than the capacity of the deque,
603  /// the array will be returned as an `Err` value.
604  ///
605  /// ## Examples
606  ///
607  /// ```
608  /// use generic_arraydeque::{ArrayDeque, typenum::{U4, U2}};
609  ///
610  /// let deque = ArrayDeque::<u32, U4>::try_from_array([1, 2, 3, 4]).unwrap();
611  /// assert_eq!(deque.len(), 4);
612  ///
613  /// let err = ArrayDeque::<u32, U2>::try_from_array([1, 2, 3]);
614  /// assert!(err.is_err());
615  ///
616  /// # #[cfg(feature = "std")] {
617  /// # use std::string::String;
618  /// let deque = ArrayDeque::<String, U4>::try_from_array([
619  ///    "one".to_string(),
620  ///    "two".to_string(),
621  /// ]).unwrap();
622  ///
623  /// assert_eq!(deque.len(), 2);
624  /// assert_eq!(deque[0].as_str(), "one");
625  /// assert_eq!(deque[1].as_str(), "two");
626  /// # }
627  /// ```
628  #[inline(always)]
629  pub const fn try_from_array<const SIZE: usize>(arr: [T; SIZE]) -> Result<Self, [T; SIZE]> {
630    if SIZE > N::USIZE {
631      return Err(arr);
632    }
633
634    let ptr = arr.as_ptr();
635    mem::forget(arr);
636
637    // SAFETY: We have already checked that the length of the array is less than or equal to the capacity of the deque.
638    unsafe {
639      let mut array = GenericArray::uninit();
640      ptr::copy_nonoverlapping(ptr, array.as_mut_slice().as_mut_ptr() as _, SIZE);
641      Ok(Self {
642        array,
643        head: 0,
644        len: SIZE,
645      })
646    }
647  }
648
649  /// Tries to create a deque from an iterator.
650  ///
651  /// If the iterator yields more elements than the capacity of the deque,
652  /// the remaining elements will be returned as an `Err` value.
653  ///
654  /// See also [`try_from_exact_iter`] which requires the iterator to yield exactly
655  /// the same number of elements as the capacity of the deque.
656  ///
657  /// ## Examples
658  ///
659  /// ```
660  /// use generic_arraydeque::{ArrayDeque, typenum::{U2, U4}};
661  ///
662  /// let deque = ArrayDeque::<u32, U4>::try_from_iter([10, 20, 30]).unwrap();
663  /// assert_eq!(deque.len(), 3);
664  ///
665  /// let result = ArrayDeque::<u32, U2>::try_from_iter(0..5);
666  /// assert!(result.is_err());
667  /// ```
668  #[allow(clippy::type_complexity)]
669  pub fn try_from_iter<I: IntoIterator<Item = T>>(
670    iter: I,
671  ) -> Result<Self, (Self, Chain<Once<T>, I::IntoIter>)> {
672    let mut deq = Self::new();
673    let mut iterator = iter.into_iter();
674    for idx in 0..N::USIZE {
675      match iterator.next() {
676        Some(value) => {
677          deq.array[idx].write(value);
678          deq.len += 1;
679        }
680        None => return Ok(deq),
681      }
682    }
683
684    match iterator.next() {
685      None => Ok(deq),
686      Some(value) => Err((deq, once(value).chain(iterator))),
687    }
688  }
689
690  /// Tries to extend the deque from an iterator.
691  ///
692  /// ## Examples
693  ///
694  /// ```
695  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
696  ///
697  /// let mut deque = ArrayDeque::<u32, U4>::new();
698  /// assert!(deque.try_extend_from_iter(0..2).is_none());
699  /// assert_eq!(deque.into_iter().collect::<Vec<_>>(), vec![0, 1]);
700  ///
701  /// let mut deque = ArrayDeque::<u32, U4>::new();
702  /// if let Some(leftovers) = deque.try_extend_from_iter(0..5) {
703  ///     assert_eq!(deque.len(), 4);
704  ///     assert_eq!(leftovers.collect::<Vec<_>>(), vec![4]);
705  /// }
706  /// ```
707  pub fn try_extend_from_iter<I: IntoIterator<Item = T>>(
708    &mut self,
709    iter: I,
710  ) -> Option<Chain<Once<T>, I::IntoIter>> {
711    let mut iterator = iter.into_iter();
712
713    for idx in self.len..N::USIZE {
714      let value = iterator.next()?;
715      let idx = self.to_physical_idx(idx);
716      self.array[idx].write(value);
717      self.len += 1;
718    }
719
720    iterator.next().map(|value| once(value).chain(iterator))
721  }
722
723  /// Tries to create a deque from an iterator that knows its exact length.
724  ///
725  /// If the iterator reports a length greater than the deque's capacity,
726  /// the iterator will be returned as an `Err` value.
727  ///
728  /// ## Examples
729  ///
730  /// ```
731  /// use generic_arraydeque::{ArrayDeque, typenum::{U2, U4}};
732  ///
733  /// let deque = ArrayDeque::<u32, U4>::try_from_exact_iter(0..4).unwrap();
734  /// assert_eq!(deque.len(), 4);
735  ///
736  /// let result = ArrayDeque::<u32, U4>::try_from_exact_iter(0..5);
737  /// assert!(result.is_err());
738  /// ```
739  pub fn try_from_exact_iter<I>(iter: I) -> Result<Self, I::IntoIter>
740  where
741    I: IntoIterator<Item = T>,
742    I::IntoIter: ExactSizeIterator,
743  {
744    let iter = iter.into_iter();
745    if iter.len() > N::USIZE {
746      return Err(iter);
747    }
748
749    let mut deq = Self::new();
750    // `ExactSizeIterator::len()` is a safe trait method, so a misbehaving
751    // impl may still yield more items than advertised. Stop once the
752    // buffer is full to preserve the capacity invariant and drop the
753    // remaining items as the iterator falls out of scope.
754    for value in iter {
755      if deq.len == N::USIZE {
756        break;
757      }
758      deq.array[deq.len].write(value);
759      deq.len += 1;
760    }
761    Ok(deq)
762  }
763
764  /// Tries to extend the deque from an iterator that knows its exact length.
765  ///
766  /// ## Examples
767  ///
768  /// ```
769  /// # #[cfg(feature = "std")]
770  /// # use std::vec::Vec;
771  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
772  ///
773  /// let mut deque = ArrayDeque::<u32, U4>::new();
774  /// assert!(deque.try_extend_from_exact_iter([0, 1, 2, 3]).is_none());
775  /// assert_eq!(deque.len(), 4);
776  ///
777  /// let mut deque = ArrayDeque::<u32, U4>::new();
778  /// let leftovers = deque.try_extend_from_exact_iter([0, 1, 2, 3, 4]).unwrap();
779  ///
780  /// # #[cfg(feature = "std")]
781  /// assert_eq!(leftovers.collect::<Vec<_>>(), vec![0, 1, 2, 3, 4]);
782  /// ```
783  pub fn try_extend_from_exact_iter<I>(&mut self, iter: I) -> Option<I::IntoIter>
784  where
785    I: IntoIterator<Item = T>,
786    I::IntoIter: ExactSizeIterator,
787  {
788    let iter = iter.into_iter();
789    if iter.len() > self.remaining_capacity() {
790      return Some(iter);
791    }
792
793    // `to_physical_idx` wraps modulo capacity, so it never panics even when
794    // a lying `ExactSizeIterator` yields more items than advertised.
795    // Without a bound, those extra writes would overwrite live slots and
796    // push `self.len` past capacity, which later turns into UB when
797    // `as_slices` / drop try to read past the buffer. Stop at capacity.
798    for value in iter {
799      if self.len == N::USIZE {
800        break;
801      }
802      let idx = self.to_physical_idx(self.len);
803      self.array[idx].write(value);
804      self.len += 1;
805    }
806    None
807  }
808
809  /// Creates a deque from an iterator without checking the number of elements and capacity of the deque.
810  ///
811  /// ## Safety
812  /// - The iterator must yield at most `N::USIZE` elements.
813  ///
814  /// ## Examples
815  ///
816  /// ```
817  /// use generic_arraydeque::{ArrayDeque, typenum::{U2, U4}};
818  ///
819  /// let deque = unsafe { ArrayDeque::<u32, U4>::from_iter_unchecked(7..10) };
820  /// assert_eq!(deque.len(), 3);
821  /// ```
822  pub unsafe fn from_iter_unchecked<I: IntoIterator<Item = T>>(iter: I) -> Self {
823    let mut deq = Self::new();
824    let mut iterator = iter.into_iter();
825    for idx in 0..N::USIZE {
826      match iterator.next() {
827        Some(value) => {
828          deq.array[idx].write(value);
829          deq.len += 1;
830        }
831        None => break,
832      }
833    }
834    deq
835  }
836
837  /// Returns the capacity of the deque.
838  ///
839  /// ## Examples
840  ///
841  /// ```
842  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
843  ///
844  /// let deque: ArrayDeque<u32, U8> = ArrayDeque::new();
845  /// assert_eq!(deque.capacity(), 8);
846  /// ```
847  #[inline(always)]
848  pub const fn capacity(&self) -> usize {
849    N::USIZE
850  }
851
852  /// Returns the number of elements in the deque.
853  ///
854  /// ## Examples
855  ///
856  /// ```
857  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
858  ///
859  /// let mut deque = ArrayDeque::<u32, U8>::new();
860  /// assert_eq!(deque.len(), 0);
861  /// deque.push_back(1);
862  /// assert_eq!(deque.len(), 1);
863  /// ```
864  #[inline(always)]
865  pub const fn len(&self) -> usize {
866    self.len
867  }
868
869  /// Returns how many more elements the deque can store without reallocating.
870  ///
871  /// ## Examples
872  ///
873  /// ```
874  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
875  ///
876  /// let mut deque = ArrayDeque::<u32, U4>::new();
877  /// assert_eq!(deque.remaining_capacity(), 4);
878  /// assert!(deque.push_back(10).is_none());
879  /// assert_eq!(deque.remaining_capacity(), 3);
880  /// ```
881  #[inline(always)]
882  pub const fn remaining_capacity(&self) -> usize {
883    debug_assert!(self.len <= self.capacity());
884    self.capacity() - self.len
885  }
886
887  /// Returns `true` if the deque is empty.
888  ///
889  /// ## Examples
890  ///
891  /// ```
892  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
893  ///
894  /// let mut deque = ArrayDeque::<u32, U8>::new();
895  /// assert!(deque.is_empty());
896  /// deque.push_front(1);
897  /// assert!(!deque.is_empty());
898  /// ```
899  #[inline(always)]
900  pub const fn is_empty(&self) -> bool {
901    self.len == 0
902  }
903
904  /// Returns `true` if the deque is at full capacity.
905  ///
906  /// ## Examples
907  ///
908  /// ```
909  /// use generic_arraydeque::{ArrayDeque, typenum::U2};
910  ///
911  /// let mut deque: ArrayDeque<u32, U2> = ArrayDeque::new();
912  /// assert!(!deque.is_full());
913  /// assert!(deque.push_back(10).is_none());
914  /// assert!(!deque.is_full());
915  /// assert!(deque.push_back(20).is_none());
916  /// assert!(deque.is_full());
917  /// ```
918  #[inline(always)]
919  pub const fn is_full(&self) -> bool {
920    self.len == self.capacity()
921  }
922
923  /// Creates an iterator that covers the specified range in the deque.
924  ///
925  /// ## Panics
926  ///
927  /// Panics if the range has `start_bound > end_bound`, or, if the range is
928  /// bounded on either end and past the length of the deque.
929  ///
930  /// ## Examples
931  ///
932  /// ```
933  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
934  ///
935  /// let deque: ArrayDeque<_, U4> = [1, 2, 3].try_into().unwrap();
936  /// let range: ArrayDeque<_, U4> = ArrayDeque::try_from_iter(deque.range(2..).copied()).unwrap();
937  /// assert_eq!(range, [3]);
938  ///
939  /// // A full range covers all contents
940  /// let all = deque.range(..);
941  /// assert_eq!(all.len(), 3);
942  /// ```
943  #[inline]
944  pub fn range<R>(&self, range: R) -> Iter<'_, T>
945  where
946    R: RangeBounds<usize>,
947  {
948    let (a_range, b_range) = self.slice_ranges(range, self.len);
949    // SAFETY: The ranges returned by `slice_ranges`
950    // are valid ranges into the physical buffer, so
951    // it's ok to pass them to `buffer_range` and
952    // dereference the result.
953    let a = unsafe { &*self.buffer_range(a_range) };
954    let b = unsafe { &*self.buffer_range(b_range) };
955    Iter::new(a.iter(), b.iter())
956  }
957
958  /// Creates an iterator that covers the specified mutable range in the deque.
959  ///
960  /// ## Panics
961  ///
962  /// Panics if the range has `start_bound > end_bound`, or, if the range is
963  /// bounded on either end and past the length of the deque.
964  ///
965  /// ## Examples
966  ///
967  /// ```
968  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
969  ///
970  /// let mut deque: ArrayDeque<_, U4> = [1, 2, 3].try_into().unwrap();
971  /// for v in deque.range_mut(2..) {
972  ///   *v *= 2;
973  /// }
974  /// assert_eq!(deque, [1, 2, 6]);
975  ///
976  /// // A full range covers all contents
977  /// for v in deque.range_mut(..) {
978  ///   *v *= 2;
979  /// }
980  /// assert_eq!(deque, [2, 4, 12]);
981  /// ```
982  #[inline]
983  pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
984  where
985    R: RangeBounds<usize>,
986  {
987    let (a_range, b_range) = self.slice_ranges(range, self.len);
988    let base = self.ptr_mut();
989    let (a, b) = unsafe {
990      let a_ptr = ptr::slice_from_raw_parts_mut(
991        base.add(a_range.start) as *mut T,
992        a_range.end - a_range.start,
993      );
994      let b_ptr = ptr::slice_from_raw_parts_mut(
995        base.add(b_range.start) as *mut T,
996        b_range.end - b_range.start,
997      );
998      (&mut *a_ptr, &mut *b_ptr)
999    };
1000    IterMut::new(a.iter_mut(), b.iter_mut())
1001  }
1002
1003  /// Returns a front-to-back iterator.
1004  ///
1005  /// ## Examples
1006  ///
1007  /// ```
1008  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
1009  ///
1010  /// let mut buf = ArrayDeque::<i32, U4>::new();
1011  /// assert!(buf.push_back(5).is_none());
1012  /// assert!(buf.push_back(3).is_none());
1013  /// assert!(buf.push_back(4).is_none());
1014  /// let collected: Vec<&i32> = buf.iter().collect();
1015  /// assert_eq!(collected, vec![&5, &3, &4]);
1016  /// ```
1017  pub fn iter(&self) -> Iter<'_, T> {
1018    let (a, b) = self.as_slices();
1019    Iter::new(a.iter(), b.iter())
1020  }
1021
1022  /// Returns a front-to-back iterator that returns mutable references.
1023  ///
1024  /// ## Examples
1025  ///
1026  /// ```
1027  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
1028  ///
1029  /// let mut buf = ArrayDeque::<i32, U4>::new();
1030  /// assert!(buf.push_back(5).is_none());
1031  /// assert!(buf.push_back(3).is_none());
1032  /// assert!(buf.push_back(4).is_none());
1033  /// for value in buf.iter_mut() {
1034  ///     *value -= 2;
1035  /// }
1036  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![3, 1, 2]);
1037  /// ```
1038  pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1039    let (a, b) = self.as_mut_slices();
1040    IterMut::new(a.iter_mut(), b.iter_mut())
1041  }
1042
1043  /// Splits the deque into two at the given index.
1044  ///
1045  /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1046  /// and the returned deque contains elements `[at, len)`.
1047  ///
1048  /// Note that the capacity of `self` does not change.
1049  ///
1050  /// Element at index 0 is the front of the queue.
1051  ///
1052  /// ## Panics
1053  ///
1054  /// Panics if `at > len`.
1055  ///
1056  /// ## Examples
1057  ///
1058  /// ```
1059  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
1060  ///
1061  /// let mut buf: ArrayDeque<_, U4> = ['a', 'b', 'c'].try_into().unwrap();
1062  /// let buf2 = buf.split_off(1);
1063  /// assert_eq!(buf, ['a']);
1064  /// assert_eq!(buf2, ['b', 'c']);
1065  /// ```
1066  #[inline]
1067  #[must_use = "use `.truncate()` if you don't need the other half"]
1068  pub const fn split_off(&mut self, at: usize) -> Self {
1069    let len = self.len;
1070    assert!(at <= len, "`at` out of bounds");
1071
1072    let other_len = len - at;
1073    let mut other = Self::new();
1074
1075    unsafe {
1076      let (first_half, second_half) = self.as_slices();
1077
1078      let first_len = first_half.len();
1079      let second_len = second_half.len();
1080      if at < first_len {
1081        // `at` lies in the first half.
1082        let amount_in_first = first_len - at;
1083
1084        ptr::copy_nonoverlapping(
1085          first_half.as_ptr().add(at),
1086          other.ptr_mut() as _,
1087          amount_in_first,
1088        );
1089
1090        // just take all of the second half.
1091        ptr::copy_nonoverlapping(
1092          second_half.as_ptr(),
1093          other.ptr_mut().add(amount_in_first) as _,
1094          second_len,
1095        );
1096      } else {
1097        // `at` lies in the second half, need to factor in the elements we skipped
1098        // in the first half.
1099        let offset = at - first_len;
1100        let amount_in_second = second_len - offset;
1101        ptr::copy_nonoverlapping(
1102          second_half.as_ptr().add(offset),
1103          other.ptr_mut() as _,
1104          amount_in_second,
1105        );
1106      }
1107    }
1108
1109    // Cleanup where the ends of the buffers are
1110    self.len = at;
1111    other.len = other_len;
1112
1113    other
1114  }
1115
1116  /// Moves all the elements of `other` into `self`, leaving `other` empty.
1117  ///
1118  /// This operation is no-op if the combined length of both deques exceeds the capacity of `self`.
1119  ///
1120  /// ## Examples
1121  ///
1122  /// ```
1123  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
1124  ///
1125  /// let mut buf: ArrayDeque<_, U4> = [1, 2].try_into().unwrap();
1126  /// let mut buf2: ArrayDeque<_, U4> = [3, 4].try_into().unwrap();
1127  /// assert!(buf.append(&mut buf2));
1128  /// assert_eq!(buf, [1, 2, 3, 4]);
1129  /// assert_eq!(buf2, []);
1130  /// ```
1131  #[inline]
1132  pub const fn append(&mut self, other: &mut Self) -> bool {
1133    if self.len + other.len > self.capacity() {
1134      return false;
1135    }
1136
1137    if mem::size_of::<T>() == 0 {
1138      match self.len.checked_add(other.len) {
1139        Some(new_len) => self.len = new_len,
1140        None => panic!("capacity overflow"),
1141      }
1142
1143      other.len = 0;
1144      other.head = 0;
1145      return true;
1146    }
1147
1148    unsafe {
1149      let (left, right) = other.as_slices();
1150      self.copy_slice(self.to_physical_idx(self.len), left);
1151      // no overflow, because self.capacity() >= old_cap + left.len() >= self.len + left.len()
1152      self.copy_slice(self.to_physical_idx(self.len + left.len()), right);
1153    }
1154    // SAFETY: Update pointers after copying to avoid leaving doppelganger
1155    // in case of panics.
1156    self.len += other.len;
1157    // Now that we own its values, forget everything in `other`.
1158    other.len = 0;
1159    other.head = 0;
1160    true
1161  }
1162
1163  /// Returns a pair of slices which contain, in order, the contents of the
1164  /// deque.
1165  ///
1166  /// If [`make_contiguous`] was previously called, all elements of the
1167  /// deque will be in the first slice and the second slice will be empty.
1168  /// Otherwise, the exact split point depends on implementation details
1169  /// and is not guaranteed.
1170  ///
1171  /// [`make_contiguous`]: ArrayDeque::make_contiguous
1172  ///
1173  /// ## Examples
1174  ///
1175  /// ```
1176  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1177  ///
1178  /// let mut deque = ArrayDeque::<u32, U8>::new();
1179  ///
1180  /// deque.push_back(0);
1181  /// deque.push_back(1);
1182  /// deque.push_back(2);
1183  ///
1184  /// let expected = [0, 1, 2];
1185  /// let (front, back) = deque.as_slices();
1186  /// assert_eq!(&expected[..front.len()], front);
1187  /// assert_eq!(&expected[front.len()..], back);
1188  ///
1189  /// deque.push_front(10);
1190  /// deque.push_front(9);
1191  ///
1192  /// let expected = [9, 10, 0, 1, 2];
1193  /// let (front, back) = deque.as_slices();
1194  /// assert_eq!(&expected[..front.len()], front);
1195  /// assert_eq!(&expected[front.len()..], back);
1196  /// ```
1197  #[inline(always)]
1198  pub const fn as_slices(&self) -> (&[T], &[T]) {
1199    let (a_range, b_range) = self.slice_full_ranges();
1200    // SAFETY: `slice_full_ranges` always returns valid ranges into
1201    // the physical buffer.
1202    unsafe { (&*self.buffer_range(a_range), &*self.buffer_range(b_range)) }
1203  }
1204
1205  /// Returns a pair of slices which contain, in order, the contents of the
1206  /// deque.
1207  ///
1208  /// If [`make_contiguous`] was previously called, all elements of the
1209  /// deque will be in the first slice and the second slice will be empty.
1210  /// Otherwise, the exact split point depends on implementation details
1211  /// and is not guaranteed.
1212  ///
1213  /// [`make_contiguous`]: ArrayDeque::make_contiguous
1214  ///
1215  /// ## Examples
1216  ///
1217  /// ```
1218  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1219  ///
1220  /// let mut deque = ArrayDeque::<u32, U8>::new();
1221  ///
1222  /// deque.push_back(0);
1223  /// deque.push_back(1);
1224  ///
1225  /// deque.push_front(10);
1226  /// deque.push_front(9);
1227  ///
1228  /// // Since the split point is not guaranteed, we may need to update
1229  /// // either slice.
1230  /// let mut update_nth = |index: usize, val: u32| {
1231  ///     let (front, back) = deque.as_mut_slices();
1232  ///     if index > front.len() - 1 {
1233  ///         back[index - front.len()] = val;
1234  ///     } else {
1235  ///         front[index] = val;
1236  ///     }
1237  /// };
1238  ///
1239  /// update_nth(0, 42);
1240  /// update_nth(2, 24);
1241  ///
1242  /// let v: Vec<_> = deque.into_iter().collect();
1243  /// assert_eq!(v, [42, 10, 24, 1]);
1244  /// ```
1245  #[inline(always)]
1246  pub const fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1247    let (a_range, b_range) = self.slice_full_ranges();
1248    let base = self.ptr_mut();
1249    unsafe {
1250      let a_ptr = ptr::slice_from_raw_parts_mut(
1251        base.add(a_range.start) as *mut T,
1252        a_range.end - a_range.start,
1253      );
1254      let b_ptr = ptr::slice_from_raw_parts_mut(
1255        base.add(b_range.start) as *mut T,
1256        b_range.end - b_range.start,
1257      );
1258      (&mut *a_ptr, &mut *b_ptr)
1259    }
1260  }
1261
1262  /// Provides a reference to the front element, or `None` if the deque is
1263  /// empty.
1264  ///
1265  /// ## Examples
1266  ///
1267  /// ```
1268  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1269  ///
1270  /// let mut d = ArrayDeque::<u32, U8>::new();
1271  /// assert_eq!(d.front(), None);
1272  ///
1273  /// d.push_back(1);
1274  /// d.push_back(2);
1275  /// assert_eq!(d.front(), Some(&1));
1276  /// ```
1277  #[inline(always)]
1278  pub const fn front(&self) -> Option<&T> {
1279    self.get(0)
1280  }
1281
1282  /// Provides a mutable reference to the front element, or `None` if the
1283  /// deque is empty.
1284  ///
1285  /// ## Examples
1286  ///
1287  /// ```
1288  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1289  ///
1290  /// let mut d = ArrayDeque::<u32, U8>::new();
1291  /// assert_eq!(d.front_mut(), None);
1292  ///
1293  /// d.push_back(1);
1294  /// d.push_back(2);
1295  /// match d.front_mut() {
1296  ///     Some(x) => *x = 9,
1297  ///     None => (),
1298  /// }
1299  /// assert_eq!(d.front(), Some(&9));
1300  /// ```
1301  #[inline(always)]
1302  pub const fn front_mut(&mut self) -> Option<&mut T> {
1303    self.get_mut(0)
1304  }
1305
1306  /// Provides a reference to the back element, or `None` if the deque is
1307  /// empty.
1308  ///
1309  /// ## Examples
1310  ///
1311  /// ```
1312  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1313  ///
1314  /// let mut d = ArrayDeque::<u32, U8>::new();
1315  /// assert_eq!(d.back(), None);
1316  ///
1317  /// d.push_back(1);
1318  /// d.push_back(2);
1319  /// assert_eq!(d.back(), Some(&2));
1320  /// ```
1321  #[inline(always)]
1322  pub const fn back(&self) -> Option<&T> {
1323    self.get(self.len.wrapping_sub(1))
1324  }
1325
1326  /// Provides a mutable reference to the back element, or `None` if the
1327  /// deque is empty.
1328  ///
1329  /// ## Examples
1330  ///
1331  /// ```
1332  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1333  ///
1334  /// let mut d = ArrayDeque::<u32, U8>::new();
1335  /// assert_eq!(d.back(), None);
1336  ///
1337  /// d.push_back(1);
1338  /// d.push_back(2);
1339  /// match d.back_mut() {
1340  ///     Some(x) => *x = 9,
1341  ///     None => (),
1342  /// }
1343  /// assert_eq!(d.back(), Some(&9));
1344  /// ```
1345  #[inline(always)]
1346  pub const fn back_mut(&mut self) -> Option<&mut T> {
1347    self.get_mut(self.len.wrapping_sub(1))
1348  }
1349
1350  /// Provides a reference to the element at the given index.
1351  ///
1352  /// Elements at index 0 is the front of the deque.
1353  ///
1354  /// ## Examples
1355  ///
1356  /// ```
1357  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1358  ///
1359  /// let mut deque: ArrayDeque<u32, U8> = ArrayDeque::new();
1360  /// assert!(deque.push_back(10).is_none());
1361  /// assert!(deque.push_back(20).is_none());
1362  /// assert_eq!(*deque.get(0).unwrap(), 10);
1363  /// assert_eq!(*deque.get(1).unwrap(), 20);
1364  /// ```
1365  #[inline(always)]
1366  pub const fn get(&self, index: usize) -> Option<&T> {
1367    if index < self.len {
1368      let idx = self.to_physical_idx(index);
1369      // SAFETY: index is checked to be in-bounds
1370      unsafe { Some((&*self.ptr().add(idx)).assume_init_ref()) }
1371    } else {
1372      None
1373    }
1374  }
1375
1376  /// Provides a mutable reference to the element at the given index.
1377  ///
1378  /// Elements at index 0 is the front of the deque.
1379  ///
1380  /// ## Examples
1381  ///
1382  /// ```
1383  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1384  ///
1385  /// let mut deque: ArrayDeque<u32, U8> = ArrayDeque::new();
1386  /// assert!(deque.push_back(10).is_none());
1387  /// assert!(deque.push_back(20).is_none());
1388  /// *deque.get_mut(0).unwrap() += 5;
1389  /// assert_eq!(*deque.get(0).unwrap(), 15);
1390  /// ```
1391  #[inline(always)]
1392  pub const fn get_mut(&mut self, index: usize) -> Option<&mut T> {
1393    if index < self.len {
1394      let idx = self.to_physical_idx(index);
1395      // SAFETY: index is checked to be in-bounds
1396      unsafe { Some((&mut *self.ptr_mut().add(idx)).assume_init_mut()) }
1397    } else {
1398      None
1399    }
1400  }
1401
1402  /// Appends an element to the back of the deque, returning `None` if successful.
1403  ///
1404  /// If the deque is at full capacity, returns the element back without modifying the deque.
1405  ///
1406  /// ## Examples
1407  ///
1408  /// ```
1409  /// use generic_arraydeque::{ArrayDeque, typenum::U2};
1410  ///
1411  /// let mut deque: ArrayDeque<u32, U2> = ArrayDeque::new();
1412  /// assert!(deque.push_back(10).is_none());
1413  /// assert!(deque.push_back(20).is_none());
1414  /// assert!(deque.push_back(30).is_some());
1415  /// ```
1416  #[inline(always)]
1417  pub const fn push_back(&mut self, value: T) -> Option<T> {
1418    if self.is_full() {
1419      Some(value)
1420    } else {
1421      let _ = unsafe { push_back_unchecked!(self(value)) };
1422      None
1423    }
1424  }
1425
1426  /// Removes the first element and returns it, or `None` if the deque is
1427  /// empty.
1428  ///
1429  /// ## Examples
1430  ///
1431  /// ```
1432  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1433  ///
1434  /// let mut d = ArrayDeque::<u32, U8>::new();
1435  /// d.push_back(1);
1436  /// d.push_back(2);
1437  ///
1438  /// assert_eq!(d.pop_front(), Some(1));
1439  /// assert_eq!(d.pop_front(), Some(2));
1440  /// assert_eq!(d.pop_front(), None);
1441  /// ```
1442  #[inline(always)]
1443  pub const fn pop_front(&mut self) -> Option<T> {
1444    if self.is_empty() {
1445      None
1446    } else {
1447      let old_head = self.head;
1448      self.head = self.to_physical_idx(1);
1449      self.len -= 1;
1450      unsafe {
1451        assert_unchecked(self.len < self.capacity());
1452        Some(self.buffer_read(old_head))
1453      }
1454    }
1455  }
1456
1457  /// Removes the last element from the deque and returns it, or `None` if
1458  /// it is empty.
1459  ///
1460  /// ## Examples
1461  ///
1462  /// ```
1463  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1464  ///
1465  /// let mut buf = ArrayDeque::<u32, U8>::new();
1466  /// assert_eq!(buf.pop_back(), None);
1467  /// buf.push_back(1);
1468  /// buf.push_back(3);
1469  /// assert_eq!(buf.pop_back(), Some(3));
1470  /// ```
1471  #[inline(always)]
1472  pub const fn pop_back(&mut self) -> Option<T> {
1473    if self.is_empty() {
1474      None
1475    } else {
1476      self.len -= 1;
1477      unsafe {
1478        assert_unchecked(self.len < self.capacity());
1479        Some(self.buffer_read(self.to_physical_idx(self.len)))
1480      }
1481    }
1482  }
1483
1484  /// Prepends an element to the front of the deque, returning `None` if successful.
1485  ///
1486  /// If the deque is at full capacity, returns the element back without modifying the deque.
1487  ///
1488  /// ## Examples
1489  ///
1490  /// ```
1491  /// use generic_arraydeque::{ArrayDeque, typenum::U2};
1492  ///
1493  /// let mut deque: ArrayDeque<u32, U2> = ArrayDeque::new();
1494  ///
1495  /// assert!(deque.push_front(10).is_none());
1496  /// assert!(deque.push_front(20).is_none());
1497  /// assert!(deque.push_front(30).is_some());
1498  /// ```
1499  #[inline(always)]
1500  pub const fn push_front(&mut self, value: T) -> Option<T> {
1501    if self.is_full() {
1502      Some(value)
1503    } else {
1504      let _ = unsafe { push_front_unchecked!(self(value)) };
1505      None
1506    }
1507  }
1508
1509  /// Rotates the double-ended queue `n` places to the left.
1510  ///
1511  /// Equivalently,
1512  /// - Rotates item `n` into the first position.
1513  /// - Pops the first `n` items and pushes them to the end.
1514  /// - Rotates `len() - n` places to the right.
1515  ///
1516  /// ## Panics
1517  ///
1518  /// If `n` is greater than `len()`. Note that `n == len()`
1519  /// does _not_ panic and is a no-op rotation.
1520  ///
1521  /// # Complexity
1522  ///
1523  /// Takes `*O*(min(n, len() - n))` time and no extra space.
1524  ///
1525  /// ## Examples
1526  ///
1527  /// ```
1528  /// use generic_arraydeque::{ArrayDeque, typenum::U10};
1529  ///
1530  /// let mut buf: ArrayDeque<u32, U10> = ArrayDeque::new();
1531  /// for value in 0..10 {
1532  ///     assert!(buf.push_back(value).is_none());
1533  /// }
1534  ///
1535  /// buf.rotate_left(3);
1536  /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
1537  ///
1538  /// for i in 1..10 {
1539  ///     assert_eq!(i * 3 % 10, buf[0]);
1540  ///     buf.rotate_left(3);
1541  /// }
1542  /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1543  /// ```
1544  #[inline(always)]
1545  pub const fn rotate_left(&mut self, n: usize) {
1546    assert!(n <= self.len());
1547    let k = self.len - n;
1548    if n <= k {
1549      unsafe { self.rotate_left_inner(n) }
1550    } else {
1551      unsafe { self.rotate_right_inner(k) }
1552    }
1553  }
1554
1555  /// Rotates the double-ended queue `n` places to the right.
1556  ///
1557  /// Equivalently,
1558  /// - Rotates the first item into position `n`.
1559  /// - Pops the last `n` items and pushes them to the front.
1560  /// - Rotates `len() - n` places to the left.
1561  ///
1562  /// ## Panics
1563  ///
1564  /// If `n` is greater than `len()`. Note that `n == len()`
1565  /// does _not_ panic and is a no-op rotation.
1566  ///
1567  /// # Complexity
1568  ///
1569  /// Takes `*O*(min(n, len() - n))` time and no extra space.
1570  ///
1571  /// ## Examples
1572  ///
1573  /// ```
1574  /// use generic_arraydeque::{ArrayDeque, typenum::U10};
1575  ///
1576  /// let mut buf: ArrayDeque<u32, U10> = ArrayDeque::new();
1577  /// for value in 0..10 {
1578  ///     assert!(buf.push_back(value).is_none());
1579  /// }
1580  ///
1581  /// buf.rotate_right(3);
1582  /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
1583  ///
1584  /// for i in 1..10 {
1585  ///     assert_eq!(0, buf[i * 3 % 10]);
1586  ///     buf.rotate_right(3);
1587  /// }
1588  /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1589  /// ```
1590  #[inline(always)]
1591  pub const fn rotate_right(&mut self, n: usize) {
1592    assert!(n <= self.len());
1593    let k = self.len - n;
1594    if n <= k {
1595      unsafe { self.rotate_right_inner(n) }
1596    } else {
1597      unsafe { self.rotate_left_inner(k) }
1598    }
1599  }
1600
1601  /// Rearranges the internal storage of this deque so it is one contiguous
1602  /// slice, which is then returned.
1603  ///
1604  /// This method does not allocate and does not change the order of the
1605  /// inserted elements. As it returns a mutable slice, this can be used to
1606  /// sort a deque.
1607  ///
1608  /// Once the internal storage is contiguous, the [`as_slices`] and
1609  /// [`as_mut_slices`] methods will return the entire contents of the
1610  /// deque in a single slice.
1611  ///
1612  /// [`as_slices`]: ArrayDeque::as_slices
1613  /// [`as_mut_slices`]: ArrayDeque::as_mut_slices
1614  ///
1615  /// ## Examples
1616  ///
1617  /// Sorting the content of a deque.
1618  ///
1619  /// ```
1620  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1621  ///
1622  /// let mut buf = ArrayDeque::<i32, U8>::new();
1623  /// assert!(buf.push_back(2).is_none());
1624  /// assert!(buf.push_back(1).is_none());
1625  /// assert!(buf.push_front(3).is_none());
1626  ///
1627  /// buf.make_contiguous().sort();
1628  /// assert_eq!(buf.as_slices(), (&[1, 2, 3][..], &[][..]));
1629  ///
1630  /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
1631  /// assert_eq!(buf.as_slices(), (&[3, 2, 1][..], &[][..]));
1632  /// ```
1633  ///
1634  /// Getting immutable access to the contiguous slice.
1635  ///
1636  /// ```rust
1637  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1638  ///
1639  /// let mut buf = ArrayDeque::<i32, U8>::new();
1640  /// assert!(buf.push_back(2).is_none());
1641  /// assert!(buf.push_back(1).is_none());
1642  /// assert!(buf.push_front(3).is_none());
1643  ///
1644  /// buf.make_contiguous();
1645  /// if let (slice, &[]) = buf.as_slices() {
1646  ///     assert_eq!(buf.len(), slice.len());
1647  ///     assert_eq!(slice, &[3, 2, 1]);
1648  /// }
1649  /// ```
1650  #[rustversion::attr(since(1.92), const)]
1651  pub fn make_contiguous(&mut self) -> &mut [T] {
1652    if mem::size_of::<T>() == 0 {
1653      self.head = 0;
1654    }
1655
1656    if self.is_contiguous() {
1657      let base = self.ptr_mut();
1658      unsafe { return slice::from_raw_parts_mut(base.add(self.head) as *mut T, self.len) }
1659    }
1660
1661    let &mut Self { head, len, .. } = self;
1662    let cap = self.capacity();
1663
1664    let free = cap - len;
1665    let head_len = cap - head;
1666    let tail = len - head_len;
1667    let tail_len = tail;
1668
1669    if free >= head_len {
1670      // there is enough free space to copy the head in one go,
1671      // this means that we first shift the tail backwards, and then
1672      // copy the head to the correct position.
1673      //
1674      // from: DEFGH....ABC
1675      // to:   ABCDEFGH....
1676      unsafe {
1677        self.copy(0, head_len, tail_len);
1678        // ...DEFGH.ABC
1679        self.copy_nonoverlapping(head, 0, head_len);
1680        // ABCDEFGH....
1681      }
1682
1683      self.head = 0;
1684    } else if free >= tail_len {
1685      // there is enough free space to copy the tail in one go,
1686      // this means that we first shift the head forwards, and then
1687      // copy the tail to the correct position.
1688      //
1689      // from: FGH....ABCDE
1690      // to:   ...ABCDEFGH.
1691      unsafe {
1692        self.copy(head, tail, head_len);
1693        // FGHABCDE....
1694        self.copy_nonoverlapping(0, tail + head_len, tail_len);
1695        // ...ABCDEFGH.
1696      }
1697
1698      self.head = tail;
1699    } else {
1700      // `free` is smaller than both `head_len` and `tail_len`.
1701      // the general algorithm for this first moves the slices
1702      // right next to each other and then uses `slice::rotate`
1703      // to rotate them into place:
1704      //
1705      // initially:   HIJK..ABCDEFG
1706      // step 1:      ..HIJKABCDEFG
1707      // step 2:      ..ABCDEFGHIJK
1708      //
1709      // or:
1710      //
1711      // initially:   FGHIJK..ABCDE
1712      // step 1:      FGHIJKABCDE..
1713      // step 2:      ABCDEFGHIJK..
1714
1715      // pick the shorter of the 2 slices to reduce the amount
1716      // of memory that needs to be moved around.
1717      if head_len > tail_len {
1718        // tail is shorter, so:
1719        //  1. copy tail forwards
1720        //  2. rotate used part of the buffer
1721        //  3. update head to point to the new beginning (which is just `free`)
1722
1723        unsafe {
1724          // if there is no free space in the buffer, then the slices are already
1725          // right next to each other and we don't need to move any memory.
1726          if free != 0 {
1727            // because we only move the tail forward as much as there's free space
1728            // behind it, we don't overwrite any elements of the head slice, and
1729            // the slices end up right next to each other.
1730            self.copy(0, free, tail_len);
1731          }
1732
1733          // We just copied the tail right next to the head slice,
1734          // so all of the elements in the range are initialized
1735          let slice = &mut *self.buffer_range_mut(free..self.capacity());
1736
1737          // because the deque wasn't contiguous, we know that `tail_len < self.len == slice.len()`,
1738          // so this will never panic.
1739          slice.rotate_left(tail_len);
1740
1741          // the used part of the buffer now is `free..self.capacity()`, so set
1742          // `head` to the beginning of that range.
1743          self.head = free;
1744        }
1745      } else {
1746        // head is shorter so:
1747        //  1. copy head backwards
1748        //  2. rotate used part of the buffer
1749        //  3. update head to point to the new beginning (which is the beginning of the buffer)
1750
1751        unsafe {
1752          // if there is no free space in the buffer, then the slices are already
1753          // right next to each other and we don't need to move any memory.
1754          if free != 0 {
1755            // copy the head slice to lie right behind the tail slice.
1756            self.copy(self.head, tail_len, head_len);
1757          }
1758
1759          // because we copied the head slice so that both slices lie right
1760          // next to each other, all the elements in the range are initialized.
1761          let slice = &mut *self.buffer_range_mut(0..self.len);
1762
1763          // because the deque wasn't contiguous, we know that `head_len < self.len == slice.len()`
1764          // so this will never panic.
1765          slice.rotate_right(head_len);
1766
1767          // the used part of the buffer now is `0..self.len`, so set
1768          // `head` to the beginning of that range.
1769          self.head = 0;
1770        }
1771      }
1772    }
1773
1774    let base = self.ptr_mut();
1775    unsafe { slice::from_raw_parts_mut(base.add(self.head) as *mut T, self.len) }
1776  }
1777
1778  /// Shortens the deque, keeping the first `len` elements and dropping
1779  /// the rest.
1780  ///
1781  /// If `len` is greater or equal to the deque's current length, this has
1782  /// no effect.
1783  ///
1784  /// ## Examples
1785  ///
1786  /// ```
1787  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1788  ///
1789  /// let mut buf = ArrayDeque::<u32, U8>::new();
1790  /// buf.push_back(5);
1791  /// buf.push_back(10);
1792  /// buf.push_back(15);
1793  /// assert_eq!(buf, [5, 10, 15]);
1794  /// buf.truncate(1);
1795  /// assert_eq!(buf, [5]);
1796  /// ```
1797  pub fn truncate(&mut self, len: usize) {
1798    /// Runs the destructor for all items in the slice when it gets dropped (normally or
1799    /// during unwinding).
1800    struct Dropper<'a, T>(&'a mut [T]);
1801
1802    impl<T> Drop for Dropper<'_, T> {
1803      fn drop(&mut self) {
1804        unsafe {
1805          ptr::drop_in_place(self.0);
1806        }
1807      }
1808    }
1809
1810    // Safe because:
1811    //
1812    // * Any slice passed to `drop_in_place` is valid; the second case has
1813    //   `len <= front.len()` and returning on `len > self.len()` ensures
1814    //   `begin <= back.len()` in the first case
1815    // * The head of the deque is moved before calling `drop_in_place`,
1816    //   so no value is dropped twice if `drop_in_place` panics
1817    unsafe {
1818      if len >= self.len {
1819        return;
1820      }
1821
1822      let (front, back) = self.as_mut_slices();
1823      if len > front.len() {
1824        let begin = len - front.len();
1825        let drop_back = back.get_unchecked_mut(begin..) as *mut _;
1826        self.len = len;
1827        ptr::drop_in_place(drop_back);
1828      } else {
1829        let drop_back = back as *mut _;
1830        let drop_front = front.get_unchecked_mut(len..) as *mut _;
1831        self.len = len;
1832
1833        // Make sure the second half is dropped even when a destructor
1834        // in the first one panics.
1835        let _back_dropper = Dropper(&mut *drop_back);
1836        ptr::drop_in_place(drop_front);
1837      }
1838    }
1839  }
1840
1841  /// Clears the deque, removing all values.
1842  ///
1843  /// ## Examples
1844  ///
1845  /// ```
1846  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
1847  ///
1848  /// let mut deque = ArrayDeque::<u32, U8>::new();
1849  /// deque.push_back(1);
1850  /// deque.clear();
1851  /// assert!(deque.is_empty());
1852  /// ```
1853  #[inline(always)]
1854  pub fn clear(&mut self) {
1855    self.truncate(0);
1856    // Not strictly necessary, but leaves things in a more consistent/predictable state.
1857    self.head = 0;
1858  }
1859
1860  /// Returns `true` if the deque contains an element equal to the
1861  /// given value.
1862  ///
1863  /// This operation is *O*(*n*).
1864  ///
1865  /// Note that if you have a sorted deque, [`binary_search`] may be faster.
1866  ///
1867  /// [`binary_search`]: ArrayDeque::binary_search
1868  ///
1869  /// ## Examples
1870  ///
1871  /// ```
1872  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
1873  ///
1874  /// let mut deque = ArrayDeque::<u32, U4>::new();
1875  /// assert!(deque.push_back(0).is_none());
1876  /// assert!(deque.push_back(1).is_none());
1877  ///
1878  /// assert!(deque.contains(&1));
1879  /// assert!(!deque.contains(&10));
1880  /// ```
1881  #[inline]
1882  pub fn contains(&self, x: &T) -> bool
1883  where
1884    T: PartialEq<T>,
1885  {
1886    let (a, b) = self.as_slices();
1887    a.contains(x) || b.contains(x)
1888  }
1889
1890  /// Binary searches this deque for a given element.
1891  /// If the deque is not sorted, the returned result is unspecified and
1892  /// meaningless.
1893  ///
1894  /// If the value is found then [`Result::Ok`] is returned, containing the
1895  /// index of the matching element. If there are multiple matches, then any
1896  /// one of the matches could be returned. If the value is not found then
1897  /// [`Result::Err`] is returned, containing the index where a matching
1898  /// element could be inserted while maintaining sorted order.
1899  ///
1900  /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
1901  ///
1902  /// [`binary_search_by`]: ArrayDeque::binary_search_by
1903  /// [`binary_search_by_key`]: ArrayDeque::binary_search_by_key
1904  /// [`partition_point`]: ArrayDeque::partition_point
1905  ///
1906  /// ## Examples
1907  ///
1908  /// Looks up a series of four elements. The first is found, with a
1909  /// uniquely determined position; the second and third are not
1910  /// found; the fourth could match any position in `[1, 4]`.
1911  ///
1912  /// ```
1913  /// use generic_arraydeque::{ArrayDeque, typenum::U16};
1914  ///
1915  /// let deque = ArrayDeque::<i32, U16>::try_from_iter([
1916  ///     0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
1917  /// ]).unwrap();
1918  ///
1919  /// assert_eq!(deque.binary_search(&13),  Ok(9));
1920  /// assert_eq!(deque.binary_search(&4),   Err(7));
1921  /// assert_eq!(deque.binary_search(&100), Err(13));
1922  /// let r = deque.binary_search(&1);
1923  /// assert!(matches!(r, Ok(1..=4)));
1924  /// ```
1925  ///
1926  /// If you want to insert an item to a sorted deque, while maintaining
1927  /// sort order, consider using [`partition_point`]:
1928  ///
1929  /// ```
1930  /// use generic_arraydeque::{ArrayDeque, typenum::U16};
1931  ///
1932  /// let deque = ArrayDeque::<i32, U16>::try_from_iter([
1933  ///     0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
1934  /// ]).unwrap();
1935  /// let num = 42;
1936  /// let idx = deque.partition_point(|&x| x <= num);
1937  /// // `idx` can now be used with `insert` to keep the deque sorted.
1938  /// ```
1939  #[inline]
1940  pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1941  where
1942    T: Ord,
1943  {
1944    self.binary_search_by(|e| e.cmp(x))
1945  }
1946
1947  /// Binary searches this deque with a comparator function.
1948  ///
1949  /// The comparator function should return an order code that indicates
1950  /// whether its argument is `Less`, `Equal` or `Greater` the desired
1951  /// target.
1952  /// If the deque is not sorted or if the comparator function does not
1953  /// implement an order consistent with the sort order of the underlying
1954  /// deque, the returned result is unspecified and meaningless.
1955  ///
1956  /// If the value is found then [`Result::Ok`] is returned, containing the
1957  /// index of the matching element. If there are multiple matches, then any
1958  /// one of the matches could be returned. If the value is not found then
1959  /// [`Result::Err`] is returned, containing the index where a matching
1960  /// element could be inserted while maintaining sorted order.
1961  ///
1962  /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
1963  ///
1964  /// [`binary_search`]: ArrayDeque::binary_search
1965  /// [`binary_search_by_key`]: ArrayDeque::binary_search_by_key
1966  /// [`partition_point`]: ArrayDeque::partition_point
1967  ///
1968  /// ## Examples
1969  ///
1970  /// Looks up a series of four elements. The first is found, with a
1971  /// uniquely determined position; the second and third are not
1972  /// found; the fourth could match any position in `[1, 4]`.
1973  ///
1974  /// ```
1975  /// use generic_arraydeque::{ArrayDeque, typenum::U16};
1976  ///
1977  /// let deque = ArrayDeque::<i32, U16>::try_from_iter([
1978  ///     0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
1979  /// ]).unwrap();
1980  ///
1981  /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)),  Ok(9));
1982  /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)),   Err(7));
1983  /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
1984  /// let r = deque.binary_search_by(|x| x.cmp(&1));
1985  /// assert!(matches!(r, Ok(1..=4)));
1986  /// ```
1987  pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1988  where
1989    F: FnMut(&'a T) -> Ordering,
1990  {
1991    let (front, back) = self.as_slices();
1992    let cmp_back = back.first().map(&mut f);
1993
1994    if let Some(Ordering::Equal) = cmp_back {
1995      Ok(front.len())
1996    } else if let Some(Ordering::Less) = cmp_back {
1997      back
1998        .binary_search_by(f)
1999        .map(|idx| idx + front.len())
2000        .map_err(|idx| idx + front.len())
2001    } else {
2002      front.binary_search_by(f)
2003    }
2004  }
2005
2006  /// Binary searches this deque with a key extraction function.
2007  ///
2008  /// Assumes that the deque is sorted by the key, for instance with
2009  /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2010  /// If the deque is not sorted by the key, the returned result is
2011  /// unspecified and meaningless.
2012  ///
2013  /// If the value is found then [`Result::Ok`] is returned, containing the
2014  /// index of the matching element. If there are multiple matches, then any
2015  /// one of the matches could be returned. If the value is not found then
2016  /// [`Result::Err`] is returned, containing the index where a matching
2017  /// element could be inserted while maintaining sorted order.
2018  ///
2019  /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2020  ///
2021  /// [`make_contiguous().sort_by_key()`]: ArrayDeque::make_contiguous
2022  /// [`binary_search`]: ArrayDeque::binary_search
2023  /// [`binary_search_by`]: ArrayDeque::binary_search_by
2024  /// [`partition_point`]: ArrayDeque::partition_point
2025  ///
2026  /// ## Examples
2027  ///
2028  /// Looks up a series of four elements in a slice of pairs sorted by
2029  /// their second elements. The first is found, with a uniquely
2030  /// determined position; the second and third are not found; the
2031  /// fourth could match any position in `[1, 4]`.
2032  ///
2033  /// ```
2034  /// use generic_arraydeque::{ArrayDeque, typenum::U16};
2035  ///
2036  /// let deque = ArrayDeque::<(i32, i32), U16>::try_from_iter([
2037  ///     (0, 0), (2, 1), (4, 1), (5, 1), (3, 1), (1, 2), (2, 3),
2038  ///     (4, 5), (5, 8), (3, 13), (1, 21), (2, 34), (4, 55),
2039  /// ]).unwrap();
2040  ///
2041  /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
2042  /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
2043  /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2044  /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2045  /// assert!(matches!(r, Ok(1..=4)));
2046  /// ```
2047  #[inline]
2048  pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2049  where
2050    F: FnMut(&'a T) -> B,
2051    B: Ord,
2052  {
2053    self.binary_search_by(|k| f(k).cmp(b))
2054  }
2055
2056  /// Returns the index of the partition point according to the given predicate
2057  /// (the index of the first element of the second partition).
2058  ///
2059  /// The deque is assumed to be partitioned according to the given predicate.
2060  /// This means that all elements for which the predicate returns true are at the start of the deque
2061  /// and all elements for which the predicate returns false are at the end.
2062  /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
2063  /// (all odd numbers are at the start, all even at the end).
2064  ///
2065  /// If the deque is not partitioned, the returned result is unspecified and meaningless,
2066  /// as this method performs a kind of binary search.
2067  ///
2068  /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2069  ///
2070  /// [`binary_search`]: ArrayDeque::binary_search
2071  /// [`binary_search_by`]: ArrayDeque::binary_search_by
2072  /// [`binary_search_by_key`]: ArrayDeque::binary_search_by_key
2073  ///
2074  /// ## Examples
2075  ///
2076  /// ```
2077  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
2078  ///
2079  /// let deque = ArrayDeque::<i32, U8>::try_from_iter([1, 2, 3, 3, 5, 6, 7]).unwrap();
2080  /// let i = deque.partition_point(|&x| x < 5);
2081  ///
2082  /// assert_eq!(i, 4);
2083  /// assert!(deque.iter().take(i).all(|&x| x < 5));
2084  /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2085  /// ```
2086  ///
2087  /// If you want to insert an item to a sorted deque, while maintaining
2088  /// sort order:
2089  ///
2090  /// ```
2091  /// use generic_arraydeque::{ArrayDeque, typenum::U16};
2092  ///
2093  /// let deque = ArrayDeque::<i32, U16>::try_from_iter([
2094  ///     0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
2095  /// ]).unwrap();
2096  /// let num = 42;
2097  /// let idx = deque.partition_point(|&x| x < num);
2098  /// // The returned index indicates where `num` should be inserted.
2099  /// ```
2100  pub fn partition_point<P>(&self, mut pred: P) -> usize
2101  where
2102    P: FnMut(&T) -> bool,
2103  {
2104    let (front, back) = self.as_slices();
2105
2106    if let Some(true) = back.first().map(&mut pred) {
2107      back.partition_point(pred) + front.len()
2108    } else {
2109      front.partition_point(pred)
2110    }
2111  }
2112
2113  /// Swaps elements at indices `i` and `j`.
2114  ///
2115  /// `i` and `j` may be equal.
2116  ///
2117  /// Element at index 0 is the front of the queue.
2118  ///
2119  /// ## Panics
2120  ///
2121  /// Panics if either index is out of bounds.
2122  ///
2123  /// ## Examples
2124  ///
2125  /// ```
2126  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
2127  ///
2128  /// let mut buf = ArrayDeque::<i32, U4>::new();
2129  /// assert!(buf.push_back(3).is_none());
2130  /// assert!(buf.push_back(4).is_none());
2131  /// assert!(buf.push_back(5).is_none());
2132  /// buf.swap(0, 2);
2133  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 4, 3]);
2134  /// ```
2135  #[inline(always)]
2136  pub const fn swap(&mut self, i: usize, j: usize) {
2137    assert!(i < self.len());
2138    assert!(j < self.len());
2139    let ri = self.to_physical_idx(i);
2140    let rj = self.to_physical_idx(j);
2141    let base = self.ptr_mut();
2142    unsafe {
2143      ptr::swap(base.add(ri), base.add(rj));
2144    }
2145  }
2146
2147  /// Removes an element from anywhere in the deque and returns it,
2148  /// replacing it with the first element.
2149  ///
2150  /// This does not preserve ordering, but is *O*(1).
2151  ///
2152  /// Returns `None` if `index` is out of bounds.
2153  ///
2154  /// Element at index 0 is the front of the queue.
2155  ///
2156  /// ## Examples
2157  ///
2158  /// ```
2159  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
2160  ///
2161  /// let mut buf = ArrayDeque::<i32, U4>::new();
2162  /// assert_eq!(buf.swap_remove_front(0), None);
2163  /// assert!(buf.push_back(1).is_none());
2164  /// assert!(buf.push_back(2).is_none());
2165  /// assert!(buf.push_back(3).is_none());
2166  /// assert_eq!(buf.swap_remove_front(2), Some(3));
2167  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![2, 1]);
2168  /// ```
2169  #[inline(always)]
2170  pub const fn swap_remove_front(&mut self, index: usize) -> Option<T> {
2171    let length = self.len;
2172    if index < length && index != 0 {
2173      self.swap(index, 0);
2174    } else if index >= length {
2175      return None;
2176    }
2177    self.pop_front()
2178  }
2179
2180  /// Removes an element from anywhere in the deque and returns it,
2181  /// replacing it with the last element.
2182  ///
2183  /// This does not preserve ordering, but is *O*(1).
2184  ///
2185  /// Returns `None` if `index` is out of bounds.
2186  ///
2187  /// Element at index 0 is the front of the queue.
2188  ///
2189  /// ## Examples
2190  ///
2191  /// ```
2192  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
2193  ///
2194  /// let mut buf = ArrayDeque::<i32, U4>::new();
2195  /// assert_eq!(buf.swap_remove_back(0), None);
2196  /// assert!(buf.push_back(1).is_none());
2197  /// assert!(buf.push_back(2).is_none());
2198  /// assert!(buf.push_back(3).is_none());
2199  /// assert_eq!(buf.swap_remove_back(0), Some(1));
2200  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![3, 2]);
2201  /// ```
2202  #[inline(always)]
2203  pub const fn swap_remove_back(&mut self, index: usize) -> Option<T> {
2204    let length = self.len;
2205    if length > 0 && index < length - 1 {
2206      self.swap(index, length - 1);
2207    } else if index >= length {
2208      return None;
2209    }
2210    self.pop_back()
2211  }
2212
2213  /// Inserts an element at `index` within the deque, shifting all elements
2214  /// with indices greater than or equal to `index` towards the back.
2215  ///
2216  /// Returns `Some(value)` if `index` is strictly greater than the deque's length or if
2217  /// the deque is full.
2218  ///
2219  /// Element at index 0 is the front of the queue.
2220  ///
2221  /// ## Examples
2222  ///
2223  /// ```
2224  /// # #[cfg(feature = "std")]
2225  /// # use std::{vec::Vec, vec};
2226  ///
2227  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
2228  ///
2229  /// let mut deque = ArrayDeque::<char, U8>::new();
2230  /// deque.push_back('a');
2231  /// deque.push_back('b');
2232  /// deque.push_back('c');
2233  ///
2234  /// deque.insert(1, 'd');
2235  /// deque.insert(4, 'e');
2236  /// # #[cfg(feature = "std")]
2237  /// assert_eq!(deque.into_iter().collect::<Vec<_>>(), vec!['a', 'd', 'b', 'c', 'e']);
2238  /// ```
2239  #[inline(always)]
2240  pub const fn insert(&mut self, index: usize, value: T) -> Option<T> {
2241    if index > self.len() || self.is_full() {
2242      return Some(value);
2243    }
2244
2245    let _ = insert!(self(index, value));
2246    None
2247  }
2248
2249  /// Removes and returns the element at `index` from the deque.
2250  /// Whichever end is closer to the removal point will be moved to make
2251  /// room, and all the affected elements will be moved to new positions.
2252  /// Returns `None` if `index` is out of bounds.
2253  ///
2254  /// Element at index 0 is the front of the queue.
2255  ///
2256  /// ## Examples
2257  ///
2258  /// ```
2259  /// use generic_arraydeque::{ArrayDeque, typenum::U4};
2260  ///
2261  /// let mut buf = ArrayDeque::<char, U4>::new();
2262  /// assert!(buf.push_back('a').is_none());
2263  /// assert!(buf.push_back('b').is_none());
2264  /// assert!(buf.push_back('c').is_none());
2265  /// assert_eq!(buf.remove(1), Some('b'));
2266  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec!['a', 'c']);
2267  /// ```
2268  #[inline(always)]
2269  pub const fn remove(&mut self, index: usize) -> Option<T> {
2270    if self.len <= index {
2271      return None;
2272    }
2273
2274    let wrapped_idx = self.to_physical_idx(index);
2275
2276    let elem = unsafe { Some(self.buffer_read(wrapped_idx)) };
2277
2278    let k = self.len - index - 1;
2279    // safety: due to the nature of the if-condition, whichever wrap_copy gets called,
2280    // its length argument will be at most `self.len / 2`, so there can't be more than
2281    // one overlapping area.
2282    if k < index {
2283      unsafe { self.wrap_copy(self.wrap_add(wrapped_idx, 1), wrapped_idx, k) };
2284      self.len -= 1;
2285    } else {
2286      let old_head = self.head;
2287      self.head = self.to_physical_idx(1);
2288      unsafe { self.wrap_copy(old_head, self.head, index) };
2289      self.len -= 1;
2290    }
2291
2292    elem
2293  }
2294
2295  /// Retains only the elements specified by the predicate.
2296  ///
2297  /// In other words, remove all elements `e` for which `f(&e)` returns false.
2298  /// This method operates in place, visiting each element exactly once in the
2299  /// original order, and preserves the order of the retained elements.
2300  ///
2301  /// ## Examples
2302  ///
2303  /// ```
2304  /// use generic_arraydeque::{ArrayDeque, typenum::U10};
2305  ///
2306  /// let mut buf = ArrayDeque::<i32, U10>::new();
2307  /// for value in 1..5 {
2308  ///     assert!(buf.push_back(value).is_none());
2309  /// }
2310  /// buf.retain(|&x| x % 2 == 0);
2311  /// assert_eq!(buf, [2, 4]);
2312  /// ```
2313  ///
2314  /// Because the elements are visited exactly once in the original order,
2315  /// external state may be used to decide which elements to keep.
2316  ///
2317  /// ```
2318  /// use generic_arraydeque::{ArrayDeque, typenum::U10};
2319  ///
2320  /// let mut buf = ArrayDeque::<i32, U10>::new();
2321  /// for value in 1..6 {
2322  ///     assert!(buf.push_back(value).is_none());
2323  /// }
2324  ///
2325  /// let keep = [false, true, true, false, true];
2326  /// let mut iter = keep.iter();
2327  /// buf.retain(|_| *iter.next().unwrap());
2328  /// assert_eq!(buf, [2, 3, 5]);
2329  /// ```
2330  pub fn retain<F>(&mut self, mut f: F)
2331  where
2332    F: FnMut(&T) -> bool,
2333  {
2334    self.retain_mut(|elem| f(elem));
2335  }
2336
2337  /// Retains only the elements specified by the predicate.
2338  ///
2339  /// In other words, remove all elements `e` for which `f(&mut e)` returns false.
2340  /// This method operates in place, visiting each element exactly once in the
2341  /// original order, and preserves the order of the retained elements.
2342  ///
2343  /// ## Examples
2344  ///
2345  /// ```
2346  /// use generic_arraydeque::{ArrayDeque, typenum::U10};
2347  ///
2348  /// let mut buf = ArrayDeque::<i32, U10>::new();
2349  /// for value in 1..5 {
2350  ///     assert!(buf.push_back(value).is_none());
2351  /// }
2352  /// buf.retain_mut(|x| if *x % 2 == 0 {
2353  ///     *x += 1;
2354  ///     true
2355  /// } else {
2356  ///     false
2357  /// });
2358  /// assert_eq!(buf, [3, 5]);
2359  /// ```
2360  pub fn retain_mut<F>(&mut self, mut f: F)
2361  where
2362    F: FnMut(&mut T) -> bool,
2363  {
2364    let len = self.len;
2365    let mut idx = 0;
2366    let mut cur = 0;
2367
2368    // Stage 1: All values are retained.
2369    while cur < len {
2370      if !f(&mut self[cur]) {
2371        cur += 1;
2372        break;
2373      }
2374      cur += 1;
2375      idx += 1;
2376    }
2377    // Stage 2: Swap retained value into current idx.
2378    while cur < len {
2379      if !f(&mut self[cur]) {
2380        cur += 1;
2381        continue;
2382      }
2383
2384      self.swap(idx, cur);
2385      cur += 1;
2386      idx += 1;
2387    }
2388    // Stage 3: Truncate all values after idx.
2389    if cur != idx {
2390      self.truncate(idx);
2391    }
2392  }
2393}
2394
2395impl<T, N> ArrayDeque<T, N>
2396where
2397  N: ArrayLength,
2398  T: Clone,
2399{
2400  /// Modifies the deque in-place so that `len()` is equal to new_len,
2401  /// either by removing excess elements from the back or by appending clones of `value`
2402  /// to the back.
2403  ///
2404  /// If the deque is full and needs to be extended, returns `Some(value)` back, the
2405  /// deque is not modified in that case.
2406  ///
2407  /// ## Examples
2408  ///
2409  /// ```
2410  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
2411  ///
2412  /// let mut buf = ArrayDeque::<u32, U8>::new();
2413  /// assert!(buf.push_back(5).is_none());
2414  /// assert!(buf.push_back(10).is_none());
2415  /// assert!(buf.push_back(15).is_none());
2416  ///
2417  /// buf.resize(2, 0);
2418  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10]);
2419  ///
2420  /// let mut buf = ArrayDeque::<u32, U8>::new();
2421  /// assert!(buf.push_back(5).is_none());
2422  /// assert!(buf.push_back(10).is_none());
2423  /// buf.resize(5, 20);
2424  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10, 20, 20, 20]);
2425  /// ```
2426  pub fn resize(&mut self, new_len: usize, value: T) -> Option<T> {
2427    if new_len > self.capacity() {
2428      return Some(value);
2429    }
2430
2431    if new_len > self.len() {
2432      let extra = new_len - self.len();
2433      for v in repeat_n(value, extra) {
2434        self.push_back(v);
2435      }
2436    } else {
2437      self.truncate(new_len);
2438    }
2439
2440    None
2441  }
2442
2443  /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2444  /// either by removing excess elements from the back or by appending
2445  /// elements generated by calling `generator` to the back.
2446  ///
2447  /// If the deque is full and needs to be extended, returns `false`, the
2448  /// deque is not modified in that case.
2449  ///
2450  /// ## Examples
2451  ///
2452  /// ```
2453  /// use generic_arraydeque::{ArrayDeque, typenum::U8};
2454  ///
2455  /// let mut buf = ArrayDeque::<u32, U8>::new();
2456  /// assert!(buf.push_back(5).is_none());
2457  /// assert!(buf.push_back(10).is_none());
2458  /// assert!(buf.push_back(15).is_none());
2459  ///
2460  /// buf.resize_with(5, Default::default);
2461  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10, 15, 0, 0]);
2462  ///
2463  /// let mut buf = ArrayDeque::<u32, U8>::new();
2464  /// assert!(buf.push_back(5).is_none());
2465  /// assert!(buf.push_back(10).is_none());
2466  /// assert!(buf.push_back(15).is_none());
2467  /// buf.resize_with(2, || unreachable!());
2468  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10]);
2469  ///
2470  /// let mut buf = ArrayDeque::<u32, U8>::new();
2471  /// assert!(buf.push_back(5).is_none());
2472  /// assert!(buf.push_back(10).is_none());
2473  /// let mut state = 100;
2474  /// buf.resize_with(5, || {
2475  ///     state += 1;
2476  ///     state
2477  /// });
2478  /// assert_eq!(buf.into_iter().collect::<Vec<_>>(), vec![5, 10, 101, 102, 103]);
2479  /// ```
2480  pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) -> bool {
2481    let len = self.len;
2482    if new_len > self.capacity() {
2483      return false;
2484    }
2485
2486    if new_len > len {
2487      for val in repeat_with(generator).take(new_len - len) {
2488        self.push_back(val);
2489      }
2490    } else {
2491      self.truncate(new_len);
2492    }
2493    true
2494  }
2495}
2496
2497impl<T, N> Drop for ArrayDeque<T, N>
2498where
2499  N: ArrayLength,
2500{
2501  fn drop(&mut self) {
2502    self.clear();
2503  }
2504}
2505
2506impl<T, N> ArrayDeque<T, N>
2507where
2508  N: ArrayLength,
2509{
2510  /// Marginally more convenient
2511  #[inline]
2512  const fn ptr(&self) -> *const MaybeUninit<T> {
2513    self.array.as_slice().as_ptr()
2514  }
2515
2516  /// Marginally more convenient
2517  #[inline]
2518  const fn ptr_mut(&mut self) -> *mut MaybeUninit<T> {
2519    self.array.as_mut_slice().as_mut_ptr()
2520  }
2521
2522  /// Given a range into the logical buffer of the deque, this function
2523  /// return two ranges into the physical buffer that correspond to
2524  /// the given range. The `len` parameter should usually just be `self.len`;
2525  /// the reason it's passed explicitly is that if the deque is wrapped in
2526  /// a `Drain`, then `self.len` is not actually the length of the deque.
2527  ///
2528  /// # Safety
2529  ///
2530  /// This function is always safe to call. For the resulting ranges to be valid
2531  /// ranges into the physical buffer, the caller must ensure that the result of
2532  /// calling `slice::range(range, ..len)` represents a valid range into the
2533  /// logical buffer, and that all elements in that range are initialized.
2534  fn slice_ranges<R>(&self, r: R, len: usize) -> (Range<usize>, Range<usize>)
2535  where
2536    R: RangeBounds<usize>,
2537  {
2538    let Range { start, end } = range::<R>(r, ..len);
2539    let len = end - start;
2540
2541    if len == 0 {
2542      (0..0, 0..0)
2543    } else {
2544      // `slice::range` guarantees that `start <= end <= len`.
2545      // because `len != 0`, we know that `start < end`, so `start < len`
2546      // and the indexing is valid.
2547      let wrapped_start = self.to_physical_idx(start);
2548
2549      // this subtraction can never overflow because `wrapped_start` is
2550      // at most `self.capacity()` (and if `self.capacity != 0`, then `wrapped_start` is strictly less
2551      // than `self.capacity`).
2552      let head_len = self.capacity() - wrapped_start;
2553
2554      if head_len >= len {
2555        // we know that `len + wrapped_start <= self.capacity <= usize::MAX`, so this addition can't overflow
2556        (wrapped_start..wrapped_start + len, 0..0)
2557      } else {
2558        // can't overflow because of the if condition
2559        let tail_len = len - head_len;
2560        (wrapped_start..self.capacity(), 0..tail_len)
2561      }
2562    }
2563  }
2564
2565  /// Given a range into the logical buffer of the deque, this function
2566  /// return two ranges into the physical buffer that correspond to
2567  /// the given range. The `len` parameter should usually just be `self.len`;
2568  /// the reason it's passed explicitly is that if the deque is wrapped in
2569  /// a `Drain`, then `self.len` is not actually the length of the deque.
2570  ///
2571  /// # Safety
2572  ///
2573  /// This function is always safe to call. For the resulting ranges to be valid
2574  /// ranges into the physical buffer, the caller must ensure that the result of
2575  /// calling `slice::range(range, ..len)` represents a valid range into the
2576  /// logical buffer, and that all elements in that range are initialized.
2577  const fn slice_full_ranges(&self) -> (Range<usize>, Range<usize>) {
2578    let start = 0;
2579    let end = self.len;
2580    let len = end - start;
2581
2582    if len == 0 {
2583      (0..0, 0..0)
2584    } else {
2585      // `slice::range` guarantees that `start <= end <= len`.
2586      // because `len != 0`, we know that `start < end`, so `start < len`
2587      // and the indexing is valid.
2588      let wrapped_start = self.to_physical_idx(start);
2589
2590      // this subtraction can never overflow because `wrapped_start` is
2591      // at most `self.capacity()` (and if `self.capacity != 0`, then `wrapped_start` is strictly less
2592      // than `self.capacity`).
2593      let head_len = self.capacity() - wrapped_start;
2594
2595      if head_len >= len {
2596        // we know that `len + wrapped_start <= self.capacity <= usize::MAX`, so this addition can't overflow
2597        (wrapped_start..wrapped_start + len, 0..0)
2598      } else {
2599        // can't overflow because of the if condition
2600        let tail_len = len - head_len;
2601        (wrapped_start..self.capacity(), 0..tail_len)
2602      }
2603    }
2604  }
2605
2606  /// Returns the index in the underlying buffer for a given logical element
2607  /// index + addend.
2608  #[inline]
2609  const fn wrap_add(&self, idx: usize, addend: usize) -> usize {
2610    wrap_index(idx.wrapping_add(addend), self.capacity())
2611  }
2612
2613  #[inline]
2614  const fn to_physical_idx(&self, idx: usize) -> usize {
2615    self.wrap_add(self.head, idx)
2616  }
2617
2618  /// Returns the index in the underlying buffer for a given logical element
2619  /// index - subtrahend.
2620  #[inline]
2621  const fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
2622    wrap_index(
2623      idx.wrapping_sub(subtrahend).wrapping_add(self.capacity()),
2624      self.capacity(),
2625    )
2626  }
2627
2628  /// Moves an element out of the buffer
2629  ///
2630  /// ## Safety
2631  /// - `off` must be a valid index into the buffer containing an initialized value
2632  #[inline]
2633  const unsafe fn buffer_read(&self, off: usize) -> T {
2634    unsafe { (&*self.ptr().add(off)).assume_init_read() }
2635  }
2636
2637  /// Returns a slice pointer into the buffer.
2638  /// `range` must lie inside `0..self.capacity()`.
2639  #[inline]
2640  const unsafe fn buffer_range(&self, range: Range<usize>) -> *const [T] {
2641    unsafe { ptr::slice_from_raw_parts(self.ptr().add(range.start) as _, range.end - range.start) }
2642  }
2643
2644  /// Returns a slice pointer into the buffer.
2645  /// `range` must lie inside `0..self.capacity()`.
2646  #[inline]
2647  const unsafe fn buffer_range_mut(&mut self, range: Range<usize>) -> *mut [T] {
2648    unsafe {
2649      ptr::slice_from_raw_parts_mut(
2650        self.ptr_mut().add(range.start) as _,
2651        range.end - range.start,
2652      )
2653    }
2654  }
2655
2656  /// Writes an element into the buffer, moving it and returning a pointer to it.
2657  /// # Safety
2658  ///
2659  /// May only be called if `off < self.capacity()`.
2660  #[inline]
2661  const unsafe fn buffer_write(&mut self, off: usize, value: T) -> &mut T {
2662    unsafe {
2663      let ptr = &mut *self.ptr_mut().add(off);
2664      ptr.write(value);
2665      ptr.assume_init_mut()
2666    }
2667  }
2668
2669  const unsafe fn rotate_left_inner(&mut self, mid: usize) {
2670    debug_assert!(mid * 2 <= self.len());
2671    unsafe {
2672      self.wrap_copy(self.head, self.to_physical_idx(self.len), mid);
2673    }
2674    self.head = self.to_physical_idx(mid);
2675  }
2676
2677  const unsafe fn rotate_right_inner(&mut self, k: usize) {
2678    debug_assert!(k * 2 <= self.len());
2679    self.head = self.wrap_sub(self.head, k);
2680    unsafe {
2681      self.wrap_copy(self.to_physical_idx(self.len), self.head, k);
2682    }
2683  }
2684
2685  /// Copies a contiguous block of memory len long from src to dst
2686  #[inline]
2687  const unsafe fn copy(&mut self, src: usize, dst: usize, len: usize) {
2688    check_copy_bounds(dst, src, len, self.capacity());
2689
2690    unsafe {
2691      let base_ptr = self.ptr_mut();
2692      let src_ptr = base_ptr.add(src) as *const MaybeUninit<T>;
2693      let dst_ptr = base_ptr.add(dst);
2694      ptr::copy(src_ptr, dst_ptr, len);
2695    }
2696  }
2697
2698  /// Copies all values from `src` to `dst`, wrapping around if needed.
2699  /// Assumes capacity is sufficient.
2700  #[inline]
2701  const unsafe fn copy_slice(&mut self, dst: usize, src: &[T]) {
2702    debug_assert!(src.len() <= self.capacity());
2703    let head_room = self.capacity() - dst;
2704    if src.len() <= head_room {
2705      unsafe {
2706        ptr::copy_nonoverlapping(src.as_ptr(), self.ptr_mut().add(dst) as _, src.len());
2707      }
2708    } else {
2709      let (left, right) = src.split_at(head_room);
2710      unsafe {
2711        ptr::copy_nonoverlapping(left.as_ptr(), self.ptr_mut().add(dst) as _, left.len());
2712        ptr::copy_nonoverlapping(right.as_ptr(), self.ptr_mut() as _, right.len());
2713      }
2714    }
2715  }
2716
2717  /// Copies a contiguous block of memory len long from src to dst
2718  #[inline]
2719  const unsafe fn copy_nonoverlapping(&mut self, src: usize, dst: usize, len: usize) {
2720    check_copy_bounds(dst, src, len, self.capacity());
2721    unsafe {
2722      let base_ptr = self.ptr_mut();
2723      let src_ptr = base_ptr.add(src) as *const MaybeUninit<T>;
2724      let dst_ptr = base_ptr.add(dst);
2725      ptr::copy_nonoverlapping(src_ptr, dst_ptr, len);
2726    }
2727  }
2728
2729  /// Copies a potentially wrapping block of memory len long from src to dest.
2730  /// (abs(dst - src) + len) must be no larger than capacity() (There must be at
2731  /// most one continuous overlapping region between src and dest).
2732  const unsafe fn wrap_copy(&mut self, src: usize, dst: usize, len: usize) {
2733    // debug_assert!(
2734    //   cmp::min(src.abs_diff(dst), self.capacity() - src.abs_diff(dst)) + len <= self.capacity(),
2735    //   "wrc dst={} src={} len={} cap={}",
2736    //   dst,
2737    //   src,
2738    //   len,
2739    //   self.capacity()
2740    // );
2741
2742    // If T is a ZST, don't do any copying.
2743    if mem::size_of::<T>() == 0 || src == dst || len == 0 {
2744      return;
2745    }
2746
2747    let dst_after_src = self.wrap_sub(dst, src) < len;
2748
2749    let src_pre_wrap_len = self.capacity() - src;
2750    let dst_pre_wrap_len = self.capacity() - dst;
2751    let src_wraps = src_pre_wrap_len < len;
2752    let dst_wraps = dst_pre_wrap_len < len;
2753
2754    match (dst_after_src, src_wraps, dst_wraps) {
2755      (_, false, false) => {
2756        // src doesn't wrap, dst doesn't wrap
2757        //
2758        //        S . . .
2759        // 1 [_ _ A A B B C C _]
2760        // 2 [_ _ A A A A B B _]
2761        //            D . . .
2762        //
2763        unsafe {
2764          self.copy(src, dst, len);
2765        }
2766      }
2767      (false, false, true) => {
2768        // dst before src, src doesn't wrap, dst wraps
2769        //
2770        //    S . . .
2771        // 1 [A A B B _ _ _ C C]
2772        // 2 [A A B B _ _ _ A A]
2773        // 3 [B B B B _ _ _ A A]
2774        //    . .           D .
2775        //
2776        unsafe {
2777          self.copy(src, dst, dst_pre_wrap_len);
2778          self.copy(src + dst_pre_wrap_len, 0, len - dst_pre_wrap_len);
2779        }
2780      }
2781      (true, false, true) => {
2782        // src before dst, src doesn't wrap, dst wraps
2783        //
2784        //              S . . .
2785        // 1 [C C _ _ _ A A B B]
2786        // 2 [B B _ _ _ A A B B]
2787        // 3 [B B _ _ _ A A A A]
2788        //    . .           D .
2789        //
2790        unsafe {
2791          self.copy(src + dst_pre_wrap_len, 0, len - dst_pre_wrap_len);
2792          self.copy(src, dst, dst_pre_wrap_len);
2793        }
2794      }
2795      (false, true, false) => {
2796        // dst before src, src wraps, dst doesn't wrap
2797        //
2798        //    . .           S .
2799        // 1 [C C _ _ _ A A B B]
2800        // 2 [C C _ _ _ B B B B]
2801        // 3 [C C _ _ _ B B C C]
2802        //              D . . .
2803        //
2804        unsafe {
2805          self.copy(src, dst, src_pre_wrap_len);
2806          self.copy(0, dst + src_pre_wrap_len, len - src_pre_wrap_len);
2807        }
2808      }
2809      (true, true, false) => {
2810        // src before dst, src wraps, dst doesn't wrap
2811        //
2812        //    . .           S .
2813        // 1 [A A B B _ _ _ C C]
2814        // 2 [A A A A _ _ _ C C]
2815        // 3 [C C A A _ _ _ C C]
2816        //    D . . .
2817        //
2818        unsafe {
2819          self.copy(0, dst + src_pre_wrap_len, len - src_pre_wrap_len);
2820          self.copy(src, dst, src_pre_wrap_len);
2821        }
2822      }
2823      (false, true, true) => {
2824        // dst before src, src wraps, dst wraps
2825        //
2826        //    . . .         S .
2827        // 1 [A B C D _ E F G H]
2828        // 2 [A B C D _ E G H H]
2829        // 3 [A B C D _ E G H A]
2830        // 4 [B C C D _ E G H A]
2831        //    . .         D . .
2832        //
2833        debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
2834        let delta = dst_pre_wrap_len - src_pre_wrap_len;
2835        unsafe {
2836          self.copy(src, dst, src_pre_wrap_len);
2837          self.copy(0, dst + src_pre_wrap_len, delta);
2838          self.copy(delta, 0, len - dst_pre_wrap_len);
2839        }
2840      }
2841      (true, true, true) => {
2842        // src before dst, src wraps, dst wraps
2843        //
2844        //    . .         S . .
2845        // 1 [A B C D _ E F G H]
2846        // 2 [A A B D _ E F G H]
2847        // 3 [H A B D _ E F G H]
2848        // 4 [H A B D _ E F F G]
2849        //    . . .         D .
2850        //
2851        debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
2852        let delta = src_pre_wrap_len - dst_pre_wrap_len;
2853        unsafe {
2854          self.copy(0, delta, len - src_pre_wrap_len);
2855          self.copy(self.capacity() - delta, 0, delta);
2856          self.copy(src, dst, dst_pre_wrap_len);
2857        }
2858      }
2859    }
2860  }
2861
2862  /// Writes all values from `iter` to `dst`.
2863  ///
2864  /// # Safety
2865  ///
2866  /// Assumes no wrapping around happens.
2867  /// Assumes capacity is sufficient.
2868  #[inline]
2869  #[cfg(feature = "std")]
2870  unsafe fn write_iter(&mut self, dst: usize, iter: impl Iterator<Item = T>, written: &mut usize) {
2871    iter.enumerate().for_each(|(i, element)| unsafe {
2872      self.buffer_write(dst + i, element);
2873      *written += 1;
2874    });
2875  }
2876
2877  /// Writes all values from `iter` to `dst`, wrapping
2878  /// at the end of the buffer and returns the number
2879  /// of written values.
2880  ///
2881  /// # Safety
2882  ///
2883  /// Assumes that `iter` yields at most `len` items.
2884  /// Assumes capacity is sufficient.
2885  #[cfg(feature = "std")]
2886  unsafe fn write_iter_wrapping(
2887    &mut self,
2888    dst: usize,
2889    mut iter: impl Iterator<Item = T>,
2890    len: usize,
2891  ) -> usize {
2892    struct Guard<'a, T, N: ArrayLength> {
2893      deque: &'a mut ArrayDeque<T, N>,
2894      written: usize,
2895    }
2896
2897    impl<T, N: ArrayLength> Drop for Guard<'_, T, N> {
2898      fn drop(&mut self) {
2899        self.deque.len += self.written;
2900      }
2901    }
2902
2903    let head_room = self.capacity() - dst;
2904
2905    let mut guard = Guard {
2906      deque: self,
2907      written: 0,
2908    };
2909
2910    if head_room >= len {
2911      unsafe { guard.deque.write_iter(dst, iter, &mut guard.written) };
2912    } else {
2913      unsafe {
2914        guard
2915          .deque
2916          .write_iter(dst, iter.by_ref().take(head_room), &mut guard.written);
2917        guard.deque.write_iter(0, iter, &mut guard.written)
2918      };
2919    }
2920
2921    guard.written
2922  }
2923
2924  #[inline]
2925  const fn is_contiguous(&self) -> bool {
2926    // Do the calculation like this to avoid overflowing if len + head > usize::MAX
2927    self.head <= self.capacity() - self.len
2928  }
2929}
2930
2931/// Returns the index in the underlying buffer for a given logical element index.
2932#[inline]
2933const fn wrap_index(logical_index: usize, capacity: usize) -> usize {
2934  debug_assert!(
2935    (logical_index == 0 && capacity == 0)
2936      || logical_index < capacity
2937      || (logical_index - capacity) < capacity
2938  );
2939  if logical_index >= capacity {
2940    logical_index - capacity
2941  } else {
2942    logical_index
2943  }
2944}
2945
2946fn range<R>(range: R, bounds: ops::RangeTo<usize>) -> ops::Range<usize>
2947where
2948  R: ops::RangeBounds<usize>,
2949{
2950  let len = bounds.end;
2951
2952  let end = match range.end_bound() {
2953    ops::Bound::Included(&end) if end >= len => slice_index_fail(0, end, len),
2954    // Cannot overflow because `end < len` implies `end < usize::MAX`.
2955    ops::Bound::Included(&end) => end + 1,
2956
2957    ops::Bound::Excluded(&end) if end > len => slice_index_fail(0, end, len),
2958    ops::Bound::Excluded(&end) => end,
2959    ops::Bound::Unbounded => len,
2960  };
2961
2962  let start = match range.start_bound() {
2963    ops::Bound::Excluded(&start) if start >= end => slice_index_fail(start, end, len),
2964    // Cannot overflow because `start < end` implies `start < usize::MAX`.
2965    ops::Bound::Excluded(&start) => start + 1,
2966
2967    ops::Bound::Included(&start) if start > end => slice_index_fail(start, end, len),
2968    ops::Bound::Included(&start) => start,
2969
2970    ops::Bound::Unbounded => 0,
2971  };
2972
2973  ops::Range { start, end }
2974}
2975
2976#[cfg(feature = "unstable")]
2977fn try_range<R>(range: R, bounds: ops::RangeTo<usize>) -> Option<ops::Range<usize>>
2978where
2979  R: ops::RangeBounds<usize>,
2980{
2981  let len = bounds.end;
2982
2983  let end = match range.end_bound() {
2984    ops::Bound::Included(&end) if end >= len => return None,
2985    // Cannot overflow because `end < len` implies `end < usize::MAX`.
2986    ops::Bound::Included(&end) => end + 1,
2987
2988    ops::Bound::Excluded(&end) if end > len => return None,
2989    ops::Bound::Excluded(&end) => end,
2990    ops::Bound::Unbounded => len,
2991  };
2992
2993  let start = match range.start_bound() {
2994    ops::Bound::Excluded(&start) if start >= end => return None,
2995    // Cannot overflow because `start < end` implies `start < usize::MAX`.
2996    ops::Bound::Excluded(&start) => start + 1,
2997
2998    ops::Bound::Included(&start) if start > end => return None,
2999    ops::Bound::Included(&start) => start,
3000
3001    ops::Bound::Unbounded => 0,
3002  };
3003
3004  Some(ops::Range { start, end })
3005}
3006
3007#[track_caller]
3008fn slice_index_fail(start: usize, end: usize, len: usize) -> ! {
3009  if start > len {
3010    panic!(
3011      // "slice start index is out of range for slice",
3012      "range start index {start} out of range for slice of length {len}",
3013      // start: usize,
3014      // len: usize,
3015    )
3016  }
3017
3018  if end > len {
3019    panic!(
3020      // "slice end index is out of range for slice",
3021      "range end index {end} out of range for slice of length {len}",
3022      // end: usize,
3023      // len: usize,
3024    )
3025  }
3026
3027  if start > end {
3028    panic!(
3029      // "slice index start is larger than end",
3030      "slice index starts at {start} but ends at {end}",
3031      // start: usize,
3032      // end: usize,
3033    )
3034  }
3035
3036  // Only reachable if the range was a `RangeInclusive` or a
3037  // `RangeToInclusive`, with `end == len`.
3038  panic!(
3039    // "slice end index is out of range for slice",
3040    "range end index {end} out of range for slice of length {len}",
3041    // end: usize,
3042    // len: usize,
3043  )
3044}
3045
3046const fn check_copy_bounds(dst: usize, src: usize, len: usize, cap: usize) {
3047  debug_assert!(dst + len <= cap,);
3048  debug_assert!(src + len <= cap,);
3049}
3050
3051#[inline(always)]
3052fn repeat_n<T: Clone>(element: T, count: usize) -> impl Iterator<Item = T> {
3053  core::iter::repeat_n(element, count)
3054}
3055
3056#[inline(always)]
3057const unsafe fn assert_unchecked(cond: bool) {
3058  unsafe {
3059    core::hint::assert_unchecked(cond);
3060  }
3061}