Skip to main content

alloc/collections/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#![stable(feature = "rust1", since = "1.0.0")]
9
10#[cfg(not(no_global_oom_handling))]
11use core::clone::TrivialClone;
12use core::cmp::{self, Ordering};
13use core::hash::{Hash, Hasher};
14use core::iter::{ByRefSized, repeat_n, repeat_with};
15// This is used in a bunch of intra-doc links.
16// FIXME: For some reason, `#[cfg(doc)]` wasn't sufficient, resulting in
17// failures in linkchecker even though rustdoc built the docs just fine.
18#[allow(unused_imports)]
19use core::mem;
20use core::mem::{ManuallyDrop, SizedTypeProperties};
21use core::ops::{Index, IndexMut, Range, RangeBounds};
22use core::{fmt, ptr, slice};
23
24use crate::alloc::{Allocator, Global};
25use crate::collections::{TryReserveError, TryReserveErrorKind};
26use crate::raw_vec::RawVec;
27use crate::vec::Vec;
28
29#[macro_use]
30mod macros;
31
32#[stable(feature = "drain", since = "1.6.0")]
33pub use self::drain::Drain;
34
35mod drain;
36
37#[unstable(feature = "vec_deque_extract_if", issue = "147750")]
38pub use self::extract_if::ExtractIf;
39
40mod extract_if;
41
42#[stable(feature = "rust1", since = "1.0.0")]
43pub use self::iter_mut::IterMut;
44
45mod iter_mut;
46
47#[stable(feature = "rust1", since = "1.0.0")]
48pub use self::into_iter::IntoIter;
49
50mod into_iter;
51
52#[stable(feature = "rust1", since = "1.0.0")]
53pub use self::iter::Iter;
54
55mod iter;
56
57use self::spec_extend::{SpecExtend, SpecExtendFront};
58
59mod spec_extend;
60
61use self::spec_from_iter::SpecFromIter;
62
63mod spec_from_iter;
64
65#[cfg(not(no_global_oom_handling))]
66#[unstable(feature = "deque_extend_front", issue = "146975")]
67pub use self::splice::Splice;
68
69#[cfg(not(no_global_oom_handling))]
70mod splice;
71
72#[cfg(test)]
73mod tests;
74
75/// A double-ended queue implemented with a growable ring buffer.
76///
77/// The "default" usage of this type as a queue is to use [`push_back`] to add to
78/// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
79/// push onto the back in this manner, and iterating over `VecDeque` goes front
80/// to back.
81///
82/// A `VecDeque` with a known list of items can be initialized from an array:
83///
84/// ```
85/// use std::collections::VecDeque;
86///
87/// let deq = VecDeque::from([-1, 0, 1]);
88/// ```
89///
90/// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
91/// in memory. If you want to access the elements as a single slice, such as for
92/// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
93/// so that its elements do not wrap, and returns a mutable slice to the
94/// now-contiguous element sequence.
95///
96/// [`push_back`]: VecDeque::push_back
97/// [`pop_front`]: VecDeque::pop_front
98/// [`extend`]: VecDeque::extend
99/// [`append`]: VecDeque::append
100/// [`make_contiguous`]: VecDeque::make_contiguous
101#[cfg_attr(not(test), rustc_diagnostic_item = "VecDeque")]
102#[stable(feature = "rust1", since = "1.0.0")]
103#[rustc_insignificant_dtor]
104pub struct VecDeque<
105    T,
106    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
107> {
108    // `self[0]`, if it exists, is `buf[head]`.
109    // `head < buf.capacity()`, unless `buf.capacity() == 0` when `head == 0`.
110    head: WrappedIndex,
111    // the number of initialized elements, starting from the one at `head` and potentially wrapping around.
112    // if `len == 0`, the exact value of `head` is unimportant.
113    // if `T` is zero-Sized, then `self.len <= usize::MAX`, otherwise `self.len <= isize::MAX as usize`.
114    len: usize,
115    buf: RawVec<T, A>,
116}
117
118#[stable(feature = "rust1", since = "1.0.0")]
119impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A> {
120    fn clone(&self) -> Self {
121        let mut deq = Self::with_capacity_in(self.len(), self.allocator().clone());
122        deq.extend(self.iter().cloned());
123        deq
124    }
125
126    /// Overwrites the contents of `self` with a clone of the contents of `source`.
127    ///
128    /// This method is preferred over simply assigning `source.clone()` to `self`,
129    /// as it avoids reallocation if possible.
130    fn clone_from(&mut self, source: &Self) {
131        self.clear();
132        self.extend(source.iter().cloned());
133    }
134}
135
136/// Runs the destructor for all items in the slice when it gets dropped (normally or
137/// during unwinding).
138struct Dropper<'a, T>(&'a mut [T]);
139
140impl<T> Drop for Dropper<'_, T> {
141    fn drop(&mut self) {
142        unsafe {
143            ptr::drop_in_place(self.0);
144        }
145    }
146}
147
148#[stable(feature = "rust1", since = "1.0.0")]
149unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
150    fn drop(&mut self) {
151        let (front, back) = self.as_mut_slices();
152        unsafe {
153            let _back_dropper = Dropper(back);
154            // use drop for [T]
155            ptr::drop_in_place(front);
156        }
157        // RawVec handles deallocation
158    }
159}
160
161#[stable(feature = "rust1", since = "1.0.0")]
162impl<T> Default for VecDeque<T> {
163    /// Creates an empty deque.
164    #[inline]
165    fn default() -> VecDeque<T> {
166        VecDeque::new()
167    }
168}
169
170impl<T, A: Allocator> VecDeque<T, A> {
171    /// Marginally more convenient
172    #[inline]
173    fn ptr(&self) -> *mut T {
174        self.buf.ptr()
175    }
176
177    /// Appends an element to the buffer.
178    ///
179    /// # Safety
180    ///
181    /// May only be called if `deque.len() < deque.capacity()`
182    #[inline]
183    unsafe fn push_unchecked(&mut self, element: T) {
184        // SAFETY: Because of the precondition, it's guaranteed that there is space
185        // in the logical array after the last element.
186        unsafe { self.buffer_write(self.to_wrapped_index(self.len), element) };
187        // This can't overflow because `deque.len() < deque.capacity() <= usize::MAX`.
188        self.len += 1;
189    }
190
191    /// Prepends an element to the buffer.
192    ///
193    /// # Safety
194    ///
195    /// May only be called if `deque.len() < deque.capacity()`
196    #[inline]
197    unsafe fn push_front_unchecked(&mut self, element: T) {
198        self.head = self.wrap_sub(self.head, 1);
199        // SAFETY: Because of the precondition, it's guaranteed that there is space
200        // in the logical array before the first element (where self.head is now).
201        unsafe { self.buffer_write(self.head, element) };
202        // This can't overflow because `deque.len() < deque.capacity() <= usize::MAX`.
203        self.len += 1;
204    }
205
206    /// Moves an element out of the buffer
207    #[inline]
208    unsafe fn buffer_read(&mut self, off: WrappedIndex) -> T {
209        unsafe { ptr::read(self.ptr().add(off.as_index())) }
210    }
211
212    /// Writes an element into the buffer, moving it and returning a pointer to it.
213    /// # Safety
214    ///
215    /// May only be called if `off < self.capacity()`.
216    #[inline]
217    unsafe fn buffer_write(&mut self, off: WrappedIndex, value: T) -> &mut T {
218        unsafe {
219            let ptr = self.ptr().add(off.as_index());
220            ptr::write(ptr, value);
221            &mut *ptr
222        }
223    }
224
225    /// Returns a slice pointer into the buffer.
226    /// `range` must lie inside `0..self.capacity()`.
227    #[inline]
228    unsafe fn buffer_range(&self, range: Range<usize>) -> *mut [T] {
229        unsafe { self.ptr().add(range.start).cast_slice(range.end - range.start) }
230    }
231
232    /// Returns `true` if the buffer is at full capacity.
233    #[inline]
234    fn is_full(&self) -> bool {
235        self.len == self.capacity()
236    }
237
238    /// Returns the index in the underlying buffer for a given logical element
239    /// index + addend.
240    #[inline]
241    fn wrap_add(&self, idx: WrappedIndex, addend: usize) -> WrappedIndex {
242        wrap_index(idx.as_index().wrapping_add(addend), self.capacity())
243    }
244
245    #[inline]
246    fn to_wrapped_index(&self, idx: usize) -> WrappedIndex {
247        self.wrap_add(self.head, idx)
248    }
249
250    /// Returns the index in the underlying buffer for a given logical element
251    /// index - subtrahend.
252    #[inline]
253    fn wrap_sub(&self, idx: WrappedIndex, subtrahend: usize) -> WrappedIndex {
254        wrap_index(
255            idx.as_index().wrapping_sub(subtrahend).wrapping_add(self.capacity()),
256            self.capacity(),
257        )
258    }
259
260    /// Get source, destination and count (like the arguments to [`ptr::copy_nonoverlapping`])
261    /// for copying `count` values from index `src` to index `dst`.
262    /// One of the ranges can wrap around the physical buffer, for this reason 2 triples are returned.
263    ///
264    /// Use of the word "ranges" specifically refers to `src..src + count` and `dst..dst + count`.
265    ///
266    /// # Safety
267    ///
268    /// - Ranges must not overlap: `src.abs_diff(dst) >= count`.
269    /// - Ranges must be in bounds of the logical buffer: `src + count <= self.capacity()` and `dst + count <= self.capacity()`.
270    /// - `head` must be in bounds: `head < self.capacity()`, unless `self.capacity() == 0`, in which case `head == 0`.
271    #[cfg(not(no_global_oom_handling))]
272    unsafe fn nonoverlapping_ranges(
273        &mut self,
274        src: usize,
275        dst: usize,
276        count: usize,
277        head: WrappedIndex,
278    ) -> [(*const T, *mut T, usize); 2] {
279        // "`src` and `dst` must be at least as far apart as `count`"
280        debug_assert!(
281            src.abs_diff(dst) >= count,
282            "`src` and `dst` must not overlap. src={src} dst={dst} count={count}",
283        );
284        debug_assert!(
285            src.max(dst) + count <= self.capacity(),
286            "ranges must be in bounds. src={src} dst={dst} count={count} cap={}",
287            self.capacity(),
288        );
289
290        let wrapped_src = self.wrap_add(head, src);
291        let wrapped_dst = self.wrap_add(head, dst);
292
293        let room_after_src = self.capacity() - wrapped_src.as_index();
294        let room_after_dst = self.capacity() - wrapped_dst.as_index();
295
296        let src_wraps = room_after_src < count;
297        let dst_wraps = room_after_dst < count;
298
299        // Wrapping occurs if `capacity` is contained within `wrapped_src..wrapped_src + count` or `wrapped_dst..wrapped_dst + count`.
300        // Since these two ranges must not overlap as per the safety invariants of this function, only one range can wrap.
301        debug_assert!(
302            !(src_wraps && dst_wraps),
303            "BUG: at most one of src and dst can wrap. src={src} dst={dst} count={count} cap={}",
304            self.capacity(),
305        );
306
307        unsafe {
308            let ptr = self.ptr();
309            let src_ptr = ptr.add(wrapped_src.as_index());
310            let dst_ptr = ptr.add(wrapped_dst.as_index());
311
312            if src_wraps {
313                [
314                    (src_ptr, dst_ptr, room_after_src),
315                    (ptr, dst_ptr.add(room_after_src), count - room_after_src),
316                ]
317            } else if dst_wraps {
318                [
319                    (src_ptr, dst_ptr, room_after_dst),
320                    (src_ptr.add(room_after_dst), ptr, count - room_after_dst),
321                ]
322            } else {
323                [
324                    (src_ptr, dst_ptr, count),
325                    // null pointers are fine as long as the count is 0
326                    (ptr::null(), ptr::null_mut(), 0),
327                ]
328            }
329        }
330    }
331
332    /// Copies a contiguous block of memory len long from src to dst
333    #[inline]
334    unsafe fn copy(&mut self, src: WrappedIndex, dst: WrappedIndex, len: usize) {
335        debug_assert!(
336            dst + len <= self.capacity(),
337            "cpy dst={} src={} len={} cap={}",
338            dst,
339            src,
340            len,
341            self.capacity()
342        );
343        debug_assert!(
344            src + len <= self.capacity(),
345            "cpy dst={} src={} len={} cap={}",
346            dst,
347            src,
348            len,
349            self.capacity()
350        );
351        unsafe {
352            ptr::copy(self.ptr().add(src.as_index()), self.ptr().add(dst.as_index()), len);
353        }
354    }
355
356    /// Copies a contiguous block of memory len long from src to dst
357    #[inline]
358    unsafe fn copy_nonoverlapping(&mut self, src: WrappedIndex, dst: WrappedIndex, len: usize) {
359        debug_assert!(
360            dst + len <= self.capacity(),
361            "cno dst={} src={} len={} cap={}",
362            dst,
363            src,
364            len,
365            self.capacity()
366        );
367        debug_assert!(
368            src + len <= self.capacity(),
369            "cno dst={} src={} len={} cap={}",
370            dst,
371            src,
372            len,
373            self.capacity()
374        );
375        unsafe {
376            ptr::copy_nonoverlapping(
377                self.ptr().add(src.as_index()),
378                self.ptr().add(dst.as_index()),
379                len,
380            );
381        }
382    }
383
384    /// Copies a potentially wrapping block of memory len long from src to dest.
385    /// (abs(dst - src) + len) must be no larger than capacity() (There must be at
386    /// most one continuous overlapping region between src and dest).
387    unsafe fn wrap_copy(&mut self, src: WrappedIndex, dst: WrappedIndex, len: usize) {
388        debug_assert!(
389            cmp::min(src.abs_diff(dst), self.capacity() - src.abs_diff(dst)) + len
390                <= self.capacity(),
391            "wrc dst={} src={} len={} cap={}",
392            dst,
393            src,
394            len,
395            self.capacity()
396        );
397
398        // If T is a ZST, don't do any copying.
399        if T::IS_ZST || src == dst || len == 0 {
400            return;
401        }
402
403        let dst_after_src = self.wrap_sub(dst, src.as_index()) < len;
404
405        let src_pre_wrap_len = self.capacity() - src.as_index();
406        let dst_pre_wrap_len = self.capacity() - dst.as_index();
407        let src_wraps = src_pre_wrap_len < len;
408        let dst_wraps = dst_pre_wrap_len < len;
409
410        match (dst_after_src, src_wraps, dst_wraps) {
411            (_, false, false) => {
412                // src doesn't wrap, dst doesn't wrap
413                //
414                //        S . . .
415                // 1 [_ _ A A B B C C _]
416                // 2 [_ _ A A A A B B _]
417                //            D . . .
418                //
419                unsafe {
420                    self.copy(src, dst, len);
421                }
422            }
423            (false, false, true) => {
424                // dst before src, src doesn't wrap, dst wraps
425                //
426                //    S . . .
427                // 1 [A A B B _ _ _ C C]
428                // 2 [A A B B _ _ _ A A]
429                // 3 [B B B B _ _ _ A A]
430                //    . .           D .
431                //
432                unsafe {
433                    self.copy(src, dst, dst_pre_wrap_len);
434                    self.copy(
435                        src.add(dst_pre_wrap_len),
436                        WrappedIndex::zero(),
437                        len - dst_pre_wrap_len,
438                    );
439                }
440            }
441            (true, false, true) => {
442                // src before dst, src doesn't wrap, dst wraps
443                //
444                //              S . . .
445                // 1 [C C _ _ _ A A B B]
446                // 2 [B B _ _ _ A A B B]
447                // 3 [B B _ _ _ A A A A]
448                //    . .           D .
449                //
450                unsafe {
451                    self.copy(
452                        src.add(dst_pre_wrap_len),
453                        WrappedIndex::zero(),
454                        len - dst_pre_wrap_len,
455                    );
456                    self.copy(src, dst, dst_pre_wrap_len);
457                }
458            }
459            (false, true, false) => {
460                // dst before src, src wraps, dst doesn't wrap
461                //
462                //    . .           S .
463                // 1 [C C _ _ _ A A B B]
464                // 2 [C C _ _ _ B B B B]
465                // 3 [C C _ _ _ B B C C]
466                //              D . . .
467                //
468                unsafe {
469                    self.copy(src, dst, src_pre_wrap_len);
470                    self.copy(
471                        WrappedIndex::zero(),
472                        dst.add(src_pre_wrap_len),
473                        len - src_pre_wrap_len,
474                    );
475                }
476            }
477            (true, true, false) => {
478                // src before dst, src wraps, dst doesn't wrap
479                //
480                //    . .           S .
481                // 1 [A A B B _ _ _ C C]
482                // 2 [A A A A _ _ _ C C]
483                // 3 [C C A A _ _ _ C C]
484                //    D . . .
485                //
486                unsafe {
487                    self.copy(
488                        WrappedIndex::zero(),
489                        dst.add(src_pre_wrap_len),
490                        len - src_pre_wrap_len,
491                    );
492                    self.copy(src, dst, src_pre_wrap_len);
493                }
494            }
495            (false, true, true) => {
496                // dst before src, src wraps, dst wraps
497                //
498                //    . . .         S .
499                // 1 [A B C D _ E F G H]
500                // 2 [A B C D _ E G H H]
501                // 3 [A B C D _ E G H A]
502                // 4 [B C C D _ E G H A]
503                //    . .         D . .
504                //
505                debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
506                let delta = dst_pre_wrap_len - src_pre_wrap_len;
507                unsafe {
508                    self.copy(src, dst, src_pre_wrap_len);
509                    self.copy(WrappedIndex::zero(), dst.add(src_pre_wrap_len), delta);
510                    self.copy(
511                        WrappedIndex::from_arbitrary_number(delta),
512                        WrappedIndex::zero(),
513                        len - dst_pre_wrap_len,
514                    );
515                }
516            }
517            (true, true, true) => {
518                // src before dst, src wraps, dst wraps
519                //
520                //    . .         S . .
521                // 1 [A B C D _ E F G H]
522                // 2 [A A B D _ E F G H]
523                // 3 [H A B D _ E F G H]
524                // 4 [H A B D _ E F F G]
525                //    . . .         D .
526                //
527                debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
528                let delta = src_pre_wrap_len - dst_pre_wrap_len;
529                unsafe {
530                    self.copy(
531                        WrappedIndex::zero(),
532                        WrappedIndex::from_arbitrary_number(delta),
533                        len - src_pre_wrap_len,
534                    );
535                    self.copy(
536                        WrappedIndex::from_arbitrary_number(self.capacity() - delta),
537                        WrappedIndex::zero(),
538                        delta,
539                    );
540                    self.copy(src, dst, dst_pre_wrap_len);
541                }
542            }
543        }
544    }
545
546    /// Copies all values from `src` to `dst`, wrapping around if needed.
547    /// Assumes capacity is sufficient.
548    #[inline]
549    unsafe fn copy_slice(&mut self, dst: WrappedIndex, src: &[T]) {
550        debug_assert!(src.len() <= self.capacity());
551        let head_room = self.capacity() - dst.as_index();
552        if src.len() <= head_room {
553            unsafe {
554                ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst.as_index()), src.len());
555            }
556        } else {
557            let (left, right) = src.split_at(head_room);
558            unsafe {
559                ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst.as_index()), left.len());
560                ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
561            }
562        }
563    }
564
565    /// Copies all values from `src` to `dst` in reversed order, wrapping around if needed.
566    /// Assumes capacity is sufficient.
567    /// Equivalent to calling [`VecDeque::copy_slice`] with a [reversed](https://doc.rust-lang.org/std/primitive.slice.html#method.reverse) slice.
568    #[inline]
569    unsafe fn copy_slice_reversed(&mut self, dst: WrappedIndex, src: &[T]) {
570        /// # Safety
571        ///
572        /// See [`ptr::copy_nonoverlapping`].
573        unsafe fn copy_nonoverlapping_reversed<T>(src: *const T, dst: *mut T, count: usize) {
574            for i in 0..count {
575                unsafe { ptr::copy_nonoverlapping(src.add(count - 1 - i), dst.add(i), 1) };
576            }
577        }
578
579        debug_assert!(src.len() <= self.capacity());
580        let head_room = self.capacity() - dst.as_index();
581        if src.len() <= head_room {
582            unsafe {
583                copy_nonoverlapping_reversed(
584                    src.as_ptr(),
585                    self.ptr().add(dst.as_index()),
586                    src.len(),
587                );
588            }
589        } else {
590            let (left, right) = src.split_at(src.len() - head_room);
591            unsafe {
592                copy_nonoverlapping_reversed(
593                    right.as_ptr(),
594                    self.ptr().add(dst.as_index()),
595                    right.len(),
596                );
597                copy_nonoverlapping_reversed(left.as_ptr(), self.ptr(), left.len());
598            }
599        }
600    }
601
602    /// Writes all values from `iter` to `dst`.
603    ///
604    /// # Safety
605    ///
606    /// Assumes no wrapping around happens.
607    /// Assumes capacity is sufficient.
608    #[inline]
609    unsafe fn write_iter(
610        &mut self,
611        dst: WrappedIndex,
612        iter: impl Iterator<Item = T>,
613        written: &mut usize,
614    ) {
615        iter.enumerate().for_each(|(i, element)| unsafe {
616            self.buffer_write(dst.add(i), element);
617            *written += 1;
618        });
619    }
620
621    /// Writes all values from `iter` to `dst`, wrapping
622    /// at the end of the buffer and returns the number
623    /// of written values.
624    ///
625    /// # Safety
626    ///
627    /// Assumes that `iter` yields at most `len` items.
628    /// Assumes capacity is sufficient.
629    unsafe fn write_iter_wrapping(
630        &mut self,
631        dst: WrappedIndex,
632        mut iter: impl Iterator<Item = T>,
633        len: usize,
634    ) -> usize {
635        struct Guard<'a, T, A: Allocator> {
636            deque: &'a mut VecDeque<T, A>,
637            written: usize,
638        }
639
640        impl<'a, T, A: Allocator> Drop for Guard<'a, T, A> {
641            fn drop(&mut self) {
642                self.deque.len += self.written;
643            }
644        }
645
646        let head_room = self.capacity() - dst.as_index();
647
648        let mut guard = Guard { deque: self, written: 0 };
649
650        if head_room >= len {
651            unsafe { guard.deque.write_iter(dst, iter, &mut guard.written) };
652        } else {
653            unsafe {
654                guard.deque.write_iter(
655                    dst,
656                    ByRefSized(&mut iter).take(head_room),
657                    &mut guard.written,
658                );
659                guard.deque.write_iter(WrappedIndex::zero(), iter, &mut guard.written)
660            };
661        }
662
663        guard.written
664    }
665
666    /// Frobs the head and tail sections around to handle the fact that we
667    /// just reallocated. Unsafe because it trusts old_capacity.
668    #[inline]
669    unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
670        let new_capacity = self.capacity();
671        debug_assert!(new_capacity >= old_capacity);
672
673        // Move the shortest contiguous section of the ring buffer
674        //
675        // H := head
676        // L := last element (`self.to_physical_idx(self.len - 1)`)
677        //
678        //    H             L
679        //   [o o o o o o o o ]
680        //    H             L
681        // A [o o o o o o o o . . . . . . . . ]
682        //        L H
683        //   [o o o o o o o o ]
684        //          H             L
685        // B [. . . o o o o o o o o . . . . . ]
686        //              L H
687        //   [o o o o o o o o ]
688        //              L                 H
689        // C [o o o o o o . . . . . . . . o o ]
690
691        // can't use is_contiguous() because the capacity is already updated.
692        if self.head <= old_capacity - self.len {
693            // A
694            // Nop
695        } else {
696            let head_len = old_capacity - self.head.as_index();
697            let tail_len = self.len - head_len;
698            if head_len > tail_len && new_capacity - old_capacity >= tail_len {
699                // B
700                unsafe {
701                    self.copy_nonoverlapping(
702                        WrappedIndex::zero(),
703                        WrappedIndex::from_arbitrary_number(old_capacity),
704                        tail_len,
705                    );
706                }
707            } else {
708                // C
709                let new_head = WrappedIndex::from_arbitrary_number(new_capacity - head_len);
710                unsafe {
711                    // can't use copy_nonoverlapping here, because if e.g. head_len = 2
712                    // and new_capacity = old_capacity + 1, then the heads overlap.
713                    self.copy(self.head, new_head, head_len);
714                }
715                self.head = new_head;
716            }
717        }
718        debug_assert!(self.head < self.capacity() || self.capacity() == 0);
719    }
720
721    /// Creates an iterator which uses a closure to determine if an element in the range should be removed.
722    ///
723    /// If the closure returns `true`, the element is removed from the deque and yielded. If the closure
724    /// returns `false`, or panics, the element remains in the deque and will not be yielded.
725    ///
726    /// Only elements that fall in the provided range are considered for extraction, but any elements
727    /// after the range will still have to be moved if any element has been extracted.
728    ///
729    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
730    /// or the iteration short-circuits, then the remaining elements will be retained.
731    /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
732    /// or [`retain_mut`] with a negated predicate if you also do not need to restrict the range.
733    ///
734    /// [`retain_mut`]: VecDeque::retain_mut
735    ///
736    /// Using this method is equivalent to the following code:
737    ///
738    /// ```
739    /// #![feature(vec_deque_extract_if)]
740    /// # use std::collections::VecDeque;
741    /// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
742    /// # let mut deq: VecDeque<_> = (0..10).collect();
743    /// # let mut deq2 = deq.clone();
744    /// # let range = 1..5;
745    /// let mut i = range.start;
746    /// let end_items = deq.len() - range.end;
747    /// # let mut extracted = vec![];
748    ///
749    /// while i < deq.len() - end_items {
750    ///     if some_predicate(&mut deq[i]) {
751    ///         let val = deq.remove(i).unwrap();
752    ///         // your code here
753    /// #         extracted.push(val);
754    ///     } else {
755    ///         i += 1;
756    ///     }
757    /// }
758    ///
759    /// # let extracted2: Vec<_> = deq2.extract_if(range, some_predicate).collect();
760    /// # assert_eq!(deq, deq2);
761    /// # assert_eq!(extracted, extracted2);
762    /// ```
763    ///
764    /// But `extract_if` is easier to use. `extract_if` is also more efficient,
765    /// because it can backshift the elements of the array in bulk.
766    ///
767    /// The iterator also lets you mutate the value of each element in the
768    /// closure, regardless of whether you choose to keep or remove it.
769    ///
770    /// # Panics
771    ///
772    /// If `range` is out of bounds.
773    ///
774    /// # Examples
775    ///
776    /// Splitting a deque into even and odd values, reusing the original deque:
777    ///
778    /// ```
779    /// #![feature(vec_deque_extract_if)]
780    /// use std::collections::VecDeque;
781    ///
782    /// let mut numbers = VecDeque::from([1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
783    ///
784    /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<VecDeque<_>>();
785    /// let odds = numbers;
786    ///
787    /// assert_eq!(evens, VecDeque::from([2, 4, 6, 8, 14]));
788    /// assert_eq!(odds, VecDeque::from([1, 3, 5, 9, 11, 13, 15]));
789    /// ```
790    ///
791    /// Using the range argument to only process a part of the deque:
792    ///
793    /// ```
794    /// #![feature(vec_deque_extract_if)]
795    /// use std::collections::VecDeque;
796    ///
797    /// let mut items = VecDeque::from([0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]);
798    /// let ones = items.extract_if(7.., |x| *x == 1).collect::<VecDeque<_>>();
799    /// assert_eq!(items, VecDeque::from([0, 0, 0, 0, 0, 0, 0, 2, 2, 2]));
800    /// assert_eq!(ones.len(), 3);
801    /// ```
802    #[unstable(feature = "vec_deque_extract_if", issue = "147750")]
803    pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A>
804    where
805        F: FnMut(&mut T) -> bool,
806        R: RangeBounds<usize>,
807    {
808        ExtractIf::new(self, filter, range)
809    }
810}
811
812impl<T> VecDeque<T> {
813    /// Creates an empty deque.
814    ///
815    /// # Examples
816    ///
817    /// ```
818    /// use std::collections::VecDeque;
819    ///
820    /// let deque: VecDeque<u32> = VecDeque::new();
821    /// ```
822    #[inline]
823    #[stable(feature = "rust1", since = "1.0.0")]
824    #[rustc_const_stable(feature = "const_vec_deque_new", since = "1.68.0")]
825    #[must_use]
826    pub const fn new() -> VecDeque<T> {
827        // FIXME(const-hack): This should just be `VecDeque::new_in(Global)` once that hits stable.
828        VecDeque { head: WrappedIndex::zero(), len: 0, buf: RawVec::new() }
829    }
830
831    /// Creates an empty deque with space for at least `capacity` elements.
832    ///
833    /// # Examples
834    ///
835    /// ```
836    /// use std::collections::VecDeque;
837    ///
838    /// let deque: VecDeque<i32> = VecDeque::with_capacity(10);
839    /// ```
840    #[inline]
841    #[stable(feature = "rust1", since = "1.0.0")]
842    #[must_use]
843    pub fn with_capacity(capacity: usize) -> VecDeque<T> {
844        Self::with_capacity_in(capacity, Global)
845    }
846
847    /// Creates an empty deque with space for at least `capacity` elements.
848    ///
849    /// # Errors
850    ///
851    /// Returns an error if the capacity exceeds `isize::MAX` _bytes_,
852    /// or if the allocator reports allocation failure.
853    ///
854    /// # Examples
855    ///
856    /// ```
857    /// # #![feature(try_with_capacity)]
858    /// # #[allow(unused)]
859    /// # fn example() -> Result<(), std::collections::TryReserveError> {
860    /// use std::collections::VecDeque;
861    ///
862    /// let deque: VecDeque<u32> = VecDeque::try_with_capacity(10)?;
863    /// # Ok(()) }
864    /// ```
865    #[inline]
866    #[unstable(feature = "try_with_capacity", issue = "91913")]
867    pub fn try_with_capacity(capacity: usize) -> Result<VecDeque<T>, TryReserveError> {
868        Ok(VecDeque {
869            head: WrappedIndex::zero(),
870            len: 0,
871            buf: RawVec::try_with_capacity_in(capacity, Global)?,
872        })
873    }
874}
875
876impl<T, A: Allocator> VecDeque<T, A> {
877    /// Creates an empty deque.
878    ///
879    /// # Examples
880    ///
881    /// ```
882    /// # #![feature(allocator_api)]
883    ///
884    /// use std::collections::VecDeque;
885    /// use std::alloc::Global;
886    ///
887    /// let deque: VecDeque<i32> = VecDeque::new_in(Global);
888    /// ```
889    #[inline]
890    #[unstable(feature = "allocator_api", issue = "32838")]
891    pub const fn new_in(alloc: A) -> VecDeque<T, A> {
892        VecDeque { head: WrappedIndex::zero(), len: 0, buf: RawVec::new_in(alloc) }
893    }
894
895    /// Creates an empty deque with space for at least `capacity` elements.
896    ///
897    /// # Examples
898    ///
899    /// ```
900    /// # #![feature(allocator_api)]
901    ///
902    /// use std::collections::VecDeque;
903    /// use std::alloc::Global;
904    ///
905    /// let deque: VecDeque<i32> = VecDeque::with_capacity_in(10, Global);
906    /// ```
907    #[unstable(feature = "allocator_api", issue = "32838")]
908    pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
909        VecDeque {
910            head: WrappedIndex::zero(),
911            len: 0,
912            buf: RawVec::with_capacity_in(capacity, alloc),
913        }
914    }
915
916    /// Creates a `VecDeque` from a raw allocation, when the initialized
917    /// part of that allocation forms a *contiguous* subslice thereof.
918    ///
919    /// For use by `vec::IntoIter::into_vecdeque`
920    ///
921    /// # Safety
922    ///
923    /// All the usual requirements on the allocated memory like in
924    /// `Vec::from_raw_parts_in`, but takes a *range* of elements that are
925    /// initialized rather than only supporting `0..len`.  Requires that
926    /// `initialized.start` â‰Ī `initialized.end` â‰Ī `capacity`.
927    #[inline]
928    #[cfg(not(test))]
929    pub(crate) unsafe fn from_contiguous_raw_parts_in(
930        ptr: *mut T,
931        initialized: Range<usize>,
932        capacity: usize,
933        alloc: A,
934    ) -> Self {
935        debug_assert!(initialized.start <= initialized.end);
936        debug_assert!(initialized.end <= capacity);
937
938        // SAFETY: Our safety precondition guarantees the range length won't wrap,
939        // and that the allocation is valid for use in `RawVec`.
940        unsafe {
941            VecDeque {
942                head: WrappedIndex::from_arbitrary_number(initialized.start),
943                len: initialized.end.unchecked_sub(initialized.start),
944                buf: RawVec::from_raw_parts_in(ptr, capacity, alloc),
945            }
946        }
947    }
948
949    /// Provides a reference to the element at the given index.
950    ///
951    /// Element at index 0 is the front of the queue.
952    ///
953    /// # Examples
954    ///
955    /// ```
956    /// use std::collections::VecDeque;
957    ///
958    /// let mut buf = VecDeque::new();
959    /// buf.push_back(3);
960    /// buf.push_back(4);
961    /// buf.push_back(5);
962    /// buf.push_back(6);
963    /// assert_eq!(buf.get(1), Some(&4));
964    /// ```
965    #[stable(feature = "rust1", since = "1.0.0")]
966    pub fn get(&self, index: usize) -> Option<&T> {
967        if index < self.len {
968            let idx = self.to_wrapped_index(index);
969            unsafe { Some(&*self.ptr().add(idx.as_index())) }
970        } else {
971            None
972        }
973    }
974
975    /// Provides a mutable reference to the element at the given index.
976    ///
977    /// Element at index 0 is the front of the queue.
978    ///
979    /// # Examples
980    ///
981    /// ```
982    /// use std::collections::VecDeque;
983    ///
984    /// let mut buf = VecDeque::new();
985    /// buf.push_back(3);
986    /// buf.push_back(4);
987    /// buf.push_back(5);
988    /// buf.push_back(6);
989    /// assert_eq!(buf[1], 4);
990    /// if let Some(elem) = buf.get_mut(1) {
991    ///     *elem = 7;
992    /// }
993    /// assert_eq!(buf[1], 7);
994    /// ```
995    #[stable(feature = "rust1", since = "1.0.0")]
996    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
997        if index < self.len {
998            let idx = self.to_wrapped_index(index);
999            unsafe { Some(&mut *self.ptr().add(idx.as_index())) }
1000        } else {
1001            None
1002        }
1003    }
1004
1005    /// Swaps elements at indices `i` and `j`.
1006    ///
1007    /// `i` and `j` may be equal.
1008    ///
1009    /// Element at index 0 is the front of the queue.
1010    ///
1011    /// # Panics
1012    ///
1013    /// Panics if either index is out of bounds.
1014    ///
1015    /// # Examples
1016    ///
1017    /// ```
1018    /// use std::collections::VecDeque;
1019    ///
1020    /// let mut buf = VecDeque::new();
1021    /// buf.push_back(3);
1022    /// buf.push_back(4);
1023    /// buf.push_back(5);
1024    /// assert_eq!(buf, [3, 4, 5]);
1025    /// buf.swap(0, 2);
1026    /// assert_eq!(buf, [5, 4, 3]);
1027    /// ```
1028    #[stable(feature = "rust1", since = "1.0.0")]
1029    pub fn swap(&mut self, i: usize, j: usize) {
1030        assert!(i < self.len());
1031        assert!(j < self.len());
1032        let ri = self.to_wrapped_index(i);
1033        let rj = self.to_wrapped_index(j);
1034        unsafe { ptr::swap(self.ptr().add(ri.as_index()), self.ptr().add(rj.as_index())) }
1035    }
1036
1037    /// Returns the number of elements the deque can hold without
1038    /// reallocating.
1039    ///
1040    /// # Examples
1041    ///
1042    /// ```
1043    /// use std::collections::VecDeque;
1044    ///
1045    /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
1046    /// assert!(buf.capacity() >= 10);
1047    /// ```
1048    #[inline]
1049    #[stable(feature = "rust1", since = "1.0.0")]
1050    pub fn capacity(&self) -> usize {
1051        if T::IS_ZST { usize::MAX } else { self.buf.capacity() }
1052    }
1053
1054    /// Reserves the minimum capacity for at least `additional` more elements to be inserted in the
1055    /// given deque. Does nothing if the capacity is already sufficient.
1056    ///
1057    /// Note that the allocator may give the collection more space than it requests. Therefore
1058    /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
1059    /// insertions are expected.
1060    ///
1061    /// # Panics
1062    ///
1063    /// Panics if the new capacity overflows `usize`.
1064    ///
1065    /// # Examples
1066    ///
1067    /// ```
1068    /// use std::collections::VecDeque;
1069    ///
1070    /// let mut buf: VecDeque<i32> = [1].into();
1071    /// buf.reserve_exact(10);
1072    /// assert!(buf.capacity() >= 11);
1073    /// ```
1074    ///
1075    /// [`reserve`]: VecDeque::reserve
1076    #[stable(feature = "rust1", since = "1.0.0")]
1077    pub fn reserve_exact(&mut self, additional: usize) {
1078        let new_cap = self.len.checked_add(additional).expect("capacity overflow");
1079        let old_cap = self.capacity();
1080
1081        if new_cap > old_cap {
1082            self.buf.reserve_exact(self.len, additional);
1083            unsafe {
1084                self.handle_capacity_increase(old_cap);
1085            }
1086        }
1087    }
1088
1089    /// Reserves capacity for at least `additional` more elements to be inserted in the given
1090    /// deque. The collection may reserve more space to speculatively avoid frequent reallocations.
1091    ///
1092    /// # Panics
1093    ///
1094    /// Panics if the new capacity overflows `usize`.
1095    ///
1096    /// # Examples
1097    ///
1098    /// ```
1099    /// use std::collections::VecDeque;
1100    ///
1101    /// let mut buf: VecDeque<i32> = [1].into();
1102    /// buf.reserve(10);
1103    /// assert!(buf.capacity() >= 11);
1104    /// ```
1105    #[stable(feature = "rust1", since = "1.0.0")]
1106    #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_reserve")]
1107    pub fn reserve(&mut self, additional: usize) {
1108        let new_cap = self.len.checked_add(additional).expect("capacity overflow");
1109        let old_cap = self.capacity();
1110
1111        if new_cap > old_cap {
1112            // we don't need to reserve_exact(), as the size doesn't have
1113            // to be a power of 2.
1114            self.buf.reserve(self.len, additional);
1115            unsafe {
1116                self.handle_capacity_increase(old_cap);
1117            }
1118        }
1119    }
1120
1121    /// Tries to reserve the minimum capacity for at least `additional` more elements to
1122    /// be inserted in the given deque. After calling `try_reserve_exact`,
1123    /// capacity will be greater than or equal to `self.len() + additional` if
1124    /// it returns `Ok(())`. Does nothing if the capacity is already sufficient.
1125    ///
1126    /// Note that the allocator may give the collection more space than it
1127    /// requests. Therefore, capacity can not be relied upon to be precisely
1128    /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1129    ///
1130    /// [`try_reserve`]: VecDeque::try_reserve
1131    ///
1132    /// # Errors
1133    ///
1134    /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
1135    /// is returned.
1136    ///
1137    /// # Examples
1138    ///
1139    /// ```
1140    /// use std::collections::TryReserveError;
1141    /// use std::collections::VecDeque;
1142    ///
1143    /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
1144    ///     let mut output = VecDeque::new();
1145    ///
1146    ///     // Pre-reserve the memory, exiting if we can't
1147    ///     output.try_reserve_exact(data.len())?;
1148    ///
1149    ///     // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
1150    ///     output.extend(data.iter().map(|&val| {
1151    ///         val * 2 + 5 // very complicated
1152    ///     }));
1153    ///
1154    ///     Ok(output)
1155    /// }
1156    /// # process_data(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1157    /// ```
1158    #[stable(feature = "try_reserve", since = "1.57.0")]
1159    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1160        let new_cap =
1161            self.len.checked_add(additional).ok_or(TryReserveErrorKind::CapacityOverflow)?;
1162        let old_cap = self.capacity();
1163
1164        if new_cap > old_cap {
1165            self.buf.try_reserve_exact(self.len, additional)?;
1166            unsafe {
1167                self.handle_capacity_increase(old_cap);
1168            }
1169        }
1170        Ok(())
1171    }
1172
1173    /// Tries to reserve capacity for at least `additional` more elements to be inserted
1174    /// in the given deque. The collection may reserve more space to speculatively avoid
1175    /// frequent reallocations. After calling `try_reserve`, capacity will be
1176    /// greater than or equal to `self.len() + additional` if it returns
1177    /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1178    /// preserves the contents even if an error occurs.
1179    ///
1180    /// # Errors
1181    ///
1182    /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
1183    /// is returned.
1184    ///
1185    /// # Examples
1186    ///
1187    /// ```
1188    /// use std::collections::TryReserveError;
1189    /// use std::collections::VecDeque;
1190    ///
1191    /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
1192    ///     let mut output = VecDeque::new();
1193    ///
1194    ///     // Pre-reserve the memory, exiting if we can't
1195    ///     output.try_reserve(data.len())?;
1196    ///
1197    ///     // Now we know this can't OOM in the middle of our complex work
1198    ///     output.extend(data.iter().map(|&val| {
1199    ///         val * 2 + 5 // very complicated
1200    ///     }));
1201    ///
1202    ///     Ok(output)
1203    /// }
1204    /// # process_data(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1205    /// ```
1206    #[stable(feature = "try_reserve", since = "1.57.0")]
1207    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1208        let new_cap =
1209            self.len.checked_add(additional).ok_or(TryReserveErrorKind::CapacityOverflow)?;
1210        let old_cap = self.capacity();
1211
1212        if new_cap > old_cap {
1213            self.buf.try_reserve(self.len, additional)?;
1214            unsafe {
1215                self.handle_capacity_increase(old_cap);
1216            }
1217        }
1218        Ok(())
1219    }
1220
1221    /// Shrinks the capacity of the deque as much as possible.
1222    ///
1223    /// It will drop down as close as possible to the length but the allocator may still inform the
1224    /// deque that there is space for a few more elements.
1225    ///
1226    /// # Examples
1227    ///
1228    /// ```
1229    /// use std::collections::VecDeque;
1230    ///
1231    /// let mut buf = VecDeque::with_capacity(15);
1232    /// buf.extend(0..4);
1233    /// assert_eq!(buf.capacity(), 15);
1234    /// buf.shrink_to_fit();
1235    /// assert!(buf.capacity() >= 4);
1236    /// ```
1237    #[stable(feature = "deque_extras_15", since = "1.5.0")]
1238    pub fn shrink_to_fit(&mut self) {
1239        self.shrink_to(0);
1240    }
1241
1242    /// Shrinks the capacity of the deque with a lower bound.
1243    ///
1244    /// The capacity will remain at least as large as both the length
1245    /// and the supplied value.
1246    ///
1247    /// If the current capacity is less than the lower limit, this is a no-op.
1248    ///
1249    /// # Examples
1250    ///
1251    /// ```
1252    /// use std::collections::VecDeque;
1253    ///
1254    /// let mut buf = VecDeque::with_capacity(15);
1255    /// buf.extend(0..4);
1256    /// assert_eq!(buf.capacity(), 15);
1257    /// buf.shrink_to(6);
1258    /// assert!(buf.capacity() >= 6);
1259    /// buf.shrink_to(0);
1260    /// assert!(buf.capacity() >= 4);
1261    /// ```
1262    #[stable(feature = "shrink_to", since = "1.56.0")]
1263    pub fn shrink_to(&mut self, min_capacity: usize) {
1264        let target_cap = min_capacity.max(self.len);
1265
1266        // never shrink ZSTs
1267        if T::IS_ZST || self.capacity() <= target_cap {
1268            return;
1269        }
1270
1271        // There are three cases of interest:
1272        //   All elements are out of desired bounds
1273        //   Elements are contiguous, and tail is out of desired bounds
1274        //   Elements are discontiguous
1275        //
1276        // At all other times, element positions are unaffected.
1277
1278        // `head` and `len` are at most `isize::MAX` and `target_cap < self.capacity()`, so nothing can
1279        // overflow.
1280        let tail_outside = (target_cap + 1..=self.capacity()).contains(&(self.head + self.len));
1281        // Used in the drop guard below.
1282        let old_head = self.head;
1283
1284        if self.len == 0 {
1285            self.head = WrappedIndex::zero();
1286        } else if self.head.as_index() >= target_cap && tail_outside {
1287            // Head and tail are both out of bounds, so copy all of them to the front.
1288            //
1289            //  H := head
1290            //  L := last element
1291            //                    H           L
1292            //   [. . . . . . . . o o o o o o o . ]
1293            //    H           L
1294            //   [o o o o o o o . ]
1295            unsafe {
1296                // nonoverlapping because `self.head >= target_cap >= self.len`.
1297                self.copy_nonoverlapping(self.head, WrappedIndex::zero(), self.len);
1298            }
1299            self.head = WrappedIndex::zero();
1300        } else if self.head < target_cap && tail_outside {
1301            // Head is in bounds, tail is out of bounds.
1302            // Copy the overflowing part to the beginning of the
1303            // buffer. This won't overlap because `target_cap >= self.len`.
1304            //
1305            //  H := head
1306            //  L := last element
1307            //          H           L
1308            //   [. . . o o o o o o o . . . . . . ]
1309            //      L   H
1310            //   [o o . o o o o o ]
1311            let len = self.head + self.len - target_cap;
1312            // Safety: head is < target_cap, so the index is wrapped
1313            unsafe {
1314                self.copy_nonoverlapping(
1315                    WrappedIndex::from_arbitrary_number(target_cap),
1316                    WrappedIndex::zero(),
1317                    len,
1318                );
1319            }
1320        } else if !self.is_contiguous() {
1321            // The head slice is at least partially out of bounds, tail is in bounds.
1322            // Copy the head backwards so it lines up with the target capacity.
1323            // This won't overlap because `target_cap >= self.len`.
1324            //
1325            //  H := head
1326            //  L := last element
1327            //            L                   H
1328            //   [o o o o o . . . . . . . . . o o ]
1329            //            L   H
1330            //   [o o o o o . o o ]
1331            let head_len = self.capacity() - self.head.as_index();
1332
1333            // head_len is at least one, so new_head will be < target_cap
1334            let new_head = WrappedIndex::from_arbitrary_number(target_cap - head_len);
1335            unsafe {
1336                // can't use `copy_nonoverlapping()` here because the new and old
1337                // regions for the head might overlap.
1338                self.copy(self.head, new_head, head_len);
1339            }
1340            self.head = new_head;
1341        }
1342
1343        struct Guard<'a, T, A: Allocator> {
1344            deque: &'a mut VecDeque<T, A>,
1345            old_head: WrappedIndex,
1346            target_cap: usize,
1347        }
1348
1349        impl<T, A: Allocator> Drop for Guard<'_, T, A> {
1350            #[cold]
1351            fn drop(&mut self) {
1352                unsafe {
1353                    // SAFETY: This is only called if `buf.shrink_to_fit` unwinds,
1354                    // which is the only time it's safe to call `abort_shrink`.
1355                    self.deque.abort_shrink(self.old_head, self.target_cap)
1356                }
1357            }
1358        }
1359
1360        let guard = Guard { deque: self, old_head, target_cap };
1361
1362        guard.deque.buf.shrink_to_fit(target_cap);
1363
1364        // Don't drop the guard if we didn't unwind.
1365        mem::forget(guard);
1366
1367        debug_assert!(self.head < self.capacity() || self.capacity() == 0);
1368        debug_assert!(self.len <= self.capacity());
1369    }
1370
1371    /// Reverts the deque back into a consistent state in case `shrink_to` failed.
1372    /// This is necessary to prevent UB if the backing allocator returns an error
1373    /// from `shrink` and `handle_alloc_error` subsequently unwinds (see #123369).
1374    ///
1375    /// `old_head` refers to the head index before `shrink_to` was called. `target_cap`
1376    /// is the capacity that it was trying to shrink to.
1377    unsafe fn abort_shrink(&mut self, old_head: WrappedIndex, target_cap: usize) {
1378        // Moral equivalent of self.head + self.len <= target_cap. Won't overflow
1379        // because `self.len <= target_cap`.
1380        if self.head <= target_cap - self.len {
1381            // The deque's buffer is contiguous, so no need to copy anything around.
1382            return;
1383        }
1384
1385        // `shrink_to` already copied the head to fit into the new capacity, so this won't overflow.
1386        let head_len = target_cap - self.head.as_index();
1387        // `self.head > target_cap - self.len` => `self.len > target_cap - self.head =: head_len` so this must be positive.
1388        let tail_len = self.len - head_len;
1389
1390        if tail_len <= cmp::min(head_len, self.capacity() - target_cap) {
1391            // There's enough spare capacity to copy the tail to the back (because `tail_len < self.capacity() - target_cap`),
1392            // and copying the tail should be cheaper than copying the head (because `tail_len <= head_len`).
1393
1394            unsafe {
1395                // The old tail and the new tail can't overlap because the head slice lies between them. The
1396                // head slice ends at `target_cap`, so that's where we copy to.
1397                self.copy_nonoverlapping(
1398                    WrappedIndex::zero(),
1399                    WrappedIndex::from_arbitrary_number(target_cap),
1400                    tail_len,
1401                );
1402            }
1403        } else {
1404            // Either there's not enough spare capacity to make the deque contiguous, or the head is shorter than the tail
1405            // (and therefore hopefully cheaper to copy).
1406            unsafe {
1407                // The old and the new head slice can overlap, so we can't use `copy_nonoverlapping` here.
1408                self.copy(self.head, old_head, head_len);
1409                self.head = old_head;
1410            }
1411        }
1412    }
1413
1414    /// Shortens the deque, keeping the first `len` elements and dropping
1415    /// the rest.
1416    ///
1417    /// If `len` is greater or equal to the deque's current length, this has
1418    /// no effect.
1419    ///
1420    /// # Examples
1421    ///
1422    /// ```
1423    /// use std::collections::VecDeque;
1424    ///
1425    /// let mut buf = VecDeque::new();
1426    /// buf.push_back(5);
1427    /// buf.push_back(10);
1428    /// buf.push_back(15);
1429    /// assert_eq!(buf, [5, 10, 15]);
1430    /// buf.truncate(1);
1431    /// assert_eq!(buf, [5]);
1432    /// ```
1433    #[doc(alias = "retain_front")]
1434    #[stable(feature = "deque_extras", since = "1.16.0")]
1435    pub fn truncate(&mut self, len: usize) {
1436        // Safe because:
1437        //
1438        // * Any slice passed to `drop_in_place` is valid; the second case has
1439        //   `len <= front.len()` and returning on `len > self.len()` ensures
1440        //   `begin <= back.len()` in the first case
1441        // * The head of the VecDeque is moved before calling `drop_in_place`,
1442        //   so no value is dropped twice if `drop_in_place` panics
1443        unsafe {
1444            if len >= self.len {
1445                return;
1446            }
1447
1448            let (front, back) = self.as_mut_slices();
1449            if len > front.len() {
1450                let begin = len - front.len();
1451                let drop_back = back.get_unchecked_mut(begin..) as *mut _;
1452                self.len = len;
1453                ptr::drop_in_place(drop_back);
1454            } else {
1455                let drop_back = back as *mut _;
1456                let drop_front = front.get_unchecked_mut(len..) as *mut _;
1457                self.len = len;
1458
1459                // Make sure the second half is dropped even when a destructor
1460                // in the first one panics.
1461                let _back_dropper = Dropper(&mut *drop_back);
1462                ptr::drop_in_place(drop_front);
1463            }
1464        }
1465    }
1466
1467    /// Shortens the deque, keeping the last `len` elements and dropping
1468    /// the rest.
1469    ///
1470    /// If `len` is greater or equal to the deque's current length, this has
1471    /// no effect.
1472    ///
1473    /// # Examples
1474    ///
1475    /// ```
1476    /// use std::collections::VecDeque;
1477    ///
1478    /// let mut buf = VecDeque::new();
1479    /// buf.push_front(5);
1480    /// buf.push_front(10);
1481    /// buf.push_front(15);
1482    /// assert_eq!(buf, [15, 10, 5]);
1483    /// assert_eq!(buf.as_slices(), (&[15, 10, 5][..], &[][..]));
1484    /// buf.retain_back(1);
1485    /// assert_eq!(buf.as_slices(), (&[5][..], &[][..]));
1486    /// ```
1487    #[doc(alias = "truncate_front")]
1488    #[stable(feature = "vec_deque_truncate_front", since = "1.99.0")]
1489    pub fn retain_back(&mut self, len: usize) {
1490        unsafe {
1491            if len >= self.len {
1492                // No action is taken
1493                return;
1494            }
1495
1496            let (front, back) = self.as_mut_slices();
1497            if len > back.len() {
1498                // The 'back' slice remains unchanged.
1499                // front.len() + back.len() == self.len, so 'end' is non-negative
1500                // and end < front.len()
1501                let end = front.len() - (len - back.len());
1502                let drop_front = front.get_unchecked_mut(..end) as *mut _;
1503                self.head = self.head.add(end);
1504                self.len = len;
1505                ptr::drop_in_place(drop_front);
1506            } else {
1507                let drop_front = front as *mut _;
1508                // 'end' is non-negative by the condition above
1509                let end = back.len() - len;
1510                let drop_back = back.get_unchecked_mut(..end) as *mut _;
1511                self.head = self.to_wrapped_index(self.len - len);
1512                self.len = len;
1513
1514                // Make sure the second half is dropped even when a destructor
1515                // in the first one panics.
1516                let _back_dropper = Dropper(&mut *drop_back);
1517                ptr::drop_in_place(drop_front);
1518            }
1519        }
1520    }
1521
1522    /// Shortens the deque to the elements within `range`, dropping the rest.
1523    ///
1524    /// # Panics
1525    ///
1526    /// Panics if the starting point is greater than the end point or if
1527    /// the end point is greater than the length of the deque.
1528    ///
1529    /// # Examples
1530    ///
1531    /// ```
1532    /// # #![feature(vec_deque_retain_range)]
1533    /// use std::collections::VecDeque;
1534    ///
1535    /// let mut buf: VecDeque<_> = (0..6).collect();
1536    /// buf.truncate_to_range(2..5);
1537    /// assert_eq!(buf, [2, 3, 4]);
1538    /// ```
1539    #[unstable(feature = "vec_deque_retain_range", issue = "156215")]
1540    pub fn truncate_to_range<R>(&mut self, range: R)
1541    where
1542        R: RangeBounds<usize>,
1543    {
1544        let Range { start, end } = slice::range(range, ..self.len);
1545
1546        if start == 0 && end == self.len {
1547            return;
1548        } else if start == end {
1549            self.clear();
1550            return;
1551        } else if start == 0 {
1552            self.truncate(end);
1553            return;
1554        } else if end == self.len {
1555            self.retain_back(self.len - start);
1556            return;
1557        }
1558
1559        // Both the dropped prefix [0..start) and the dropped suffix [end..self.len) are
1560        // non-empty.  Plan up to three physical slices to drop, then update head/len, then
1561        // drop.  Only one of the dropped prefix or dropped suffix can cross between slices.
1562        let (front, back) = self.as_mut_slices();
1563        let flen = front.len();
1564        let blen = back.len();
1565        let fptr = front.as_mut_ptr();
1566        let bptr = back.as_mut_ptr();
1567
1568        unsafe {
1569            let (drop_a, drop_b, drop_c) = if end <= flen {
1570                // Kept range lies in `front`.  The dropped suffix is the rest of `front`
1571                // plus all of `back`.
1572                let pre = ptr::slice_from_raw_parts_mut(fptr, start);
1573                let mid = ptr::slice_from_raw_parts_mut(fptr.add(end), flen - end);
1574                (pre, mid, Some(back as *mut [T]))
1575            } else if start >= flen {
1576                // Kept range lies in `back`.  The dropped prefix is all of `front` plus the
1577                // start of `back`.
1578                let mid = ptr::slice_from_raw_parts_mut(bptr, start - flen);
1579                let suf = ptr::slice_from_raw_parts_mut(bptr.add(end - flen), blen - (end - flen));
1580                (front as *mut [T], mid, Some(suf))
1581            } else {
1582                // Kept range straddles the boundary.  The dropped prefix is in `front`, the
1583                // dropped suffix is in `back`.  Only two regions to drop.
1584                let pre = ptr::slice_from_raw_parts_mut(fptr, start);
1585                let suf = ptr::slice_from_raw_parts_mut(bptr.add(end - flen), blen - (end - flen));
1586                (pre, suf, None)
1587            };
1588
1589            // Set these once only, then drop.  If we called truncate + retain_back, a panic in
1590            // a destructor could leave this truncation in a half completed state.
1591            self.head = self.to_wrapped_index(start);
1592            self.len = end - start;
1593
1594            match drop_c {
1595                Some(c) => {
1596                    let _g_a = Dropper(&mut *drop_a);
1597                    let _g_b = Dropper(&mut *drop_b);
1598                    ptr::drop_in_place(c);
1599                }
1600                None => {
1601                    let _g_a = Dropper(&mut *drop_a);
1602                    ptr::drop_in_place(drop_b);
1603                }
1604            }
1605        }
1606    }
1607
1608    /// Returns a reference to the underlying allocator.
1609    #[unstable(feature = "allocator_api", issue = "32838")]
1610    #[inline]
1611    pub fn allocator(&self) -> &A {
1612        self.buf.allocator()
1613    }
1614
1615    /// Returns a front-to-back iterator.
1616    ///
1617    /// # Examples
1618    ///
1619    /// ```
1620    /// use std::collections::VecDeque;
1621    ///
1622    /// let mut buf = VecDeque::new();
1623    /// buf.push_back(5);
1624    /// buf.push_back(3);
1625    /// buf.push_back(4);
1626    /// let b: &[_] = &[&5, &3, &4];
1627    /// let c: Vec<&i32> = buf.iter().collect();
1628    /// assert_eq!(&c[..], b);
1629    /// ```
1630    #[stable(feature = "rust1", since = "1.0.0")]
1631    #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_iter")]
1632    pub fn iter(&self) -> Iter<'_, T> {
1633        let (a, b) = self.as_slices();
1634        Iter::new(a.iter(), b.iter())
1635    }
1636
1637    /// Returns a front-to-back iterator that returns mutable references.
1638    ///
1639    /// # Examples
1640    ///
1641    /// ```
1642    /// use std::collections::VecDeque;
1643    ///
1644    /// let mut buf = VecDeque::new();
1645    /// buf.push_back(5);
1646    /// buf.push_back(3);
1647    /// buf.push_back(4);
1648    /// for num in buf.iter_mut() {
1649    ///     *num = *num - 2;
1650    /// }
1651    /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1652    /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1653    /// ```
1654    #[stable(feature = "rust1", since = "1.0.0")]
1655    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1656        let (a, b) = self.as_mut_slices();
1657        IterMut::new(a.iter_mut(), b.iter_mut())
1658    }
1659
1660    /// Returns a pair of slices which contain, in order, the contents of the
1661    /// deque.
1662    ///
1663    /// If [`make_contiguous`] was previously called, all elements of the
1664    /// deque will be in the first slice and the second slice will be empty.
1665    /// Otherwise, the exact split point depends on implementation details
1666    /// and is not guaranteed.
1667    ///
1668    /// [`make_contiguous`]: VecDeque::make_contiguous
1669    ///
1670    /// # Examples
1671    ///
1672    /// ```
1673    /// use std::collections::VecDeque;
1674    ///
1675    /// let mut deque = VecDeque::new();
1676    ///
1677    /// deque.push_back(0);
1678    /// deque.push_back(1);
1679    /// deque.push_back(2);
1680    ///
1681    /// let expected = [0, 1, 2];
1682    /// let (front, back) = deque.as_slices();
1683    /// assert_eq!(&expected[..front.len()], front);
1684    /// assert_eq!(&expected[front.len()..], back);
1685    ///
1686    /// deque.push_front(10);
1687    /// deque.push_front(9);
1688    ///
1689    /// let expected = [9, 10, 0, 1, 2];
1690    /// let (front, back) = deque.as_slices();
1691    /// assert_eq!(&expected[..front.len()], front);
1692    /// assert_eq!(&expected[front.len()..], back);
1693    /// ```
1694    #[inline]
1695    #[stable(feature = "deque_extras_15", since = "1.5.0")]
1696    pub fn as_slices(&self) -> (&[T], &[T]) {
1697        let (a_range, b_range) = self.slice_ranges(.., self.len);
1698        // SAFETY: `slice_ranges` always returns valid ranges into
1699        // the physical buffer.
1700        unsafe { (&*self.buffer_range(a_range), &*self.buffer_range(b_range)) }
1701    }
1702
1703    /// Returns a pair of slices which contain, in order, the contents of the
1704    /// deque.
1705    ///
1706    /// If [`make_contiguous`] was previously called, all elements of the
1707    /// deque will be in the first slice and the second slice will be empty.
1708    /// Otherwise, the exact split point depends on implementation details
1709    /// and is not guaranteed.
1710    ///
1711    /// [`make_contiguous`]: VecDeque::make_contiguous
1712    ///
1713    /// # Examples
1714    ///
1715    /// ```
1716    /// use std::collections::VecDeque;
1717    ///
1718    /// let mut deque = VecDeque::new();
1719    ///
1720    /// deque.push_back(0);
1721    /// deque.push_back(1);
1722    ///
1723    /// deque.push_front(10);
1724    /// deque.push_front(9);
1725    ///
1726    /// // Since the split point is not guaranteed, we may need to update
1727    /// // either slice.
1728    /// let mut update_nth = |index: usize, val: u32| {
1729    ///     let (front, back) = deque.as_mut_slices();
1730    ///     if index > front.len() - 1 {
1731    ///         back[index - front.len()] = val;
1732    ///     } else {
1733    ///         front[index] = val;
1734    ///     }
1735    /// };
1736    ///
1737    /// update_nth(0, 42);
1738    /// update_nth(2, 24);
1739    ///
1740    /// let v: Vec<_> = deque.into();
1741    /// assert_eq!(v, [42, 10, 24, 1]);
1742    /// ```
1743    #[inline]
1744    #[stable(feature = "deque_extras_15", since = "1.5.0")]
1745    pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1746        let (a_range, b_range) = self.slice_ranges(.., self.len);
1747        // SAFETY: `slice_ranges` always returns valid ranges into
1748        // the physical buffer.
1749        unsafe { (&mut *self.buffer_range(a_range), &mut *self.buffer_range(b_range)) }
1750    }
1751
1752    /// Returns the number of elements in the deque.
1753    ///
1754    /// # Examples
1755    ///
1756    /// ```
1757    /// use std::collections::VecDeque;
1758    ///
1759    /// let mut deque = VecDeque::new();
1760    /// assert_eq!(deque.len(), 0);
1761    /// deque.push_back(1);
1762    /// assert_eq!(deque.len(), 1);
1763    /// ```
1764    #[stable(feature = "rust1", since = "1.0.0")]
1765    #[rustc_confusables("length", "size")]
1766    pub fn len(&self) -> usize {
1767        self.len
1768    }
1769
1770    /// Returns `true` if the deque is empty.
1771    ///
1772    /// # Examples
1773    ///
1774    /// ```
1775    /// use std::collections::VecDeque;
1776    ///
1777    /// let mut deque = VecDeque::new();
1778    /// assert!(deque.is_empty());
1779    /// deque.push_front(1);
1780    /// assert!(!deque.is_empty());
1781    /// ```
1782    #[stable(feature = "rust1", since = "1.0.0")]
1783    pub fn is_empty(&self) -> bool {
1784        self.len == 0
1785    }
1786
1787    /// Given a range into the logical buffer of the deque, this function
1788    /// return two ranges into the physical buffer that correspond to
1789    /// the given range. The `len` parameter should usually just be `self.len`;
1790    /// the reason it's passed explicitly is that if the deque is wrapped in
1791    /// a `Drain`, then `self.len` is not actually the length of the deque.
1792    ///
1793    /// # Safety
1794    ///
1795    /// This function is always safe to call. For the resulting ranges to be valid
1796    /// ranges into the physical buffer, the caller must ensure that the result of
1797    /// calling `slice::range(range, ..len)` represents a valid range into the
1798    /// logical buffer, and that all elements in that range are initialized.
1799    fn slice_ranges<R>(&self, range: R, len: usize) -> (Range<usize>, Range<usize>)
1800    where
1801        R: RangeBounds<usize>,
1802    {
1803        let Range { start, end } = slice::range(range, ..len);
1804        let len = end - start;
1805
1806        if len == 0 {
1807            (0..0, 0..0)
1808        } else {
1809            // `slice::range` guarantees that `start <= end <= len`.
1810            // because `len != 0`, we know that `start < end`, so `start < len`
1811            // and the indexing is valid.
1812            let wrapped_start = self.to_wrapped_index(start);
1813
1814            // this subtraction can never overflow because `wrapped_start` is
1815            // at most `self.capacity()` (and if `self.capacity != 0`, then `wrapped_start` is strictly less
1816            // than `self.capacity`).
1817            let head_len = self.capacity() - wrapped_start.as_index();
1818
1819            if head_len >= len {
1820                // we know that `len + wrapped_start <= self.capacity <= usize::MAX`, so this addition can't overflow
1821                (wrapped_start.as_index()..wrapped_start + len, 0..0)
1822            } else {
1823                // can't overflow because of the if condition
1824                let tail_len = len - head_len;
1825                (wrapped_start.as_index()..self.capacity(), 0..tail_len)
1826            }
1827        }
1828    }
1829
1830    /// Creates an iterator that covers the specified range in the deque.
1831    ///
1832    /// # Panics
1833    ///
1834    /// Panics if the range has `start_bound > end_bound`, or, if the range is
1835    /// bounded on either end and past the length of the deque.
1836    ///
1837    /// # Examples
1838    ///
1839    /// ```
1840    /// use std::collections::VecDeque;
1841    ///
1842    /// let deque: VecDeque<_> = [1, 2, 3].into();
1843    /// let range = deque.range(2..).copied().collect::<VecDeque<_>>();
1844    /// assert_eq!(range, [3]);
1845    ///
1846    /// // A full range covers all contents
1847    /// let all = deque.range(..);
1848    /// assert_eq!(all.len(), 3);
1849    /// ```
1850    #[inline]
1851    #[stable(feature = "deque_range", since = "1.51.0")]
1852    pub fn range<R>(&self, range: R) -> Iter<'_, T>
1853    where
1854        R: RangeBounds<usize>,
1855    {
1856        let (a_range, b_range) = self.slice_ranges(range, self.len);
1857        // SAFETY: The ranges returned by `slice_ranges`
1858        // are valid ranges into the physical buffer, so
1859        // it's ok to pass them to `buffer_range` and
1860        // dereference the result.
1861        let a = unsafe { &*self.buffer_range(a_range) };
1862        let b = unsafe { &*self.buffer_range(b_range) };
1863        Iter::new(a.iter(), b.iter())
1864    }
1865
1866    /// Creates an iterator that covers the specified mutable range in the deque.
1867    ///
1868    /// # Panics
1869    ///
1870    /// Panics if the range has `start_bound > end_bound`, or, if the range is
1871    /// bounded on either end and past the length of the deque.
1872    ///
1873    /// # Examples
1874    ///
1875    /// ```
1876    /// use std::collections::VecDeque;
1877    ///
1878    /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1879    /// for v in deque.range_mut(2..) {
1880    ///   *v *= 2;
1881    /// }
1882    /// assert_eq!(deque, [1, 2, 6]);
1883    ///
1884    /// // A full range covers all contents
1885    /// for v in deque.range_mut(..) {
1886    ///   *v *= 2;
1887    /// }
1888    /// assert_eq!(deque, [2, 4, 12]);
1889    /// ```
1890    #[inline]
1891    #[stable(feature = "deque_range", since = "1.51.0")]
1892    pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1893    where
1894        R: RangeBounds<usize>,
1895    {
1896        let (a_range, b_range) = self.slice_ranges(range, self.len);
1897        // SAFETY: The ranges returned by `slice_ranges`
1898        // are valid ranges into the physical buffer, so
1899        // it's ok to pass them to `buffer_range` and
1900        // dereference the result.
1901        let a = unsafe { &mut *self.buffer_range(a_range) };
1902        let b = unsafe { &mut *self.buffer_range(b_range) };
1903        IterMut::new(a.iter_mut(), b.iter_mut())
1904    }
1905
1906    /// Removes the specified range from the deque in bulk, returning all
1907    /// removed elements as an iterator. If the iterator is dropped before
1908    /// being fully consumed, it drops the remaining removed elements.
1909    ///
1910    /// The returned iterator keeps a mutable borrow on the queue to optimize
1911    /// its implementation.
1912    ///
1913    ///
1914    /// # Panics
1915    ///
1916    /// Panics if the range has `start_bound > end_bound`, or, if the range is
1917    /// bounded on either end and past the length of the deque.
1918    ///
1919    /// # Leaking
1920    ///
1921    /// If the returned iterator goes out of scope without being dropped (due to
1922    /// [`mem::forget`], for example), the deque may have lost and leaked
1923    /// elements arbitrarily, including elements outside the range.
1924    ///
1925    /// # Examples
1926    ///
1927    /// ```
1928    /// use std::collections::VecDeque;
1929    ///
1930    /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1931    /// let drained = deque.drain(2..).collect::<VecDeque<_>>();
1932    /// assert_eq!(drained, [3]);
1933    /// assert_eq!(deque, [1, 2]);
1934    ///
1935    /// // A full range clears all contents, like `clear()` does
1936    /// deque.drain(..);
1937    /// assert!(deque.is_empty());
1938    /// ```
1939    #[inline]
1940    #[stable(feature = "drain", since = "1.6.0")]
1941    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1942    where
1943        R: RangeBounds<usize>,
1944    {
1945        // Memory safety
1946        //
1947        // When the Drain is first created, the source deque is shortened to
1948        // make sure no uninitialized or moved-from elements are accessible at
1949        // all if the Drain's destructor never gets to run.
1950        //
1951        // Drain will ptr::read out the values to remove.
1952        // When finished, the remaining data will be copied back to cover the hole,
1953        // and the head/tail values will be restored correctly.
1954        //
1955        let Range { start, end } = slice::range(range, ..self.len);
1956        let drain_start = start;
1957        let drain_len = end - start;
1958
1959        // The deque's elements are parted into three segments:
1960        // * 0  -> drain_start
1961        // * drain_start -> drain_start+drain_len
1962        // * drain_start+drain_len -> self.len
1963        //
1964        // H = self.head; T = self.head+self.len; t = drain_start+drain_len; h = drain_head
1965        //
1966        // We store drain_start as self.len, and drain_len and self.len as
1967        // drain_len and orig_len respectively on the Drain. This also
1968        // truncates the effective array such that if the Drain is leaked, we
1969        // have forgotten about the potentially moved values after the start of
1970        // the drain.
1971        //
1972        //        H   h   t   T
1973        // [. . . o o x x o o . . .]
1974        //
1975        // "forget" about the values after the start of the drain until after
1976        // the drain is complete and the Drain destructor is run.
1977
1978        unsafe { Drain::new(self, drain_start, drain_len) }
1979    }
1980
1981    /// Creates a splicing iterator that replaces the specified range in the deque with the given
1982    /// `replace_with` iterator and yields the removed items. `replace_with` does not need to be the
1983    /// same length as `range`.
1984    ///
1985    /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped.
1986    ///
1987    /// It is unspecified how many elements are removed from the deque if the `Splice` value is
1988    /// leaked.
1989    ///
1990    /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
1991    ///
1992    /// This is optimal if:
1993    ///
1994    /// * The tail (elements in the deque after `range`) is empty,
1995    /// * or `replace_with` yields fewer or equal elements than `range`'s length
1996    /// * or the lower bound of its `size_hint()` is exact.
1997    ///
1998    /// Otherwise, a temporary vector is allocated and the tail is moved twice.
1999    ///
2000    /// # Panics
2001    ///
2002    /// Panics if the range has `start_bound > end_bound`, or, if the range is
2003    /// bounded on either end and past the length of the deque.
2004    ///
2005    /// # Examples
2006    ///
2007    /// ```
2008    /// # #![feature(deque_extend_front)]
2009    /// # use std::collections::VecDeque;
2010    ///
2011    /// let mut v = VecDeque::from(vec![1, 2, 3, 4]);
2012    /// let new = [7, 8, 9];
2013    /// let u: Vec<_> = v.splice(1..3, new).collect();
2014    /// assert_eq!(v, [1, 7, 8, 9, 4]);
2015    /// assert_eq!(u, [2, 3]);
2016    /// ```
2017    ///
2018    /// Using `splice` to insert new items into a vector efficiently at a specific position
2019    /// indicated by an empty range:
2020    ///
2021    /// ```
2022    /// # #![feature(deque_extend_front)]
2023    /// # use std::collections::VecDeque;
2024    ///
2025    /// let mut v = VecDeque::from(vec![1, 5]);
2026    /// let new = [2, 3, 4];
2027    /// v.splice(1..1, new);
2028    /// assert_eq!(v, [1, 2, 3, 4, 5]);
2029    /// ```
2030    #[unstable(feature = "deque_extend_front", issue = "146975")]
2031    pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2032    where
2033        R: RangeBounds<usize>,
2034        I: IntoIterator<Item = T>,
2035    {
2036        Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2037    }
2038
2039    /// Clears the deque, removing all values.
2040    ///
2041    /// # Examples
2042    ///
2043    /// ```
2044    /// use std::collections::VecDeque;
2045    ///
2046    /// let mut deque = VecDeque::new();
2047    /// deque.push_back(1);
2048    /// deque.clear();
2049    /// assert!(deque.is_empty());
2050    /// ```
2051    #[stable(feature = "rust1", since = "1.0.0")]
2052    #[expect(clippy::manual_clear, reason = "implements clear")]
2053    #[inline]
2054    pub fn clear(&mut self) {
2055        self.truncate(0);
2056        // Not strictly necessary, but leaves things in a more consistent/predictable state.
2057        self.head = WrappedIndex::zero();
2058    }
2059
2060    /// Returns `true` if the deque contains an element equal to the
2061    /// given value.
2062    ///
2063    /// This operation is *O*(*n*).
2064    ///
2065    /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
2066    ///
2067    /// [`binary_search`]: VecDeque::binary_search
2068    ///
2069    /// # Examples
2070    ///
2071    /// ```
2072    /// use std::collections::VecDeque;
2073    ///
2074    /// let mut deque: VecDeque<u32> = VecDeque::new();
2075    ///
2076    /// deque.push_back(0);
2077    /// deque.push_back(1);
2078    ///
2079    /// assert_eq!(deque.contains(&1), true);
2080    /// assert_eq!(deque.contains(&10), false);
2081    /// ```
2082    #[stable(feature = "vec_deque_contains", since = "1.12.0")]
2083    pub fn contains(&self, x: &T) -> bool
2084    where
2085        T: PartialEq<T>,
2086    {
2087        let (a, b) = self.as_slices();
2088        a.contains(x) || b.contains(x)
2089    }
2090
2091    /// Provides a reference to the front element, or `None` if the deque is
2092    /// empty.
2093    ///
2094    /// # Examples
2095    ///
2096    /// ```
2097    /// use std::collections::VecDeque;
2098    ///
2099    /// let mut d = VecDeque::new();
2100    /// assert_eq!(d.front(), None);
2101    ///
2102    /// d.push_back(1);
2103    /// d.push_back(2);
2104    /// assert_eq!(d.front(), Some(&1));
2105    /// ```
2106    #[stable(feature = "rust1", since = "1.0.0")]
2107    #[rustc_confusables("first")]
2108    pub fn front(&self) -> Option<&T> {
2109        self.get(0)
2110    }
2111
2112    /// Provides a mutable reference to the front element, or `None` if the
2113    /// deque is empty.
2114    ///
2115    /// # Examples
2116    ///
2117    /// ```
2118    /// use std::collections::VecDeque;
2119    ///
2120    /// let mut d = VecDeque::new();
2121    /// assert_eq!(d.front_mut(), None);
2122    ///
2123    /// d.push_back(1);
2124    /// d.push_back(2);
2125    /// match d.front_mut() {
2126    ///     Some(x) => *x = 9,
2127    ///     None => (),
2128    /// }
2129    /// assert_eq!(d.front(), Some(&9));
2130    /// ```
2131    #[stable(feature = "rust1", since = "1.0.0")]
2132    pub fn front_mut(&mut self) -> Option<&mut T> {
2133        self.get_mut(0)
2134    }
2135
2136    /// Provides a reference to the back element, or `None` if the deque is
2137    /// empty.
2138    ///
2139    /// # Examples
2140    ///
2141    /// ```
2142    /// use std::collections::VecDeque;
2143    ///
2144    /// let mut d = VecDeque::new();
2145    /// assert_eq!(d.back(), None);
2146    ///
2147    /// d.push_back(1);
2148    /// d.push_back(2);
2149    /// assert_eq!(d.back(), Some(&2));
2150    /// ```
2151    #[stable(feature = "rust1", since = "1.0.0")]
2152    #[rustc_confusables("last")]
2153    pub fn back(&self) -> Option<&T> {
2154        self.get(self.len.wrapping_sub(1))
2155    }
2156
2157    /// Provides a mutable reference to the back element, or `None` if the
2158    /// deque is empty.
2159    ///
2160    /// # Examples
2161    ///
2162    /// ```
2163    /// use std::collections::VecDeque;
2164    ///
2165    /// let mut d = VecDeque::new();
2166    /// assert_eq!(d.back(), None);
2167    ///
2168    /// d.push_back(1);
2169    /// d.push_back(2);
2170    /// match d.back_mut() {
2171    ///     Some(x) => *x = 9,
2172    ///     None => (),
2173    /// }
2174    /// assert_eq!(d.back(), Some(&9));
2175    /// ```
2176    #[stable(feature = "rust1", since = "1.0.0")]
2177    pub fn back_mut(&mut self) -> Option<&mut T> {
2178        self.get_mut(self.len.wrapping_sub(1))
2179    }
2180
2181    /// Removes the first element and returns it, or `None` if the deque is
2182    /// empty.
2183    ///
2184    /// # Examples
2185    ///
2186    /// ```
2187    /// use std::collections::VecDeque;
2188    ///
2189    /// let mut d = VecDeque::new();
2190    /// d.push_back(1);
2191    /// d.push_back(2);
2192    ///
2193    /// assert_eq!(d.pop_front(), Some(1));
2194    /// assert_eq!(d.pop_front(), Some(2));
2195    /// assert_eq!(d.pop_front(), None);
2196    /// ```
2197    #[stable(feature = "rust1", since = "1.0.0")]
2198    pub fn pop_front(&mut self) -> Option<T> {
2199        if self.is_empty() {
2200            None
2201        } else {
2202            let old_head = self.head;
2203            self.head = self.to_wrapped_index(1);
2204            self.len -= 1;
2205            unsafe {
2206                core::hint::assert_unchecked(self.len < self.capacity());
2207                Some(self.buffer_read(old_head))
2208            }
2209        }
2210    }
2211
2212    /// Removes the last element from the deque and returns it, or `None` if
2213    /// it is empty.
2214    ///
2215    /// # Examples
2216    ///
2217    /// ```
2218    /// use std::collections::VecDeque;
2219    ///
2220    /// let mut buf = VecDeque::new();
2221    /// assert_eq!(buf.pop_back(), None);
2222    /// buf.push_back(1);
2223    /// buf.push_back(3);
2224    /// assert_eq!(buf.pop_back(), Some(3));
2225    /// ```
2226    #[stable(feature = "rust1", since = "1.0.0")]
2227    pub fn pop_back(&mut self) -> Option<T> {
2228        if self.is_empty() {
2229            None
2230        } else {
2231            self.len -= 1;
2232            unsafe {
2233                core::hint::assert_unchecked(self.len < self.capacity());
2234                Some(self.buffer_read(self.to_wrapped_index(self.len)))
2235            }
2236        }
2237    }
2238
2239    /// Removes and returns the first element from the deque if the predicate
2240    /// returns `true`, or [`None`] if the predicate returns false or the deque
2241    /// is empty (the predicate will not be called in that case).
2242    ///
2243    /// # Examples
2244    ///
2245    /// ```
2246    /// use std::collections::VecDeque;
2247    ///
2248    /// let mut deque: VecDeque<i32> = vec![0, 1, 2, 3, 4].into();
2249    /// let pred = |x: &mut i32| *x % 2 == 0;
2250    ///
2251    /// assert_eq!(deque.pop_front_if(pred), Some(0));
2252    /// assert_eq!(deque, [1, 2, 3, 4]);
2253    /// assert_eq!(deque.pop_front_if(pred), None);
2254    /// ```
2255    #[stable(feature = "vec_deque_pop_if", since = "1.93.0")]
2256    pub fn pop_front_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2257        let first = self.front_mut()?;
2258        if predicate(first) { self.pop_front() } else { None }
2259    }
2260
2261    /// Removes and returns the last element from the deque if the predicate
2262    /// returns `true`, or [`None`] if the predicate returns false or the deque
2263    /// is empty (the predicate will not be called in that case).
2264    ///
2265    /// # Examples
2266    ///
2267    /// ```
2268    /// use std::collections::VecDeque;
2269    ///
2270    /// let mut deque: VecDeque<i32> = vec![0, 1, 2, 3, 4].into();
2271    /// let pred = |x: &mut i32| *x % 2 == 0;
2272    ///
2273    /// assert_eq!(deque.pop_back_if(pred), Some(4));
2274    /// assert_eq!(deque, [0, 1, 2, 3]);
2275    /// assert_eq!(deque.pop_back_if(pred), None);
2276    /// ```
2277    #[stable(feature = "vec_deque_pop_if", since = "1.93.0")]
2278    pub fn pop_back_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2279        let last = self.back_mut()?;
2280        if predicate(last) { self.pop_back() } else { None }
2281    }
2282
2283    /// Prepends an element to the deque.
2284    ///
2285    /// # Examples
2286    ///
2287    /// ```
2288    /// use std::collections::VecDeque;
2289    ///
2290    /// let mut d = VecDeque::new();
2291    /// d.push_front(1);
2292    /// d.push_front(2);
2293    /// assert_eq!(d.front(), Some(&2));
2294    /// ```
2295    #[stable(feature = "rust1", since = "1.0.0")]
2296    pub fn push_front(&mut self, value: T) {
2297        let _ = self.push_front_mut(value);
2298    }
2299
2300    /// Prepends an element to the deque, returning a reference to it.
2301    ///
2302    /// # Examples
2303    ///
2304    /// ```
2305    /// use std::collections::VecDeque;
2306    ///
2307    /// let mut d = VecDeque::from([1, 2, 3]);
2308    /// let x = d.push_front_mut(8);
2309    /// *x -= 1;
2310    /// assert_eq!(d.front(), Some(&7));
2311    /// ```
2312    #[stable(feature = "push_mut", since = "1.95.0")]
2313    #[must_use = "if you don't need a reference to the value, use `VecDeque::push_front` instead"]
2314    pub fn push_front_mut(&mut self, value: T) -> &mut T {
2315        if self.is_full() {
2316            self.grow();
2317        }
2318
2319        self.head = self.wrap_sub(self.head, 1);
2320        self.len += 1;
2321        // SAFETY: We know that self.head is within range of the deque.
2322        unsafe { self.buffer_write(self.head, value) }
2323    }
2324
2325    /// Appends an element to the back of the deque.
2326    ///
2327    /// # Examples
2328    ///
2329    /// ```
2330    /// use std::collections::VecDeque;
2331    ///
2332    /// let mut buf = VecDeque::new();
2333    /// buf.push_back(1);
2334    /// buf.push_back(3);
2335    /// assert_eq!(3, *buf.back().unwrap());
2336    /// ```
2337    #[stable(feature = "rust1", since = "1.0.0")]
2338    #[rustc_confusables("push", "put", "append")]
2339    pub fn push_back(&mut self, value: T) {
2340        let _ = self.push_back_mut(value);
2341    }
2342
2343    /// Appends an element to the back of the deque, returning a reference to it.
2344    ///
2345    /// # Examples
2346    ///
2347    /// ```
2348    /// use std::collections::VecDeque;
2349    ///
2350    /// let mut d = VecDeque::from([1, 2, 3]);
2351    /// let x = d.push_back_mut(9);
2352    /// *x += 1;
2353    /// assert_eq!(d.back(), Some(&10));
2354    /// ```
2355    #[stable(feature = "push_mut", since = "1.95.0")]
2356    #[must_use = "if you don't need a reference to the value, use `VecDeque::push_back` instead"]
2357    pub fn push_back_mut(&mut self, value: T) -> &mut T {
2358        if self.is_full() {
2359            self.grow();
2360        }
2361
2362        let len = self.len;
2363        self.len += 1;
2364        unsafe { self.buffer_write(self.to_wrapped_index(len), value) }
2365    }
2366
2367    /// Prepends all contents of the iterator to the front of the deque.
2368    /// The order of the contents is preserved.
2369    ///
2370    /// To get behavior like [`append`][VecDeque::append] where elements are moved
2371    /// from the other collection to this one, use `self.prepend(other.drain(..))`.
2372    ///
2373    /// # Examples
2374    ///
2375    /// ```
2376    /// #![feature(deque_extend_front)]
2377    /// use std::collections::VecDeque;
2378    ///
2379    /// let mut deque = VecDeque::from([4, 5, 6]);
2380    /// deque.prepend([1, 2, 3]);
2381    /// assert_eq!(deque, [1, 2, 3, 4, 5, 6]);
2382    /// ```
2383    ///
2384    /// Move values between collections like [`append`][VecDeque::append] does but prepend to the front:
2385    ///
2386    /// ```
2387    /// #![feature(deque_extend_front)]
2388    /// use std::collections::VecDeque;
2389    ///
2390    /// let mut deque1 = VecDeque::from([4, 5, 6]);
2391    /// let mut deque2 = VecDeque::from([1, 2, 3]);
2392    /// deque1.prepend(deque2.drain(..));
2393    /// assert_eq!(deque1, [1, 2, 3, 4, 5, 6]);
2394    /// assert!(deque2.is_empty());
2395    /// ```
2396    #[unstable(feature = "deque_extend_front", issue = "146975")]
2397    #[track_caller]
2398    pub fn prepend<I: IntoIterator<Item = T, IntoIter: DoubleEndedIterator>>(&mut self, other: I) {
2399        self.extend_front(other.into_iter().rev())
2400    }
2401
2402    /// Prepends all contents of the iterator to the front of the deque,
2403    /// as if [`push_front`][VecDeque::push_front] was called repeatedly with
2404    /// the values yielded by the iterator.
2405    ///
2406    /// # Examples
2407    ///
2408    /// ```
2409    /// #![feature(deque_extend_front)]
2410    /// use std::collections::VecDeque;
2411    ///
2412    /// let mut deque = VecDeque::from([4, 5, 6]);
2413    /// deque.extend_front([3, 2, 1]);
2414    /// assert_eq!(deque, [1, 2, 3, 4, 5, 6]);
2415    /// ```
2416    ///
2417    /// This behaves like [`push_front`][VecDeque::push_front] was called repeatedly:
2418    ///
2419    /// ```
2420    /// use std::collections::VecDeque;
2421    ///
2422    /// let mut deque = VecDeque::from([4, 5, 6]);
2423    /// for v in [3, 2, 1] {
2424    ///     deque.push_front(v);
2425    /// }
2426    /// assert_eq!(deque, [1, 2, 3, 4, 5, 6]);
2427    /// ```
2428    #[unstable(feature = "deque_extend_front", issue = "146975")]
2429    #[track_caller]
2430    pub fn extend_front<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2431        <Self as SpecExtendFront<T, I::IntoIter>>::spec_extend_front(self, iter.into_iter());
2432    }
2433
2434    #[inline]
2435    fn is_contiguous(&self) -> bool {
2436        // Do the calculation like this to avoid overflowing if len + head > usize::MAX
2437        self.head <= self.capacity() - self.len
2438    }
2439
2440    /// Removes an element from anywhere in the deque and returns it,
2441    /// replacing it with the first element.
2442    ///
2443    /// This does not preserve ordering, but is *O*(1).
2444    ///
2445    /// Returns `None` if `index` is out of bounds.
2446    ///
2447    /// Element at index 0 is the front of the queue.
2448    ///
2449    /// # Examples
2450    ///
2451    /// ```
2452    /// use std::collections::VecDeque;
2453    ///
2454    /// let mut buf = VecDeque::new();
2455    /// assert_eq!(buf.swap_remove_front(0), None);
2456    /// buf.push_back(1);
2457    /// buf.push_back(2);
2458    /// buf.push_back(3);
2459    /// assert_eq!(buf, [1, 2, 3]);
2460    ///
2461    /// assert_eq!(buf.swap_remove_front(2), Some(3));
2462    /// assert_eq!(buf, [2, 1]);
2463    /// ```
2464    #[stable(feature = "deque_extras_15", since = "1.5.0")]
2465    pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
2466        let length = self.len;
2467        if index < length && index != 0 {
2468            self.swap(index, 0);
2469        } else if index >= length {
2470            return None;
2471        }
2472        self.pop_front()
2473    }
2474
2475    /// Removes an element from anywhere in the deque and returns it,
2476    /// replacing it with the last element.
2477    ///
2478    /// This does not preserve ordering, but is *O*(1).
2479    ///
2480    /// Returns `None` if `index` is out of bounds.
2481    ///
2482    /// Element at index 0 is the front of the queue.
2483    ///
2484    /// # Examples
2485    ///
2486    /// ```
2487    /// use std::collections::VecDeque;
2488    ///
2489    /// let mut buf = VecDeque::new();
2490    /// assert_eq!(buf.swap_remove_back(0), None);
2491    /// buf.push_back(1);
2492    /// buf.push_back(2);
2493    /// buf.push_back(3);
2494    /// assert_eq!(buf, [1, 2, 3]);
2495    ///
2496    /// assert_eq!(buf.swap_remove_back(0), Some(1));
2497    /// assert_eq!(buf, [3, 2]);
2498    /// ```
2499    #[stable(feature = "deque_extras_15", since = "1.5.0")]
2500    pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
2501        let length = self.len;
2502        if length > 0 && index < length - 1 {
2503            self.swap(index, length - 1);
2504        } else if index >= length {
2505            return None;
2506        }
2507        self.pop_back()
2508    }
2509
2510    /// Inserts an element at `index` within the deque, shifting all elements
2511    /// with indices greater than or equal to `index` towards the back.
2512    ///
2513    /// Element at index 0 is the front of the queue.
2514    ///
2515    /// # Panics
2516    ///
2517    /// Panics if `index` is strictly greater than the deque's length.
2518    ///
2519    /// # Examples
2520    ///
2521    /// ```
2522    /// use std::collections::VecDeque;
2523    ///
2524    /// let mut vec_deque = VecDeque::new();
2525    /// vec_deque.push_back('a');
2526    /// vec_deque.push_back('b');
2527    /// vec_deque.push_back('c');
2528    /// assert_eq!(vec_deque, &['a', 'b', 'c']);
2529    ///
2530    /// vec_deque.insert(1, 'd');
2531    /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
2532    ///
2533    /// vec_deque.insert(4, 'e');
2534    /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c', 'e']);
2535    /// ```
2536    #[stable(feature = "deque_extras_15", since = "1.5.0")]
2537    pub fn insert(&mut self, index: usize, value: T) {
2538        let _ = self.insert_mut(index, value);
2539    }
2540
2541    /// Inserts an element at `index` within the deque, shifting all elements
2542    /// with indices greater than or equal to `index` towards the back, and
2543    /// returning a reference to it.
2544    ///
2545    /// Element at index 0 is the front of the queue.
2546    ///
2547    /// # Panics
2548    ///
2549    /// Panics if `index` is strictly greater than the deque's length.
2550    ///
2551    /// # Examples
2552    ///
2553    /// ```
2554    /// use std::collections::VecDeque;
2555    ///
2556    /// let mut vec_deque = VecDeque::from([1, 2, 3]);
2557    ///
2558    /// let x = vec_deque.insert_mut(1, 5);
2559    /// *x += 7;
2560    /// assert_eq!(vec_deque, &[1, 12, 2, 3]);
2561    /// ```
2562    #[stable(feature = "push_mut", since = "1.95.0")]
2563    #[must_use = "if you don't need a reference to the value, use `VecDeque::insert` instead"]
2564    pub fn insert_mut(&mut self, index: usize, value: T) -> &mut T {
2565        assert!(index <= self.len(), "index out of bounds");
2566
2567        if self.is_full() {
2568            self.grow();
2569        }
2570
2571        let k = self.len - index;
2572        if k < index {
2573            // `index + 1` can't overflow, because if index was usize::MAX, then either the
2574            // assert would've failed, or the deque would've tried to grow past usize::MAX
2575            // and panicked.
2576            unsafe {
2577                // see `remove()` for explanation why this wrap_copy() call is safe.
2578                self.wrap_copy(self.to_wrapped_index(index), self.to_wrapped_index(index + 1), k);
2579                self.len += 1;
2580                self.buffer_write(self.to_wrapped_index(index), value)
2581            }
2582        } else {
2583            let old_head = self.head;
2584            self.head = self.wrap_sub(self.head, 1);
2585            unsafe {
2586                self.wrap_copy(old_head, self.head, index);
2587                self.len += 1;
2588                self.buffer_write(self.to_wrapped_index(index), value)
2589            }
2590        }
2591    }
2592
2593    /// Removes and returns the element at `index` from the deque.
2594    /// Whichever end is closer to the removal point will be moved to make
2595    /// room, and all the affected elements will be moved to new positions.
2596    /// Returns `None` if `index` is out of bounds.
2597    ///
2598    /// Element at index 0 is the front of the queue.
2599    ///
2600    /// # Examples
2601    ///
2602    /// ```
2603    /// use std::collections::VecDeque;
2604    ///
2605    /// let mut buf = VecDeque::new();
2606    /// buf.push_back('a');
2607    /// buf.push_back('b');
2608    /// buf.push_back('c');
2609    /// assert_eq!(buf, ['a', 'b', 'c']);
2610    ///
2611    /// assert_eq!(buf.remove(1), Some('b'));
2612    /// assert_eq!(buf, ['a', 'c']);
2613    /// ```
2614    #[stable(feature = "rust1", since = "1.0.0")]
2615    #[rustc_confusables("delete", "take")]
2616    pub fn remove(&mut self, index: usize) -> Option<T> {
2617        if self.len <= index {
2618            return None;
2619        }
2620
2621        let wrapped_idx = self.to_wrapped_index(index);
2622
2623        let elem = unsafe { Some(self.buffer_read(wrapped_idx)) };
2624
2625        let k = self.len - index - 1;
2626        // safety: due to the nature of the if-condition, whichever wrap_copy gets called,
2627        // its length argument will be at most `self.len / 2`, so there can't be more than
2628        // one overlapping area.
2629        if k < index {
2630            unsafe { self.wrap_copy(self.wrap_add(wrapped_idx, 1), wrapped_idx, k) };
2631            self.len -= 1;
2632        } else {
2633            let old_head = self.head;
2634            self.head = self.to_wrapped_index(1);
2635            unsafe { self.wrap_copy(old_head, self.head, index) };
2636            self.len -= 1;
2637        }
2638
2639        elem
2640    }
2641
2642    /// Splits the deque into two at the given index.
2643    ///
2644    /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2645    /// and the returned deque contains elements `[at, len)`.
2646    ///
2647    /// Note that the capacity of `self` does not change.
2648    ///
2649    /// Element at index 0 is the front of the queue.
2650    ///
2651    /// # Panics
2652    ///
2653    /// Panics if `at > len`.
2654    ///
2655    /// # Examples
2656    ///
2657    /// ```
2658    /// use std::collections::VecDeque;
2659    ///
2660    /// let mut buf: VecDeque<_> = ['a', 'b', 'c'].into();
2661    /// let buf2 = buf.split_off(1);
2662    /// assert_eq!(buf, ['a']);
2663    /// assert_eq!(buf2, ['b', 'c']);
2664    /// ```
2665    #[inline]
2666    #[must_use = "use `.truncate()` if you don't need the other half"]
2667    #[stable(feature = "split_off", since = "1.4.0")]
2668    pub fn split_off(&mut self, at: usize) -> Self
2669    where
2670        A: Clone,
2671    {
2672        let len = self.len;
2673        assert!(at <= len, "`at` out of bounds");
2674
2675        let other_len = len - at;
2676        let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2677
2678        let (first_half, second_half) = self.as_slices();
2679        let first_len = first_half.len();
2680        let second_len = second_half.len();
2681
2682        unsafe {
2683            if at < first_len {
2684                // `at` lies in the first half.
2685                let amount_in_first = first_len - at;
2686
2687                ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2688
2689                // just take all of the second half.
2690                ptr::copy_nonoverlapping(
2691                    second_half.as_ptr(),
2692                    other.ptr().add(amount_in_first),
2693                    second_len,
2694                );
2695            } else {
2696                // `at` lies in the second half, need to factor in the elements we skipped
2697                // in the first half.
2698                let offset = at - first_len;
2699                let amount_in_second = second_len - offset;
2700                ptr::copy_nonoverlapping(
2701                    second_half.as_ptr().add(offset),
2702                    other.ptr(),
2703                    amount_in_second,
2704                );
2705            }
2706        }
2707
2708        // Cleanup where the ends of the buffers are
2709        self.len = at;
2710        other.len = other_len;
2711
2712        other
2713    }
2714
2715    /// Moves all the elements of `other` into `self`, leaving `other` empty.
2716    ///
2717    /// # Panics
2718    ///
2719    /// Panics if the new number of elements in self overflows a `usize`.
2720    ///
2721    /// # Examples
2722    ///
2723    /// ```
2724    /// use std::collections::VecDeque;
2725    ///
2726    /// let mut buf: VecDeque<_> = [1, 2].into();
2727    /// let mut buf2: VecDeque<_> = [3, 4].into();
2728    /// buf.append(&mut buf2);
2729    /// assert_eq!(buf, [1, 2, 3, 4]);
2730    /// assert_eq!(buf2, []);
2731    /// ```
2732    #[inline]
2733    #[stable(feature = "append", since = "1.4.0")]
2734    pub fn append(&mut self, other: &mut Self) {
2735        if T::IS_ZST {
2736            self.len = self.len.checked_add(other.len).expect("capacity overflow");
2737            other.len = 0;
2738            other.head = WrappedIndex::zero();
2739            return;
2740        }
2741
2742        self.reserve(other.len);
2743        unsafe {
2744            let (left, right) = other.as_slices();
2745            self.copy_slice(self.to_wrapped_index(self.len), left);
2746            // no overflow, because self.capacity() >= old_cap + left.len() >= self.len + left.len()
2747            self.copy_slice(self.to_wrapped_index(self.len + left.len()), right);
2748        }
2749        // SAFETY: Update pointers after copying to avoid leaving doppelganger
2750        // in case of panics.
2751        self.len += other.len;
2752        // Now that we own its values, forget everything in `other`.
2753        other.len = 0;
2754        other.head = WrappedIndex::zero();
2755    }
2756
2757    /// Retains only the elements specified by the predicate.
2758    ///
2759    /// In other words, remove all elements `e` for which `f(&e)` returns false.
2760    /// This method operates in place, visiting each element exactly once in the
2761    /// original order, and preserves the order of the retained elements.
2762    ///
2763    /// # Examples
2764    ///
2765    /// ```
2766    /// use std::collections::VecDeque;
2767    ///
2768    /// let mut buf = VecDeque::new();
2769    /// buf.extend(1..5);
2770    /// buf.retain(|&x| x % 2 == 0);
2771    /// assert_eq!(buf, [2, 4]);
2772    /// ```
2773    ///
2774    /// Because the elements are visited exactly once in the original order,
2775    /// external state may be used to decide which elements to keep.
2776    ///
2777    /// ```
2778    /// use std::collections::VecDeque;
2779    ///
2780    /// let mut buf = VecDeque::new();
2781    /// buf.extend(1..6);
2782    ///
2783    /// let keep = [false, true, true, false, true];
2784    /// let mut iter = keep.iter();
2785    /// buf.retain(|_| *iter.next().unwrap());
2786    /// assert_eq!(buf, [2, 3, 5]);
2787    /// ```
2788    #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2789    pub fn retain<F>(&mut self, mut f: F)
2790    where
2791        F: FnMut(&T) -> bool,
2792    {
2793        self.retain_mut(|elem| f(elem));
2794    }
2795
2796    /// Retains only the elements specified by the predicate.
2797    ///
2798    /// In other words, remove all elements `e` for which `f(&mut e)` returns false.
2799    /// This method operates in place, visiting each element exactly once in the
2800    /// original order, and preserves the order of the retained elements.
2801    ///
2802    /// # Examples
2803    ///
2804    /// ```
2805    /// use std::collections::VecDeque;
2806    ///
2807    /// let mut buf = VecDeque::new();
2808    /// buf.extend(1..5);
2809    /// buf.retain_mut(|x| if *x % 2 == 0 {
2810    ///     *x += 1;
2811    ///     true
2812    /// } else {
2813    ///     false
2814    /// });
2815    /// assert_eq!(buf, [3, 5]);
2816    /// ```
2817    #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2818    pub fn retain_mut<F>(&mut self, mut f: F)
2819    where
2820        F: FnMut(&mut T) -> bool,
2821    {
2822        let len = self.len;
2823        let mut idx = 0;
2824        let mut cur = 0;
2825
2826        // Stage 1: All values are retained.
2827        while cur < len {
2828            if !f(&mut self[cur]) {
2829                cur += 1;
2830                break;
2831            }
2832            cur += 1;
2833            idx += 1;
2834        }
2835        // Stage 2: Swap retained value into current idx.
2836        while cur < len {
2837            if !f(&mut self[cur]) {
2838                cur += 1;
2839                continue;
2840            }
2841
2842            self.swap(idx, cur);
2843            cur += 1;
2844            idx += 1;
2845        }
2846        // Stage 3: Truncate all values after idx.
2847        if cur != idx {
2848            self.truncate(idx);
2849        }
2850    }
2851
2852    // Double the buffer size. This method is inline(never), so we expect it to only
2853    // be called in cold paths.
2854    // This may panic or abort
2855    #[inline(never)]
2856    fn grow(&mut self) {
2857        // Extend or possibly remove this assertion when valid use-cases for growing the
2858        // buffer without it being full emerge
2859        debug_assert!(self.is_full());
2860        let old_cap = self.capacity();
2861        self.buf.grow_one();
2862        unsafe {
2863            self.handle_capacity_increase(old_cap);
2864        }
2865        debug_assert!(!self.is_full());
2866    }
2867
2868    /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2869    /// either by removing excess elements from the back or by appending
2870    /// elements generated by calling `generator` to the back.
2871    ///
2872    /// # Examples
2873    ///
2874    /// ```
2875    /// use std::collections::VecDeque;
2876    ///
2877    /// let mut buf = VecDeque::new();
2878    /// buf.push_back(5);
2879    /// buf.push_back(10);
2880    /// buf.push_back(15);
2881    /// assert_eq!(buf, [5, 10, 15]);
2882    ///
2883    /// buf.resize_with(5, Default::default);
2884    /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2885    ///
2886    /// buf.resize_with(2, || unreachable!());
2887    /// assert_eq!(buf, [5, 10]);
2888    ///
2889    /// let mut state = 100;
2890    /// buf.resize_with(5, || { state += 1; state });
2891    /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2892    /// ```
2893    #[stable(feature = "vec_resize_with", since = "1.33.0")]
2894    pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2895        let len = self.len;
2896
2897        if new_len > len {
2898            self.extend(repeat_with(generator).take(new_len - len))
2899        } else {
2900            self.truncate(new_len);
2901        }
2902    }
2903
2904    /// Rearranges the internal storage of this deque so it is one contiguous
2905    /// slice, which is then returned.
2906    ///
2907    /// This method does not allocate and does not change the order of the
2908    /// inserted elements. As it returns a mutable slice, this can be used to
2909    /// sort a deque.
2910    ///
2911    /// Once the internal storage is contiguous, the [`as_slices`] and
2912    /// [`as_mut_slices`] methods will return the entire contents of the
2913    /// deque in a single slice.
2914    ///
2915    /// [`as_slices`]: VecDeque::as_slices
2916    /// [`as_mut_slices`]: VecDeque::as_mut_slices
2917    ///
2918    /// # Examples
2919    ///
2920    /// Sorting the content of a deque.
2921    ///
2922    /// ```
2923    /// use std::collections::VecDeque;
2924    ///
2925    /// let mut buf = VecDeque::with_capacity(15);
2926    ///
2927    /// buf.push_back(2);
2928    /// buf.push_back(1);
2929    /// buf.push_front(3);
2930    ///
2931    /// // sorting the deque
2932    /// buf.make_contiguous().sort();
2933    /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2934    ///
2935    /// // sorting it in reverse order
2936    /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2937    /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2938    /// ```
2939    ///
2940    /// Getting immutable access to the contiguous slice.
2941    ///
2942    /// ```rust
2943    /// use std::collections::VecDeque;
2944    ///
2945    /// let mut buf = VecDeque::new();
2946    ///
2947    /// buf.push_back(2);
2948    /// buf.push_back(1);
2949    /// buf.push_front(3);
2950    ///
2951    /// buf.make_contiguous();
2952    /// if let (slice, &[]) = buf.as_slices() {
2953    ///     // we can now be sure that `slice` contains all elements of the deque,
2954    ///     // while still having immutable access to `buf`.
2955    ///     assert_eq!(buf.len(), slice.len());
2956    ///     assert_eq!(slice, &[3, 2, 1] as &[_]);
2957    /// }
2958    /// ```
2959    #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2960    pub fn make_contiguous(&mut self) -> &mut [T] {
2961        if T::IS_ZST {
2962            self.head = WrappedIndex::zero();
2963        }
2964
2965        if self.is_contiguous() {
2966            unsafe {
2967                return slice::from_raw_parts_mut(self.ptr().add(self.head.as_index()), self.len);
2968            }
2969        }
2970
2971        let &mut Self { head, len, .. } = self;
2972        let ptr = self.ptr();
2973        let cap = self.capacity();
2974
2975        let free = cap - len;
2976        let head_len = cap - head.as_index();
2977
2978        // tail <= head < capacity
2979        // head cannot be <= capacity, because we know that VecDeque is non-empty, since it is not
2980        // contiguous at this point
2981        let tail = WrappedIndex::from_arbitrary_number(len - head_len);
2982        let tail_len = tail.as_index();
2983
2984        if free >= head_len {
2985            // there is enough free space to copy the head in one go,
2986            // this means that we first shift the tail backwards, and then
2987            // copy the head to the correct position.
2988            //
2989            // from: DEFGH....ABC
2990            // to:   ABCDEFGH....
2991            unsafe {
2992                self.copy(
2993                    WrappedIndex::zero(),
2994                    WrappedIndex::from_arbitrary_number(head_len),
2995                    tail_len,
2996                );
2997                // ...DEFGH.ABC
2998                self.copy_nonoverlapping(head, WrappedIndex::zero(), head_len);
2999                // ABCDEFGH....
3000            }
3001
3002            self.head = WrappedIndex::zero();
3003        } else if free >= tail_len {
3004            // there is enough free space to copy the tail in one go,
3005            // this means that we first shift the head forwards, and then
3006            // copy the tail to the correct position.
3007            //
3008            // from: FGH....ABCDE
3009            // to:   ...ABCDEFGH.
3010            unsafe {
3011                self.copy(head, tail, head_len);
3012                // FGHABCDE....
3013                self.copy_nonoverlapping(WrappedIndex::zero(), tail.add(head_len), tail_len);
3014                // ...ABCDEFGH.
3015            }
3016
3017            self.head = tail;
3018        } else {
3019            // `free` is smaller than both `head_len` and `tail_len`.
3020            // the general algorithm for this first moves the slices
3021            // right next to each other and then uses `slice::rotate`
3022            // to rotate them into place:
3023            //
3024            // initially:   HIJK..ABCDEFG
3025            // step 1:      ..HIJKABCDEFG
3026            // step 2:      ..ABCDEFGHIJK
3027            //
3028            // or:
3029            //
3030            // initially:   FGHIJK..ABCDE
3031            // step 1:      FGHIJKABCDE..
3032            // step 2:      ABCDEFGHIJK..
3033
3034            // pick the shorter of the 2 slices to reduce the amount
3035            // of memory that needs to be moved around.
3036            if head_len > tail_len {
3037                // tail is shorter, so:
3038                //  1. copy tail forwards
3039                //  2. rotate used part of the buffer
3040                //  3. update head to point to the new beginning (which is just `free`)
3041
3042                unsafe {
3043                    // if there is no free space in the buffer, then the slices are already
3044                    // right next to each other and we don't need to move any memory.
3045                    if free != 0 {
3046                        // because we only move the tail forward as much as there's free space
3047                        // behind it, we don't overwrite any elements of the head slice, and
3048                        // the slices end up right next to each other.
3049                        self.copy(
3050                            WrappedIndex::zero(),
3051                            WrappedIndex::from_arbitrary_number(free),
3052                            tail_len,
3053                        );
3054                    }
3055
3056                    // We just copied the tail right next to the head slice,
3057                    // so all of the elements in the range are initialized
3058                    let slice = &mut *self.buffer_range(free..self.capacity());
3059
3060                    // because the deque wasn't contiguous, we know that `tail_len < self.len == slice.len()`,
3061                    // so this will never panic.
3062                    slice.rotate_left(tail_len);
3063
3064                    // the used part of the buffer now is `free..self.capacity()`, so set
3065                    // `head` to the beginning of that range.
3066                    self.head = WrappedIndex::from_arbitrary_number(free);
3067                }
3068            } else {
3069                // head is shorter so:
3070                //  1. copy head backwards
3071                //  2. rotate used part of the buffer
3072                //  3. update head to point to the new beginning (which is the beginning of the buffer)
3073
3074                unsafe {
3075                    // if there is no free space in the buffer, then the slices are already
3076                    // right next to each other and we don't need to move any memory.
3077                    if free != 0 {
3078                        // copy the head slice to lie right behind the tail slice.
3079                        self.copy(
3080                            self.head,
3081                            WrappedIndex::from_arbitrary_number(tail_len),
3082                            head_len,
3083                        );
3084                    }
3085
3086                    // because we copied the head slice so that both slices lie right
3087                    // next to each other, all the elements in the range are initialized.
3088                    let slice = &mut *self.buffer_range(0..self.len);
3089
3090                    // because the deque wasn't contiguous, we know that `head_len < self.len == slice.len()`
3091                    // so this will never panic.
3092                    slice.rotate_right(head_len);
3093
3094                    // the used part of the buffer now is `0..self.len`, so set
3095                    // `head` to the beginning of that range.
3096                    self.head = WrappedIndex::zero();
3097                }
3098            }
3099        }
3100
3101        unsafe { slice::from_raw_parts_mut(ptr.add(self.head.as_index()), self.len) }
3102    }
3103
3104    /// Rotates the double-ended queue `n` places to the left.
3105    ///
3106    /// Equivalently,
3107    /// - Rotates item `n` into the first position.
3108    /// - Pops the first `n` items and pushes them to the end.
3109    /// - Rotates `len() - n` places to the right.
3110    ///
3111    /// # Panics
3112    ///
3113    /// If `n` is greater than `len()`. Note that `n == len()`
3114    /// does _not_ panic and is a no-op rotation.
3115    ///
3116    /// # Complexity
3117    ///
3118    /// Takes `*O*(min(n, len() - n))` time and no extra space.
3119    ///
3120    /// # Examples
3121    ///
3122    /// ```
3123    /// use std::collections::VecDeque;
3124    ///
3125    /// let mut buf: VecDeque<_> = (0..10).collect();
3126    ///
3127    /// buf.rotate_left(3);
3128    /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
3129    ///
3130    /// for i in 1..10 {
3131    ///     assert_eq!(i * 3 % 10, buf[0]);
3132    ///     buf.rotate_left(3);
3133    /// }
3134    /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
3135    /// ```
3136    #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
3137    pub fn rotate_left(&mut self, n: usize) {
3138        assert!(n <= self.len());
3139        let k = self.len - n;
3140        if n <= k {
3141            unsafe { self.rotate_left_inner(n) }
3142        } else {
3143            unsafe { self.rotate_right_inner(k) }
3144        }
3145    }
3146
3147    /// Rotates the double-ended queue `n` places to the right.
3148    ///
3149    /// Equivalently,
3150    /// - Rotates the first item into position `n`.
3151    /// - Pops the last `n` items and pushes them to the front.
3152    /// - Rotates `len() - n` places to the left.
3153    ///
3154    /// # Panics
3155    ///
3156    /// If `n` is greater than `len()`. Note that `n == len()`
3157    /// does _not_ panic and is a no-op rotation.
3158    ///
3159    /// # Complexity
3160    ///
3161    /// Takes `*O*(min(n, len() - n))` time and no extra space.
3162    ///
3163    /// # Examples
3164    ///
3165    /// ```
3166    /// use std::collections::VecDeque;
3167    ///
3168    /// let mut buf: VecDeque<_> = (0..10).collect();
3169    ///
3170    /// buf.rotate_right(3);
3171    /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
3172    ///
3173    /// for i in 1..10 {
3174    ///     assert_eq!(0, buf[i * 3 % 10]);
3175    ///     buf.rotate_right(3);
3176    /// }
3177    /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
3178    /// ```
3179    #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
3180    pub fn rotate_right(&mut self, n: usize) {
3181        assert!(n <= self.len());
3182        let k = self.len - n;
3183        if n <= k {
3184            unsafe { self.rotate_right_inner(n) }
3185        } else {
3186            unsafe { self.rotate_left_inner(k) }
3187        }
3188    }
3189
3190    // SAFETY: the following two methods require that the rotation amount
3191    // be less than half the length of the deque.
3192    //
3193    // `wrap_copy` requires that `min(x, capacity() - x) + copy_len <= capacity()`,
3194    // but then `min` is never more than half the capacity, regardless of x,
3195    // so it's sound to call here because we're calling with something
3196    // less than half the length, which is never above half the capacity.
3197
3198    unsafe fn rotate_left_inner(&mut self, mid: usize) {
3199        debug_assert!(mid * 2 <= self.len());
3200        unsafe {
3201            self.wrap_copy(self.head, self.to_wrapped_index(self.len), mid);
3202        }
3203        self.head = self.to_wrapped_index(mid);
3204    }
3205
3206    unsafe fn rotate_right_inner(&mut self, k: usize) {
3207        debug_assert!(k * 2 <= self.len());
3208        self.head = self.wrap_sub(self.head, k);
3209        unsafe {
3210            self.wrap_copy(self.to_wrapped_index(self.len), self.head, k);
3211        }
3212    }
3213
3214    /// Binary searches this `VecDeque` for a given element.
3215    /// If the `VecDeque` is not sorted, the returned result is unspecified and
3216    /// meaningless.
3217    ///
3218    /// If the value is found then [`Result::Ok`] is returned, containing the
3219    /// index of the matching element. If there are multiple matches, then any
3220    /// one of the matches could be returned. If the value is not found then
3221    /// [`Result::Err`] is returned, containing the index where a matching
3222    /// element could be inserted while maintaining sorted order.
3223    ///
3224    /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
3225    ///
3226    /// [`binary_search_by`]: VecDeque::binary_search_by
3227    /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
3228    /// [`partition_point`]: VecDeque::partition_point
3229    ///
3230    /// # Examples
3231    ///
3232    /// Looks up a series of four elements. The first is found, with a
3233    /// uniquely determined position; the second and third are not
3234    /// found; the fourth could match any position in `[1, 4]`.
3235    ///
3236    /// ```
3237    /// use std::collections::VecDeque;
3238    ///
3239    /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3240    ///
3241    /// assert_eq!(deque.binary_search(&13),  Ok(9));
3242    /// assert_eq!(deque.binary_search(&4),   Err(7));
3243    /// assert_eq!(deque.binary_search(&100), Err(13));
3244    /// let r = deque.binary_search(&1);
3245    /// assert!(matches!(r, Ok(1..=4)));
3246    /// ```
3247    ///
3248    /// If you want to insert an item to a sorted deque, while maintaining
3249    /// sort order, consider using [`partition_point`]:
3250    ///
3251    /// ```
3252    /// use std::collections::VecDeque;
3253    ///
3254    /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3255    /// let num = 42;
3256    /// let idx = deque.partition_point(|&x| x <= num);
3257    /// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
3258    /// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` may allow `insert`
3259    /// // to shift less elements.
3260    /// deque.insert(idx, num);
3261    /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
3262    /// ```
3263    #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3264    #[inline]
3265    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
3266    where
3267        T: Ord,
3268    {
3269        self.binary_search_by(|e| e.cmp(x))
3270    }
3271
3272    /// Binary searches this `VecDeque` with a comparator function.
3273    ///
3274    /// The comparator function should return an order code that indicates
3275    /// whether its argument is `Less`, `Equal` or `Greater` the desired
3276    /// target.
3277    /// If the `VecDeque` is not sorted or if the comparator function does not
3278    /// implement an order consistent with the sort order of the underlying
3279    /// `VecDeque`, the returned result is unspecified and meaningless.
3280    ///
3281    /// If the value is found then [`Result::Ok`] is returned, containing the
3282    /// index of the matching element. If there are multiple matches, then any
3283    /// one of the matches could be returned. If the value is not found then
3284    /// [`Result::Err`] is returned, containing the index where a matching
3285    /// element could be inserted while maintaining sorted order.
3286    ///
3287    /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
3288    ///
3289    /// [`binary_search`]: VecDeque::binary_search
3290    /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
3291    /// [`partition_point`]: VecDeque::partition_point
3292    ///
3293    /// # Examples
3294    ///
3295    /// Looks up a series of four elements. The first is found, with a
3296    /// uniquely determined position; the second and third are not
3297    /// found; the fourth could match any position in `[1, 4]`.
3298    ///
3299    /// ```
3300    /// use std::collections::VecDeque;
3301    ///
3302    /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3303    ///
3304    /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)),  Ok(9));
3305    /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)),   Err(7));
3306    /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
3307    /// let r = deque.binary_search_by(|x| x.cmp(&1));
3308    /// assert!(matches!(r, Ok(1..=4)));
3309    /// ```
3310    #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3311    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
3312    where
3313        F: FnMut(&'a T) -> Ordering,
3314    {
3315        let (front, back) = self.as_slices();
3316        let cmp_back = back.first().map(&mut f);
3317
3318        if let Some(Ordering::Equal) = cmp_back {
3319            Ok(front.len())
3320        } else if let Some(Ordering::Less) = cmp_back {
3321            back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
3322        } else {
3323            front.binary_search_by(f)
3324        }
3325    }
3326
3327    /// Binary searches this `VecDeque` with a key extraction function.
3328    ///
3329    /// Assumes that the deque is sorted by the key, for instance with
3330    /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
3331    /// If the deque is not sorted by the key, the returned result is
3332    /// unspecified and meaningless.
3333    ///
3334    /// If the value is found then [`Result::Ok`] is returned, containing the
3335    /// index of the matching element. If there are multiple matches, then any
3336    /// one of the matches could be returned. If the value is not found then
3337    /// [`Result::Err`] is returned, containing the index where a matching
3338    /// element could be inserted while maintaining sorted order.
3339    ///
3340    /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
3341    ///
3342    /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
3343    /// [`binary_search`]: VecDeque::binary_search
3344    /// [`binary_search_by`]: VecDeque::binary_search_by
3345    /// [`partition_point`]: VecDeque::partition_point
3346    ///
3347    /// # Examples
3348    ///
3349    /// Looks up a series of four elements in a slice of pairs sorted by
3350    /// their second elements. The first is found, with a uniquely
3351    /// determined position; the second and third are not found; the
3352    /// fourth could match any position in `[1, 4]`.
3353    ///
3354    /// ```
3355    /// use std::collections::VecDeque;
3356    ///
3357    /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
3358    ///          (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
3359    ///          (1, 21), (2, 34), (4, 55)].into();
3360    ///
3361    /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
3362    /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
3363    /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
3364    /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
3365    /// assert!(matches!(r, Ok(1..=4)));
3366    /// ```
3367    #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3368    #[inline]
3369    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
3370    where
3371        F: FnMut(&'a T) -> B,
3372        B: Ord,
3373    {
3374        self.binary_search_by(|k| f(k).cmp(b))
3375    }
3376
3377    /// Returns the index of the partition point according to the given predicate
3378    /// (the index of the first element of the second partition).
3379    ///
3380    /// The deque is assumed to be partitioned according to the given predicate.
3381    /// This means that all elements for which the predicate returns true are at the start of the deque
3382    /// and all elements for which the predicate returns false are at the end.
3383    /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
3384    /// (all odd numbers are at the start, all even at the end).
3385    ///
3386    /// If the deque is not partitioned, the returned result is unspecified and meaningless,
3387    /// as this method performs a kind of binary search.
3388    ///
3389    /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
3390    ///
3391    /// [`binary_search`]: VecDeque::binary_search
3392    /// [`binary_search_by`]: VecDeque::binary_search_by
3393    /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
3394    ///
3395    /// # Examples
3396    ///
3397    /// ```
3398    /// use std::collections::VecDeque;
3399    ///
3400    /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
3401    /// let i = deque.partition_point(|&x| x < 5);
3402    ///
3403    /// assert_eq!(i, 4);
3404    /// assert!(deque.iter().take(i).all(|&x| x < 5));
3405    /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
3406    /// ```
3407    ///
3408    /// If you want to insert an item to a sorted deque, while maintaining
3409    /// sort order:
3410    ///
3411    /// ```
3412    /// use std::collections::VecDeque;
3413    ///
3414    /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3415    /// let num = 42;
3416    /// let idx = deque.partition_point(|&x| x < num);
3417    /// deque.insert(idx, num);
3418    /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
3419    /// ```
3420    #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3421    pub fn partition_point<P>(&self, mut pred: P) -> usize
3422    where
3423        P: FnMut(&T) -> bool,
3424    {
3425        let (front, back) = self.as_slices();
3426
3427        if let Some(true) = back.first().map(&mut pred) {
3428            back.partition_point(pred) + front.len()
3429        } else {
3430            front.partition_point(pred)
3431        }
3432    }
3433}
3434
3435impl<T: Clone, A: Allocator> VecDeque<T, A> {
3436    /// Modifies the deque in-place so that `len()` is equal to new_len,
3437    /// either by removing excess elements from the back or by appending clones of `value`
3438    /// to the back.
3439    ///
3440    /// # Examples
3441    ///
3442    /// ```
3443    /// use std::collections::VecDeque;
3444    ///
3445    /// let mut buf = VecDeque::new();
3446    /// buf.push_back(5);
3447    /// buf.push_back(10);
3448    /// buf.push_back(15);
3449    /// assert_eq!(buf, [5, 10, 15]);
3450    ///
3451    /// buf.resize(2, 0);
3452    /// assert_eq!(buf, [5, 10]);
3453    ///
3454    /// buf.resize(5, 20);
3455    /// assert_eq!(buf, [5, 10, 20, 20, 20]);
3456    /// ```
3457    #[stable(feature = "deque_extras", since = "1.16.0")]
3458    pub fn resize(&mut self, new_len: usize, value: T) {
3459        if new_len > self.len() {
3460            let extra = new_len - self.len();
3461            self.extend(repeat_n(value, extra))
3462        } else {
3463            self.truncate(new_len);
3464        }
3465    }
3466
3467    /// Clones the elements at the range `src` and appends them to the end.
3468    ///
3469    /// # Panics
3470    ///
3471    /// Panics if the starting index is greater than the end index
3472    /// or if either index is greater than the length of the vector.
3473    ///
3474    /// # Examples
3475    ///
3476    /// ```
3477    /// #![feature(deque_extend_front)]
3478    /// use std::collections::VecDeque;
3479    ///
3480    /// let mut characters = VecDeque::from(['a', 'b', 'c', 'd', 'e']);
3481    /// characters.extend_from_within(2..);
3482    /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
3483    ///
3484    /// let mut numbers = VecDeque::from([0, 1, 2, 3, 4]);
3485    /// numbers.extend_from_within(..2);
3486    /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
3487    ///
3488    /// let mut strings = VecDeque::from([String::from("hello"), String::from("world"), String::from("!")]);
3489    /// strings.extend_from_within(1..=2);
3490    /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
3491    /// ```
3492    #[cfg(not(no_global_oom_handling))]
3493    #[unstable(feature = "deque_extend_front", issue = "146975")]
3494    pub fn extend_from_within<R>(&mut self, src: R)
3495    where
3496        R: RangeBounds<usize>,
3497    {
3498        let range = slice::range(src, ..self.len());
3499        self.reserve(range.len());
3500
3501        // SAFETY:
3502        // - `slice::range` guarantees that the given range is valid for indexing self
3503        // - at least `range.len()` additional space is available
3504        unsafe {
3505            self.spec_extend_from_within(range);
3506        }
3507    }
3508
3509    /// Clones the elements at the range `src` and prepends them to the front.
3510    ///
3511    /// # Panics
3512    ///
3513    /// Panics if the starting index is greater than the end index
3514    /// or if either index is greater than the length of the vector.
3515    ///
3516    /// # Examples
3517    ///
3518    /// ```
3519    /// #![feature(deque_extend_front)]
3520    /// use std::collections::VecDeque;
3521    ///
3522    /// let mut characters = VecDeque::from(['a', 'b', 'c', 'd', 'e']);
3523    /// characters.prepend_from_within(2..);
3524    /// assert_eq!(characters, ['c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']);
3525    ///
3526    /// let mut numbers = VecDeque::from([0, 1, 2, 3, 4]);
3527    /// numbers.prepend_from_within(..2);
3528    /// assert_eq!(numbers, [0, 1, 0, 1, 2, 3, 4]);
3529    ///
3530    /// let mut strings = VecDeque::from([String::from("hello"), String::from("world"), String::from("!")]);
3531    /// strings.prepend_from_within(1..=2);
3532    /// assert_eq!(strings, ["world", "!", "hello", "world", "!"]);
3533    /// ```
3534    #[cfg(not(no_global_oom_handling))]
3535    #[unstable(feature = "deque_extend_front", issue = "146975")]
3536    pub fn prepend_from_within<R>(&mut self, src: R)
3537    where
3538        R: RangeBounds<usize>,
3539    {
3540        let range = slice::range(src, ..self.len());
3541        self.reserve(range.len());
3542
3543        // SAFETY:
3544        // - `slice::range` guarantees that the given range is valid for indexing self
3545        // - at least `range.len()` additional space is available
3546        unsafe {
3547            self.spec_prepend_from_within(range);
3548        }
3549    }
3550}
3551
3552/// Associated functions have the following preconditions:
3553///
3554/// - `src` needs to be a valid range: `src.start <= src.end <= self.len()`.
3555/// - The buffer must have enough spare capacity: `self.capacity() - self.len() >= src.len()`.
3556#[cfg(not(no_global_oom_handling))]
3557trait SpecExtendFromWithin {
3558    unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
3559
3560    unsafe fn spec_prepend_from_within(&mut self, src: Range<usize>);
3561}
3562
3563#[cfg(not(no_global_oom_handling))]
3564impl<T: Clone, A: Allocator> SpecExtendFromWithin for VecDeque<T, A> {
3565    default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3566        let dst = self.len();
3567        let count = src.end - src.start;
3568        let src = src.start;
3569
3570        unsafe {
3571            // SAFETY:
3572            // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3573            // - Ranges are in bounds: guaranteed by the caller.
3574            let ranges = self.nonoverlapping_ranges(src, dst, count, self.head);
3575
3576            // `len` is updated after every clone to prevent leaking and
3577            // leave the deque in the right state when a clone implementation panics
3578
3579            for (src, dst, count) in ranges {
3580                for offset in 0..count {
3581                    dst.add(offset).write((*src.add(offset)).clone());
3582                    self.len += 1;
3583                }
3584            }
3585        }
3586    }
3587
3588    default unsafe fn spec_prepend_from_within(&mut self, src: Range<usize>) {
3589        let dst = 0;
3590        let count = src.end - src.start;
3591        let src = src.start + count;
3592
3593        let new_head = self.wrap_sub(self.head, count);
3594        let cap = self.capacity();
3595
3596        unsafe {
3597            // SAFETY:
3598            // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3599            // - Ranges are in bounds: guaranteed by the caller.
3600            let ranges = self.nonoverlapping_ranges(src, dst, count, new_head);
3601
3602            // Cloning is done in reverse because we prepend to the front of the deque,
3603            // we can't get holes in the *logical* buffer.
3604            // `head` and `len` are updated after every clone to prevent leaking and
3605            // leave the deque in the right state when a clone implementation panics
3606
3607            // Clone the first range
3608            let (src, dst, count) = ranges[1];
3609            for offset in (0..count).rev() {
3610                dst.add(offset).write((*src.add(offset)).clone());
3611                self.head = self.head.sub(1);
3612                self.len += 1;
3613            }
3614
3615            // Clone the second range
3616            let (src, dst, count) = ranges[0];
3617            let mut iter = (0..count).rev();
3618            if let Some(offset) = iter.next() {
3619                dst.add(offset).write((*src.add(offset)).clone());
3620                // After the first clone of the second range, wrap `head` around
3621                if self.head.is_zero() {
3622                    // SAFETY: the wrapped index may be temporarily equal to the capacity even if it
3623                    // is not zero, because we subtract it one line below.
3624                    self.head = WrappedIndex::from_arbitrary_number(cap);
3625                }
3626                self.head = self.head.sub(1);
3627                self.len += 1;
3628
3629                // Continue like normal
3630                for offset in iter {
3631                    dst.add(offset).write((*src.add(offset)).clone());
3632                    self.head = self.head.sub(1);
3633                    self.len += 1;
3634                }
3635            }
3636        }
3637    }
3638}
3639
3640#[cfg(not(no_global_oom_handling))]
3641impl<T: TrivialClone, A: Allocator> SpecExtendFromWithin for VecDeque<T, A> {
3642    unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3643        let dst = self.len();
3644        let count = src.end - src.start;
3645        let src = src.start;
3646
3647        unsafe {
3648            // SAFETY:
3649            // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3650            // - Ranges are in bounds: guaranteed by the caller.
3651            let ranges = self.nonoverlapping_ranges(src, dst, count, self.head);
3652            for (src, dst, count) in ranges {
3653                ptr::copy_nonoverlapping(src, dst, count);
3654            }
3655        }
3656
3657        // SAFETY:
3658        // - The elements were just initialized by `copy_nonoverlapping`
3659        self.len += count;
3660    }
3661
3662    unsafe fn spec_prepend_from_within(&mut self, src: Range<usize>) {
3663        let dst = 0;
3664        let count = src.end - src.start;
3665        let src = src.start + count;
3666
3667        let new_head = self.wrap_sub(self.head, count);
3668
3669        unsafe {
3670            // SAFETY:
3671            // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3672            // - Ranges are in bounds: guaranteed by the caller.
3673            let ranges = self.nonoverlapping_ranges(src, dst, count, new_head);
3674            for (src, dst, count) in ranges {
3675                ptr::copy_nonoverlapping(src, dst, count);
3676            }
3677        }
3678
3679        // SAFETY:
3680        // - The elements were just initialized by `copy_nonoverlapping`
3681        self.head = new_head;
3682        self.len += count;
3683    }
3684}
3685
3686use index::{WrappedIndex, wrap_index};
3687
3688// The code is separated into a module to make it harder to construct a BufferIndex without
3689// going through wrapping.
3690mod index {
3691    use core::cmp::Ordering;
3692
3693    /// Returns the index in the underlying buffer for a given logical element index.
3694    #[inline]
3695    pub(super) fn wrap_index(logical_index: usize, capacity: usize) -> WrappedIndex {
3696        debug_assert!(
3697            (logical_index == 0 && capacity == 0)
3698                || logical_index < capacity
3699                || (logical_index - capacity) < capacity
3700        );
3701        if logical_index >= capacity {
3702            WrappedIndex(logical_index - capacity)
3703        } else {
3704            WrappedIndex(logical_index)
3705        }
3706    }
3707
3708    /// Represents an index that can be safely used to index the VecDeque buffer.
3709    /// It exists as a separate type to avoid passing logical (unwrapped) indices to various
3710    /// VecDeque functions by accident.
3711    ///
3712    /// The invariant of this index is that it is always < VecDeque capacity, unless the VecDeque
3713    /// is empty (in that case the index can be 0 when the capacity is 0).
3714    #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
3715    #[repr(transparent)]
3716    pub(super) struct WrappedIndex(usize);
3717
3718    impl WrappedIndex {
3719        /// The newly constructed index has to be in-bounds for the VecDeque
3720        /// that uses the index.
3721        #[inline(always)]
3722        pub(super) fn from_arbitrary_number(index: usize) -> Self {
3723            Self(index)
3724        }
3725
3726        /// Safety invariant: the newly constructed index must still be in-bounds for the VecDeque
3727        #[inline(always)]
3728        pub(super) unsafe fn add(self, offset: usize) -> Self {
3729            Self(self.0 + offset)
3730        }
3731
3732        /// Safety invariant: the newly constructed index must still be in-bounds for the VecDeque
3733        #[inline(always)]
3734        pub(super) unsafe fn sub(self, offset: usize) -> Self {
3735            debug_assert!(self.0 >= offset);
3736            Self(self.0 - offset)
3737        }
3738
3739        #[inline(always)]
3740        pub(super) const fn zero() -> Self {
3741            Self(0)
3742        }
3743
3744        #[inline(always)]
3745        pub(super) fn abs_diff(self, other: Self) -> usize {
3746            self.0.abs_diff(other.0)
3747        }
3748
3749        #[inline(always)]
3750        pub(super) fn as_index(self) -> usize {
3751            self.0
3752        }
3753
3754        #[inline(always)]
3755        pub(super) fn is_zero(self) -> bool {
3756            self.0 == 0
3757        }
3758    }
3759
3760    impl core::ops::Add<usize> for WrappedIndex {
3761        // The output might not be wrapped anymore
3762        type Output = usize;
3763
3764        #[inline(always)]
3765        fn add(self, rhs: usize) -> Self::Output {
3766            self.0 + rhs
3767        }
3768    }
3769
3770    impl core::fmt::Display for WrappedIndex {
3771        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3772            self.0.fmt(f)
3773        }
3774    }
3775
3776    impl core::cmp::PartialEq<usize> for WrappedIndex {
3777        #[inline(always)]
3778        fn eq(&self, other: &usize) -> bool {
3779            self.0.eq(other)
3780        }
3781    }
3782
3783    impl core::cmp::PartialOrd<usize> for WrappedIndex {
3784        #[inline(always)]
3785        fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
3786            self.0.partial_cmp(other)
3787        }
3788    }
3789}
3790
3791#[stable(feature = "rust1", since = "1.0.0")]
3792impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
3793    fn eq(&self, other: &Self) -> bool {
3794        if self.len != other.len() {
3795            return false;
3796        }
3797        let (sa, sb) = self.as_slices();
3798        let (oa, ob) = other.as_slices();
3799        if sa.len() == oa.len() {
3800            sa == oa && sb == ob
3801        } else if sa.len() < oa.len() {
3802            // Always divisible in three sections, for example:
3803            // self:  [a b c|d e f]
3804            // other: [0 1 2 3|4 5]
3805            // front = 3, mid = 1,
3806            // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
3807            let front = sa.len();
3808            let mid = oa.len() - front;
3809
3810            let (oa_front, oa_mid) = oa.split_at(front);
3811            let (sb_mid, sb_back) = sb.split_at(mid);
3812            debug_assert_eq!(sa.len(), oa_front.len());
3813            debug_assert_eq!(sb_mid.len(), oa_mid.len());
3814            debug_assert_eq!(sb_back.len(), ob.len());
3815            sa == oa_front && sb_mid == oa_mid && sb_back == ob
3816        } else {
3817            let front = oa.len();
3818            let mid = sa.len() - front;
3819
3820            let (sa_front, sa_mid) = sa.split_at(front);
3821            let (ob_mid, ob_back) = ob.split_at(mid);
3822            debug_assert_eq!(sa_front.len(), oa.len());
3823            debug_assert_eq!(sa_mid.len(), ob_mid.len());
3824            debug_assert_eq!(sb.len(), ob_back.len());
3825            sa_front == oa && sa_mid == ob_mid && sb == ob_back
3826        }
3827    }
3828}
3829
3830#[stable(feature = "rust1", since = "1.0.0")]
3831impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
3832
3833__impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
3834__impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
3835__impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
3836__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
3837__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
3838__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
3839
3840#[stable(feature = "rust1", since = "1.0.0")]
3841impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
3842    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3843        self.iter().partial_cmp(other.iter())
3844    }
3845}
3846
3847#[stable(feature = "rust1", since = "1.0.0")]
3848impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
3849    #[inline]
3850    fn cmp(&self, other: &Self) -> Ordering {
3851        self.iter().cmp(other.iter())
3852    }
3853}
3854
3855#[stable(feature = "rust1", since = "1.0.0")]
3856impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
3857    fn hash<H: Hasher>(&self, state: &mut H) {
3858        state.write_length_prefix(self.len);
3859        // It's not possible to use Hash::hash_slice on slices
3860        // returned by as_slices method as their length can vary
3861        // in otherwise identical deques.
3862        //
3863        // Hasher only guarantees equivalence for the exact same
3864        // set of calls to its methods.
3865        self.iter().for_each(|elem| elem.hash(state));
3866    }
3867}
3868
3869#[stable(feature = "rust1", since = "1.0.0")]
3870impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
3871    type Output = T;
3872
3873    #[inline]
3874    fn index(&self, index: usize) -> &T {
3875        self.get(index).expect("out of bounds access")
3876    }
3877}
3878
3879#[stable(feature = "rust1", since = "1.0.0")]
3880impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
3881    #[inline]
3882    fn index_mut(&mut self, index: usize) -> &mut T {
3883        self.get_mut(index).expect("out of bounds access")
3884    }
3885}
3886
3887#[stable(feature = "rust1", since = "1.0.0")]
3888impl<T> FromIterator<T> for VecDeque<T> {
3889    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
3890        SpecFromIter::spec_from_iter(iter.into_iter())
3891    }
3892}
3893
3894#[stable(feature = "rust1", since = "1.0.0")]
3895impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
3896    type Item = T;
3897    type IntoIter = IntoIter<T, A>;
3898
3899    /// Consumes the deque into a front-to-back iterator yielding elements by
3900    /// value.
3901    fn into_iter(self) -> IntoIter<T, A> {
3902        IntoIter::new(self)
3903    }
3904}
3905
3906#[stable(feature = "rust1", since = "1.0.0")]
3907impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
3908    type Item = &'a T;
3909    type IntoIter = Iter<'a, T>;
3910
3911    fn into_iter(self) -> Iter<'a, T> {
3912        self.iter()
3913    }
3914}
3915
3916#[stable(feature = "rust1", since = "1.0.0")]
3917impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
3918    type Item = &'a mut T;
3919    type IntoIter = IterMut<'a, T>;
3920
3921    fn into_iter(self) -> IterMut<'a, T> {
3922        self.iter_mut()
3923    }
3924}
3925
3926#[stable(feature = "rust1", since = "1.0.0")]
3927impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
3928    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
3929        <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter());
3930    }
3931
3932    #[inline]
3933    fn extend_one(&mut self, elem: T) {
3934        self.push_back(elem);
3935    }
3936
3937    #[inline]
3938    fn extend_reserve(&mut self, additional: usize) {
3939        self.reserve(additional);
3940    }
3941
3942    #[inline]
3943    unsafe fn extend_one_unchecked(&mut self, item: T) {
3944        // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3945        unsafe {
3946            self.push_unchecked(item);
3947        }
3948    }
3949}
3950
3951#[stable(feature = "extend_ref", since = "1.2.0")]
3952impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
3953    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3954        self.spec_extend(iter.into_iter());
3955    }
3956
3957    #[inline]
3958    fn extend_one(&mut self, &elem: &'a T) {
3959        self.push_back(elem);
3960    }
3961
3962    #[inline]
3963    fn extend_reserve(&mut self, additional: usize) {
3964        self.reserve(additional);
3965    }
3966
3967    #[inline]
3968    unsafe fn extend_one_unchecked(&mut self, &item: &'a T) {
3969        // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3970        unsafe {
3971            self.push_unchecked(item);
3972        }
3973    }
3974}
3975
3976#[stable(feature = "rust1", since = "1.0.0")]
3977impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
3978    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3979        f.debug_list().entries(self.iter()).finish()
3980    }
3981}
3982
3983#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3984impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
3985    /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3986    ///
3987    /// [`Vec<T>`]: crate::vec::Vec
3988    /// [`VecDeque<T>`]: crate::collections::VecDeque
3989    ///
3990    /// This conversion is guaranteed to run in *O*(1) time
3991    /// and to not re-allocate the `Vec`'s buffer or allocate
3992    /// any additional memory.
3993    #[inline]
3994    fn from(other: Vec<T, A>) -> Self {
3995        let (ptr, len, cap, alloc) = other.into_raw_parts_with_allocator();
3996        Self {
3997            head: WrappedIndex::zero(),
3998            len,
3999            buf: unsafe { RawVec::from_raw_parts_in(ptr, cap, alloc) },
4000        }
4001    }
4002}
4003
4004#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
4005impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
4006    /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
4007    ///
4008    /// [`Vec<T>`]: crate::vec::Vec
4009    /// [`VecDeque<T>`]: crate::collections::VecDeque
4010    ///
4011    /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
4012    /// the circular buffer doesn't happen to be at the beginning of the allocation.
4013    ///
4014    /// # Examples
4015    ///
4016    /// ```
4017    /// use std::collections::VecDeque;
4018    ///
4019    /// // This one is *O*(1).
4020    /// let deque: VecDeque<_> = (1..5).collect();
4021    /// let ptr = deque.as_slices().0.as_ptr();
4022    /// let vec = Vec::from(deque);
4023    /// assert_eq!(vec, [1, 2, 3, 4]);
4024    /// assert_eq!(vec.as_ptr(), ptr);
4025    ///
4026    /// // This one needs data rearranging.
4027    /// let mut deque: VecDeque<_> = (1..5).collect();
4028    /// deque.push_front(9);
4029    /// deque.push_front(8);
4030    /// let ptr = deque.as_slices().1.as_ptr();
4031    /// let vec = Vec::from(deque);
4032    /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
4033    /// assert_eq!(vec.as_ptr(), ptr);
4034    /// ```
4035    fn from(mut other: VecDeque<T, A>) -> Self {
4036        other.make_contiguous();
4037
4038        unsafe {
4039            let other = ManuallyDrop::new(other);
4040            let buf = other.buf.ptr();
4041            let len = other.len();
4042            let cap = other.capacity();
4043            let alloc = ptr::read(other.allocator());
4044
4045            if !other.head.is_zero() {
4046                ptr::copy(buf.add(other.head.as_index()), buf, len);
4047            }
4048            Vec::from_raw_parts_in(buf, len, cap, alloc)
4049        }
4050    }
4051}
4052
4053#[stable(feature = "std_collections_from_array", since = "1.56.0")]
4054impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
4055    /// Converts a `[T; N]` into a `VecDeque<T>`.
4056    ///
4057    /// ```
4058    /// use std::collections::VecDeque;
4059    ///
4060    /// let deq1 = VecDeque::from([1, 2, 3, 4]);
4061    /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
4062    /// assert_eq!(deq1, deq2);
4063    /// ```
4064    fn from(arr: [T; N]) -> Self {
4065        let mut deq = VecDeque::with_capacity(N);
4066        let arr = ManuallyDrop::new(arr);
4067        if !<T>::IS_ZST {
4068            // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
4069            unsafe {
4070                ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);
4071            }
4072        }
4073        deq.head = WrappedIndex::zero();
4074        deq.len = N;
4075        deq
4076    }
4077}