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