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