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