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