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