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