Skip to main content

alloc/collections/vec_deque/
mod.rs

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