Thanks to visit codestin.com
Credit goes to doc.rust-lang.org

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