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