rune_alloc/vec_deque/
mod.rs

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