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