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