1 //! A double-ended queue (deque) implemented with a growable ring buffer.
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.
8 #![stable(feature = "rust1", since = "1.0.0")]
10 use core::cmp::{self, Ordering};
12 use core::hash::{Hash, Hasher};
13 use core::iter::{repeat_with, FromIterator};
14 use core::marker::PhantomData;
15 use core::mem::{self, ManuallyDrop, MaybeUninit};
16 use core::ops::{Index, IndexMut, Range, RangeBounds};
17 use core::ptr::{self, NonNull};
20 use crate::alloc::{Allocator, Global};
21 use crate::collections::TryReserveError;
22 use crate::collections::TryReserveErrorKind;
23 use crate::raw_vec::RawVec;
29 #[stable(feature = "drain", since = "1.6.0")]
30 pub use self::drain::Drain;
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use self::iter_mut::IterMut;
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub use self::into_iter::IntoIter;
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub use self::iter::Iter;
49 use self::pair_slices::PairSlices;
53 use self::ring_slices::RingSlices;
60 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
61 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
63 const MAXIMUM_ZST_CAPACITY: usize = 1 << (usize::BITS - 1); // Largest possible power of two
65 /// A double-ended queue implemented with a growable ring buffer.
67 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
68 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
69 /// push onto the back in this manner, and iterating over `VecDeque` goes front
72 /// A `VecDeque` with a known list of items can be initialized from an array:
75 /// use std::collections::VecDeque;
77 /// let deq = VecDeque::from([-1, 0, 1]);
80 /// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
81 /// in memory. If you want to access the elements as a single slice, such as for
82 /// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
83 /// so that its elements do not wrap, and returns a mutable slice to the
84 /// now-contiguous element sequence.
86 /// [`push_back`]: VecDeque::push_back
87 /// [`pop_front`]: VecDeque::pop_front
88 /// [`extend`]: VecDeque::extend
89 /// [`append`]: VecDeque::append
90 /// [`make_contiguous`]: VecDeque::make_contiguous
91 #[cfg_attr(not(test), rustc_diagnostic_item = "VecDeque")]
92 #[stable(feature = "rust1", since = "1.0.0")]
93 #[rustc_insignificant_dtor]
96 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
98 // tail and head are pointers into the buffer. Tail always points
99 // to the first element that could be read, Head always points
100 // to where data should be written.
101 // If tail == head the buffer is empty. The length of the ringbuffer
102 // is defined as the distance between the two.
108 #[stable(feature = "rust1", since = "1.0.0")]
109 impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A> {
110 fn clone(&self) -> Self {
111 let mut deq = Self::with_capacity_in(self.len(), self.allocator().clone());
112 deq.extend(self.iter().cloned());
116 fn clone_from(&mut self, other: &Self) {
117 self.truncate(other.len());
119 let mut iter = PairSlices::from(self, other);
120 while let Some((dst, src)) = iter.next() {
121 dst.clone_from_slice(&src);
124 if iter.has_remainder() {
125 for remainder in iter.remainder() {
126 self.extend(remainder.iter().cloned());
132 #[stable(feature = "rust1", since = "1.0.0")]
133 unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
135 /// Runs the destructor for all items in the slice when it gets dropped (normally or
136 /// during unwinding).
137 struct Dropper<'a, T>(&'a mut [T]);
139 impl<'a, T> Drop for Dropper<'a, T> {
142 ptr::drop_in_place(self.0);
147 let (front, back) = self.as_mut_slices();
149 let _back_dropper = Dropper(back);
151 ptr::drop_in_place(front);
153 // RawVec handles deallocation
157 #[stable(feature = "rust1", since = "1.0.0")]
158 impl<T> Default for VecDeque<T> {
159 /// Creates an empty deque.
161 fn default() -> VecDeque<T> {
166 impl<T, A: Allocator> VecDeque<T, A> {
167 /// Marginally more convenient
169 fn ptr(&self) -> *mut T {
173 /// Marginally more convenient
175 fn cap(&self) -> usize {
176 if mem::size_of::<T>() == 0 {
177 // For zero sized types, we are always at maximum capacity
184 /// Turn ptr into a slice, since the elements of the backing buffer may be uninitialized,
185 /// we will return a slice of [`MaybeUninit<T>`].
187 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
188 /// incorrect usage of this method.
190 /// [zeroed]: mem::MaybeUninit::zeroed
192 unsafe fn buffer_as_slice(&self) -> &[MaybeUninit<T>] {
193 unsafe { slice::from_raw_parts(self.ptr() as *mut MaybeUninit<T>, self.cap()) }
196 /// Turn ptr into a mut slice, since the elements of the backing buffer may be uninitialized,
197 /// we will return a slice of [`MaybeUninit<T>`].
199 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
200 /// incorrect usage of this method.
202 /// [zeroed]: mem::MaybeUninit::zeroed
204 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [MaybeUninit<T>] {
205 unsafe { slice::from_raw_parts_mut(self.ptr() as *mut MaybeUninit<T>, self.cap()) }
208 /// Moves an element out of the buffer
210 unsafe fn buffer_read(&mut self, off: usize) -> T {
211 unsafe { ptr::read(self.ptr().add(off)) }
214 /// Writes an element into the buffer, moving it.
216 unsafe fn buffer_write(&mut self, off: usize, value: T) {
218 ptr::write(self.ptr().add(off), value);
222 /// Returns `true` if the buffer is at full capacity.
224 fn is_full(&self) -> bool {
225 self.cap() - self.len() == 1
228 /// Returns the index in the underlying buffer for a given logical element
231 fn wrap_index(&self, idx: usize) -> usize {
232 wrap_index(idx, self.cap())
235 /// Returns the index in the underlying buffer for a given logical element
238 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
239 wrap_index(idx.wrapping_add(addend), self.cap())
242 /// Returns the index in the underlying buffer for a given logical element
243 /// index - subtrahend.
245 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
246 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
249 /// Copies a contiguous block of memory len long from src to dst
251 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
253 dst + len <= self.cap(),
254 "cpy dst={} src={} len={} cap={}",
261 src + len <= self.cap(),
262 "cpy dst={} src={} len={} cap={}",
269 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
273 /// Copies a contiguous block of memory len long from src to dst
275 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
277 dst + len <= self.cap(),
278 "cno dst={} src={} len={} cap={}",
285 src + len <= self.cap(),
286 "cno dst={} src={} len={} cap={}",
293 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
297 /// Copies a potentially wrapping block of memory len long from src to dest.
298 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
299 /// most one continuous overlapping region between src and dest).
300 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
302 fn diff(a: usize, b: usize) -> usize {
303 if a <= b { b - a } else { a - b }
306 cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
307 "wrc dst={} src={} len={} cap={}",
314 if src == dst || len == 0 {
318 let dst_after_src = self.wrap_sub(dst, src) < len;
320 let src_pre_wrap_len = self.cap() - src;
321 let dst_pre_wrap_len = self.cap() - dst;
322 let src_wraps = src_pre_wrap_len < len;
323 let dst_wraps = dst_pre_wrap_len < len;
325 match (dst_after_src, src_wraps, dst_wraps) {
326 (_, false, false) => {
327 // src doesn't wrap, dst doesn't wrap
330 // 1 [_ _ A A B B C C _]
331 // 2 [_ _ A A A A B B _]
335 self.copy(dst, src, len);
338 (false, false, true) => {
339 // dst before src, src doesn't wrap, dst wraps
342 // 1 [A A B B _ _ _ C C]
343 // 2 [A A B B _ _ _ A A]
344 // 3 [B B B B _ _ _ A A]
348 self.copy(dst, src, dst_pre_wrap_len);
349 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
352 (true, false, true) => {
353 // src before dst, src doesn't wrap, dst wraps
356 // 1 [C C _ _ _ A A B B]
357 // 2 [B B _ _ _ A A B B]
358 // 3 [B B _ _ _ A A A A]
362 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
363 self.copy(dst, src, dst_pre_wrap_len);
366 (false, true, false) => {
367 // dst before src, src wraps, dst doesn't wrap
370 // 1 [C C _ _ _ A A B B]
371 // 2 [C C _ _ _ B B B B]
372 // 3 [C C _ _ _ B B C C]
376 self.copy(dst, src, src_pre_wrap_len);
377 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
380 (true, true, false) => {
381 // src before dst, src wraps, dst doesn't wrap
384 // 1 [A A B B _ _ _ C C]
385 // 2 [A A A A _ _ _ C C]
386 // 3 [C C A A _ _ _ C C]
390 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
391 self.copy(dst, src, src_pre_wrap_len);
394 (false, true, true) => {
395 // dst before src, src wraps, dst wraps
398 // 1 [A B C D _ E F G H]
399 // 2 [A B C D _ E G H H]
400 // 3 [A B C D _ E G H A]
401 // 4 [B C C D _ E G H A]
404 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
405 let delta = dst_pre_wrap_len - src_pre_wrap_len;
407 self.copy(dst, src, src_pre_wrap_len);
408 self.copy(dst + src_pre_wrap_len, 0, delta);
409 self.copy(0, delta, len - dst_pre_wrap_len);
412 (true, true, true) => {
413 // src before dst, src wraps, dst wraps
416 // 1 [A B C D _ E F G H]
417 // 2 [A A B D _ E F G H]
418 // 3 [H A B D _ E F G H]
419 // 4 [H A B D _ E F F G]
422 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
423 let delta = src_pre_wrap_len - dst_pre_wrap_len;
425 self.copy(delta, 0, len - src_pre_wrap_len);
426 self.copy(0, self.cap() - delta, delta);
427 self.copy(dst, src, dst_pre_wrap_len);
433 /// Copies all values from `src` to `dst`, wrapping around if needed.
434 /// Assumes capacity is sufficient.
436 unsafe fn copy_slice(&mut self, dst: usize, src: &[T]) {
437 debug_assert!(src.len() <= self.cap());
438 let head_room = self.cap() - dst;
439 if src.len() <= head_room {
441 ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst), src.len());
444 let (left, right) = src.split_at(head_room);
446 ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst), left.len());
447 ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
452 /// Frobs the head and tail sections around to handle the fact that we
453 /// just reallocated. Unsafe because it trusts old_capacity.
455 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
456 let new_capacity = self.cap();
458 // Move the shortest contiguous section of the ring buffer
460 // [o o o o o o o . ]
462 // A [o o o o o o o . . . . . . . . . ]
464 // [o o . o o o o o ]
466 // B [. . . o o o o o o o . . . . . . ]
468 // [o o o o o . o o ]
470 // C [o o o o o . . . . . . . . . o o ]
472 if self.tail <= self.head {
475 } else if self.head < old_capacity - self.tail {
478 self.copy_nonoverlapping(old_capacity, 0, self.head);
480 self.head += old_capacity;
481 debug_assert!(self.head > self.tail);
484 let new_tail = new_capacity - (old_capacity - self.tail);
486 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
488 self.tail = new_tail;
489 debug_assert!(self.head < self.tail);
491 debug_assert!(self.head < self.cap());
492 debug_assert!(self.tail < self.cap());
493 debug_assert!(self.cap().count_ones() == 1);
497 impl<T> VecDeque<T> {
498 /// Creates an empty deque.
503 /// use std::collections::VecDeque;
505 /// let deque: VecDeque<u32> = VecDeque::new();
508 #[stable(feature = "rust1", since = "1.0.0")]
510 pub fn new() -> VecDeque<T> {
511 VecDeque::new_in(Global)
514 /// Creates an empty deque with space for at least `capacity` elements.
519 /// use std::collections::VecDeque;
521 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
524 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
527 Self::with_capacity_in(capacity, Global)
531 impl<T, A: Allocator> VecDeque<T, A> {
532 /// Creates an empty deque.
537 /// use std::collections::VecDeque;
539 /// let deque: VecDeque<u32> = VecDeque::new();
542 #[unstable(feature = "allocator_api", issue = "32838")]
543 pub fn new_in(alloc: A) -> VecDeque<T, A> {
544 VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc)
547 /// Creates an empty deque with space for at least `capacity` elements.
552 /// use std::collections::VecDeque;
554 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
556 #[unstable(feature = "allocator_api", issue = "32838")]
557 pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
558 assert!(capacity < 1_usize << usize::BITS - 1, "capacity overflow");
559 // +1 since the ringbuffer always leaves one space empty
560 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
562 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) }
565 /// Provides a reference to the element at the given index.
567 /// Element at index 0 is the front of the queue.
572 /// use std::collections::VecDeque;
574 /// let mut buf = VecDeque::new();
575 /// buf.push_back(3);
576 /// buf.push_back(4);
577 /// buf.push_back(5);
578 /// assert_eq!(buf.get(1), Some(&4));
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn get(&self, index: usize) -> Option<&T> {
582 if index < self.len() {
583 let idx = self.wrap_add(self.tail, index);
584 unsafe { Some(&*self.ptr().add(idx)) }
590 /// Provides a mutable reference to the element at the given index.
592 /// Element at index 0 is the front of the queue.
597 /// use std::collections::VecDeque;
599 /// let mut buf = VecDeque::new();
600 /// buf.push_back(3);
601 /// buf.push_back(4);
602 /// buf.push_back(5);
603 /// if let Some(elem) = buf.get_mut(1) {
607 /// assert_eq!(buf[1], 7);
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
611 if index < self.len() {
612 let idx = self.wrap_add(self.tail, index);
613 unsafe { Some(&mut *self.ptr().add(idx)) }
619 /// Swaps elements at indices `i` and `j`.
621 /// `i` and `j` may be equal.
623 /// Element at index 0 is the front of the queue.
627 /// Panics if either index is out of bounds.
632 /// use std::collections::VecDeque;
634 /// let mut buf = VecDeque::new();
635 /// buf.push_back(3);
636 /// buf.push_back(4);
637 /// buf.push_back(5);
638 /// assert_eq!(buf, [3, 4, 5]);
640 /// assert_eq!(buf, [5, 4, 3]);
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn swap(&mut self, i: usize, j: usize) {
644 assert!(i < self.len());
645 assert!(j < self.len());
646 let ri = self.wrap_add(self.tail, i);
647 let rj = self.wrap_add(self.tail, j);
648 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
651 /// Returns the number of elements the deque can hold without
657 /// use std::collections::VecDeque;
659 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
660 /// assert!(buf.capacity() >= 10);
663 #[stable(feature = "rust1", since = "1.0.0")]
664 pub fn capacity(&self) -> usize {
668 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
669 /// given deque. Does nothing if the capacity is already sufficient.
671 /// Note that the allocator may give the collection more space than it requests. Therefore
672 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
673 /// insertions are expected.
677 /// Panics if the new capacity overflows `usize`.
682 /// use std::collections::VecDeque;
684 /// let mut buf: VecDeque<i32> = [1].into();
685 /// buf.reserve_exact(10);
686 /// assert!(buf.capacity() >= 11);
689 /// [`reserve`]: VecDeque::reserve
690 #[stable(feature = "rust1", since = "1.0.0")]
691 pub fn reserve_exact(&mut self, additional: usize) {
692 self.reserve(additional);
695 /// Reserves capacity for at least `additional` more elements to be inserted in the given
696 /// deque. The collection may reserve more space to avoid frequent reallocations.
700 /// Panics if the new capacity overflows `usize`.
705 /// use std::collections::VecDeque;
707 /// let mut buf: VecDeque<i32> = [1].into();
709 /// assert!(buf.capacity() >= 11);
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn reserve(&mut self, additional: usize) {
713 let old_cap = self.cap();
714 let used_cap = self.len() + 1;
715 let new_cap = used_cap
716 .checked_add(additional)
717 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
718 .expect("capacity overflow");
720 if new_cap > old_cap {
721 self.buf.reserve_exact(used_cap, new_cap - used_cap);
723 self.handle_capacity_increase(old_cap);
728 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
729 /// be inserted in the given deque. After calling `try_reserve_exact`,
730 /// capacity will be greater than or equal to `self.len() + additional`.
731 /// Does nothing if the capacity is already sufficient.
733 /// Note that the allocator may give the collection more space than it
734 /// requests. Therefore, capacity can not be relied upon to be precisely
735 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
737 /// [`try_reserve`]: VecDeque::try_reserve
741 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
747 /// use std::collections::TryReserveError;
748 /// use std::collections::VecDeque;
750 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
751 /// let mut output = VecDeque::new();
753 /// // Pre-reserve the memory, exiting if we can't
754 /// output.try_reserve_exact(data.len())?;
756 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
757 /// output.extend(data.iter().map(|&val| {
758 /// val * 2 + 5 // very complicated
763 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
765 #[stable(feature = "try_reserve", since = "1.57.0")]
766 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
767 self.try_reserve(additional)
770 /// Tries to reserve capacity for at least `additional` more elements to be inserted
771 /// in the given deque. The collection may reserve more space to avoid
772 /// frequent reallocations. After calling `try_reserve`, capacity will be
773 /// greater than or equal to `self.len() + additional`. Does nothing if
774 /// capacity is already sufficient.
778 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
784 /// use std::collections::TryReserveError;
785 /// use std::collections::VecDeque;
787 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
788 /// let mut output = VecDeque::new();
790 /// // Pre-reserve the memory, exiting if we can't
791 /// output.try_reserve(data.len())?;
793 /// // Now we know this can't OOM in the middle of our complex work
794 /// output.extend(data.iter().map(|&val| {
795 /// val * 2 + 5 // very complicated
800 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
802 #[stable(feature = "try_reserve", since = "1.57.0")]
803 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
804 let old_cap = self.cap();
805 let used_cap = self.len() + 1;
806 let new_cap = used_cap
807 .checked_add(additional)
808 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
809 .ok_or(TryReserveErrorKind::CapacityOverflow)?;
811 if new_cap > old_cap {
812 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
814 self.handle_capacity_increase(old_cap);
820 /// Shrinks the capacity of the deque as much as possible.
822 /// It will drop down as close as possible to the length but the allocator may still inform the
823 /// deque that there is space for a few more elements.
828 /// use std::collections::VecDeque;
830 /// let mut buf = VecDeque::with_capacity(15);
831 /// buf.extend(0..4);
832 /// assert_eq!(buf.capacity(), 15);
833 /// buf.shrink_to_fit();
834 /// assert!(buf.capacity() >= 4);
836 #[stable(feature = "deque_extras_15", since = "1.5.0")]
837 pub fn shrink_to_fit(&mut self) {
841 /// Shrinks the capacity of the deque with a lower bound.
843 /// The capacity will remain at least as large as both the length
844 /// and the supplied value.
846 /// If the current capacity is less than the lower limit, this is a no-op.
851 /// use std::collections::VecDeque;
853 /// let mut buf = VecDeque::with_capacity(15);
854 /// buf.extend(0..4);
855 /// assert_eq!(buf.capacity(), 15);
856 /// buf.shrink_to(6);
857 /// assert!(buf.capacity() >= 6);
858 /// buf.shrink_to(0);
859 /// assert!(buf.capacity() >= 4);
861 #[stable(feature = "shrink_to", since = "1.56.0")]
862 pub fn shrink_to(&mut self, min_capacity: usize) {
863 let min_capacity = cmp::min(min_capacity, self.capacity());
864 // We don't have to worry about an overflow as neither `self.len()` nor `self.capacity()`
865 // can ever be `usize::MAX`. +1 as the ringbuffer always leaves one space empty.
866 let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
867 .next_power_of_two();
869 if target_cap < self.cap() {
870 // There are three cases of interest:
871 // All elements are out of desired bounds
872 // Elements are contiguous, and head is out of desired bounds
873 // Elements are discontiguous, and tail is out of desired bounds
875 // At all other times, element positions are unaffected.
877 // Indicates that elements at the head should be moved.
878 let head_outside = self.head == 0 || self.head >= target_cap;
879 // Move elements from out of desired bounds (positions after target_cap)
880 if self.tail >= target_cap && head_outside {
882 // [. . . . . . . . o o o o o o o . ]
884 // [o o o o o o o . ]
886 self.copy_nonoverlapping(0, self.tail, self.len());
888 self.head = self.len();
890 } else if self.tail != 0 && self.tail < target_cap && head_outside {
892 // [. . . o o o o o o o . . . . . . ]
894 // [o o . o o o o o ]
895 let len = self.wrap_sub(self.head, target_cap);
897 self.copy_nonoverlapping(0, target_cap, len);
900 debug_assert!(self.head < self.tail);
901 } else if self.tail >= target_cap {
903 // [o o o o o . . . . . . . . . o o ]
905 // [o o o o o . o o ]
906 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
907 let len = self.cap() - self.tail;
908 let new_tail = target_cap - len;
910 self.copy_nonoverlapping(new_tail, self.tail, len);
912 self.tail = new_tail;
913 debug_assert!(self.head < self.tail);
916 self.buf.shrink_to_fit(target_cap);
918 debug_assert!(self.head < self.cap());
919 debug_assert!(self.tail < self.cap());
920 debug_assert!(self.cap().count_ones() == 1);
924 /// Shortens the deque, keeping the first `len` elements and dropping
927 /// If `len` is greater than the deque's current length, this has no
933 /// use std::collections::VecDeque;
935 /// let mut buf = VecDeque::new();
936 /// buf.push_back(5);
937 /// buf.push_back(10);
938 /// buf.push_back(15);
939 /// assert_eq!(buf, [5, 10, 15]);
941 /// assert_eq!(buf, [5]);
943 #[stable(feature = "deque_extras", since = "1.16.0")]
944 pub fn truncate(&mut self, len: usize) {
945 /// Runs the destructor for all items in the slice when it gets dropped (normally or
946 /// during unwinding).
947 struct Dropper<'a, T>(&'a mut [T]);
949 impl<'a, T> Drop for Dropper<'a, T> {
952 ptr::drop_in_place(self.0);
959 // * Any slice passed to `drop_in_place` is valid; the second case has
960 // `len <= front.len()` and returning on `len > self.len()` ensures
961 // `begin <= back.len()` in the first case
962 // * The head of the VecDeque is moved before calling `drop_in_place`,
963 // so no value is dropped twice if `drop_in_place` panics
965 if len > self.len() {
968 let num_dropped = self.len() - len;
969 let (front, back) = self.as_mut_slices();
970 if len > front.len() {
971 let begin = len - front.len();
972 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
973 self.head = self.wrap_sub(self.head, num_dropped);
974 ptr::drop_in_place(drop_back);
976 let drop_back = back as *mut _;
977 let drop_front = front.get_unchecked_mut(len..) as *mut _;
978 self.head = self.wrap_sub(self.head, num_dropped);
980 // Make sure the second half is dropped even when a destructor
981 // in the first one panics.
982 let _back_dropper = Dropper(&mut *drop_back);
983 ptr::drop_in_place(drop_front);
988 /// Returns a reference to the underlying allocator.
989 #[unstable(feature = "allocator_api", issue = "32838")]
991 pub fn allocator(&self) -> &A {
995 /// Returns a front-to-back iterator.
1000 /// use std::collections::VecDeque;
1002 /// let mut buf = VecDeque::new();
1003 /// buf.push_back(5);
1004 /// buf.push_back(3);
1005 /// buf.push_back(4);
1006 /// let b: &[_] = &[&5, &3, &4];
1007 /// let c: Vec<&i32> = buf.iter().collect();
1008 /// assert_eq!(&c[..], b);
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 pub fn iter(&self) -> Iter<'_, T> {
1012 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } }
1015 /// Returns a front-to-back iterator that returns mutable references.
1020 /// use std::collections::VecDeque;
1022 /// let mut buf = VecDeque::new();
1023 /// buf.push_back(5);
1024 /// buf.push_back(3);
1025 /// buf.push_back(4);
1026 /// for num in buf.iter_mut() {
1027 /// *num = *num - 2;
1029 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1030 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1034 // SAFETY: The internal `IterMut` safety invariant is established because the
1035 // `ring` we create is a dereferenceable slice for lifetime '_.
1036 let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1038 unsafe { IterMut::new(ring, self.tail, self.head, PhantomData) }
1041 /// Returns a pair of slices which contain, in order, the contents of the
1044 /// If [`make_contiguous`] was previously called, all elements of the
1045 /// deque will be in the first slice and the second slice will be empty.
1047 /// [`make_contiguous`]: VecDeque::make_contiguous
1052 /// use std::collections::VecDeque;
1054 /// let mut deque = VecDeque::new();
1056 /// deque.push_back(0);
1057 /// deque.push_back(1);
1058 /// deque.push_back(2);
1060 /// assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..]));
1062 /// deque.push_front(10);
1063 /// deque.push_front(9);
1065 /// assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1068 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1069 pub fn as_slices(&self) -> (&[T], &[T]) {
1071 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
1072 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
1074 let buf = self.buffer_as_slice();
1075 let (front, back) = RingSlices::ring_slices(buf, self.head, self.tail);
1076 (MaybeUninit::slice_assume_init_ref(front), MaybeUninit::slice_assume_init_ref(back))
1080 /// Returns a pair of slices which contain, in order, the contents of the
1083 /// If [`make_contiguous`] was previously called, all elements of the
1084 /// deque will be in the first slice and the second slice will be empty.
1086 /// [`make_contiguous`]: VecDeque::make_contiguous
1091 /// use std::collections::VecDeque;
1093 /// let mut deque = VecDeque::new();
1095 /// deque.push_back(0);
1096 /// deque.push_back(1);
1098 /// deque.push_front(10);
1099 /// deque.push_front(9);
1101 /// deque.as_mut_slices().0[0] = 42;
1102 /// deque.as_mut_slices().1[0] = 24;
1103 /// assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
1106 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1107 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1109 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
1110 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
1112 let head = self.head;
1113 let tail = self.tail;
1114 let buf = self.buffer_as_mut_slice();
1115 let (front, back) = RingSlices::ring_slices(buf, head, tail);
1116 (MaybeUninit::slice_assume_init_mut(front), MaybeUninit::slice_assume_init_mut(back))
1120 /// Returns the number of elements in the deque.
1125 /// use std::collections::VecDeque;
1127 /// let mut deque = VecDeque::new();
1128 /// assert_eq!(deque.len(), 0);
1129 /// deque.push_back(1);
1130 /// assert_eq!(deque.len(), 1);
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 pub fn len(&self) -> usize {
1134 count(self.tail, self.head, self.cap())
1137 /// Returns `true` if the deque is empty.
1142 /// use std::collections::VecDeque;
1144 /// let mut deque = VecDeque::new();
1145 /// assert!(deque.is_empty());
1146 /// deque.push_front(1);
1147 /// assert!(!deque.is_empty());
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub fn is_empty(&self) -> bool {
1151 self.tail == self.head
1154 fn range_tail_head<R>(&self, range: R) -> (usize, usize)
1156 R: RangeBounds<usize>,
1158 let Range { start, end } = slice::range(range, ..self.len());
1159 let tail = self.wrap_add(self.tail, start);
1160 let head = self.wrap_add(self.tail, end);
1164 /// Creates an iterator that covers the specified range in the deque.
1168 /// Panics if the starting point is greater than the end point or if
1169 /// the end point is greater than the length of the deque.
1174 /// use std::collections::VecDeque;
1176 /// let deque: VecDeque<_> = [1, 2, 3].into();
1177 /// let range = deque.range(2..).copied().collect::<VecDeque<_>>();
1178 /// assert_eq!(range, [3]);
1180 /// // A full range covers all contents
1181 /// let all = deque.range(..);
1182 /// assert_eq!(all.len(), 3);
1185 #[stable(feature = "deque_range", since = "1.51.0")]
1186 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1188 R: RangeBounds<usize>,
1190 let (tail, head) = self.range_tail_head(range);
1194 // The shared reference we have in &self is maintained in the '_ of Iter.
1195 ring: unsafe { self.buffer_as_slice() },
1199 /// Creates an iterator that covers the specified mutable range in the deque.
1203 /// Panics if the starting point is greater than the end point or if
1204 /// the end point is greater than the length of the deque.
1209 /// use std::collections::VecDeque;
1211 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1212 /// for v in deque.range_mut(2..) {
1215 /// assert_eq!(deque, [1, 2, 6]);
1217 /// // A full range covers all contents
1218 /// for v in deque.range_mut(..) {
1221 /// assert_eq!(deque, [2, 4, 12]);
1224 #[stable(feature = "deque_range", since = "1.51.0")]
1225 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1227 R: RangeBounds<usize>,
1229 let (tail, head) = self.range_tail_head(range);
1231 // SAFETY: The internal `IterMut` safety invariant is established because the
1232 // `ring` we create is a dereferenceable slice for lifetime '_.
1233 let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1235 unsafe { IterMut::new(ring, tail, head, PhantomData) }
1238 /// Removes the specified range from the deque in bulk, returning all
1239 /// removed elements as an iterator. If the iterator is dropped before
1240 /// being fully consumed, it drops the remaining removed elements.
1242 /// The returned iterator keeps a mutable borrow on the queue to optimize
1243 /// its implementation.
1248 /// Panics if the starting point is greater than the end point or if
1249 /// the end point is greater than the length of the deque.
1253 /// If the returned iterator goes out of scope without being dropped (due to
1254 /// [`mem::forget`], for example), the deque may have lost and leaked
1255 /// elements arbitrarily, including elements outside the range.
1260 /// use std::collections::VecDeque;
1262 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1263 /// let drained = deque.drain(2..).collect::<VecDeque<_>>();
1264 /// assert_eq!(drained, [3]);
1265 /// assert_eq!(deque, [1, 2]);
1267 /// // A full range clears all contents, like `clear()` does
1268 /// deque.drain(..);
1269 /// assert!(deque.is_empty());
1272 #[stable(feature = "drain", since = "1.6.0")]
1273 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1275 R: RangeBounds<usize>,
1279 // When the Drain is first created, the source deque is shortened to
1280 // make sure no uninitialized or moved-from elements are accessible at
1281 // all if the Drain's destructor never gets to run.
1283 // Drain will ptr::read out the values to remove.
1284 // When finished, the remaining data will be copied back to cover the hole,
1285 // and the head/tail values will be restored correctly.
1287 let (drain_tail, drain_head) = self.range_tail_head(range);
1289 // The deque's elements are parted into three segments:
1290 // * self.tail -> drain_tail
1291 // * drain_tail -> drain_head
1292 // * drain_head -> self.head
1294 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1296 // We store drain_tail as self.head, and drain_head and self.head as
1297 // after_tail and after_head respectively on the Drain. This also
1298 // truncates the effective array such that if the Drain is leaked, we
1299 // have forgotten about the potentially moved values after the start of
1303 // [. . . o o x x o o . . .]
1305 let head = self.head;
1307 // "forget" about the values after the start of the drain until after
1308 // the drain is complete and the Drain destructor is run.
1309 self.head = drain_tail;
1311 let deque = NonNull::from(&mut *self);
1315 // Crucially, we only create shared references from `self` here and read from
1316 // it. We do not write to `self` nor reborrow to a mutable reference.
1317 // Hence the raw pointer we created above, for `deque`, remains valid.
1318 ring: unsafe { self.buffer_as_slice() },
1321 unsafe { Drain::new(drain_head, head, iter, deque) }
1324 /// Clears the deque, removing all values.
1329 /// use std::collections::VecDeque;
1331 /// let mut deque = VecDeque::new();
1332 /// deque.push_back(1);
1334 /// assert!(deque.is_empty());
1336 #[stable(feature = "rust1", since = "1.0.0")]
1338 pub fn clear(&mut self) {
1342 /// Returns `true` if the deque contains an element equal to the
1348 /// use std::collections::VecDeque;
1350 /// let mut deque: VecDeque<u32> = VecDeque::new();
1352 /// deque.push_back(0);
1353 /// deque.push_back(1);
1355 /// assert_eq!(deque.contains(&1), true);
1356 /// assert_eq!(deque.contains(&10), false);
1358 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1359 pub fn contains(&self, x: &T) -> bool
1363 let (a, b) = self.as_slices();
1364 a.contains(x) || b.contains(x)
1367 /// Provides a reference to the front element, or `None` if the deque is
1373 /// use std::collections::VecDeque;
1375 /// let mut d = VecDeque::new();
1376 /// assert_eq!(d.front(), None);
1380 /// assert_eq!(d.front(), Some(&1));
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 pub fn front(&self) -> Option<&T> {
1387 /// Provides a mutable reference to the front element, or `None` if the
1393 /// use std::collections::VecDeque;
1395 /// let mut d = VecDeque::new();
1396 /// assert_eq!(d.front_mut(), None);
1400 /// match d.front_mut() {
1401 /// Some(x) => *x = 9,
1404 /// assert_eq!(d.front(), Some(&9));
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 pub fn front_mut(&mut self) -> Option<&mut T> {
1411 /// Provides a reference to the back element, or `None` if the deque is
1417 /// use std::collections::VecDeque;
1419 /// let mut d = VecDeque::new();
1420 /// assert_eq!(d.back(), None);
1424 /// assert_eq!(d.back(), Some(&2));
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 pub fn back(&self) -> Option<&T> {
1428 self.get(self.len().wrapping_sub(1))
1431 /// Provides a mutable reference to the back element, or `None` if the
1437 /// use std::collections::VecDeque;
1439 /// let mut d = VecDeque::new();
1440 /// assert_eq!(d.back(), None);
1444 /// match d.back_mut() {
1445 /// Some(x) => *x = 9,
1448 /// assert_eq!(d.back(), Some(&9));
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 pub fn back_mut(&mut self) -> Option<&mut T> {
1452 self.get_mut(self.len().wrapping_sub(1))
1455 /// Removes the first element and returns it, or `None` if the deque is
1461 /// use std::collections::VecDeque;
1463 /// let mut d = VecDeque::new();
1467 /// assert_eq!(d.pop_front(), Some(1));
1468 /// assert_eq!(d.pop_front(), Some(2));
1469 /// assert_eq!(d.pop_front(), None);
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 pub fn pop_front(&mut self) -> Option<T> {
1473 if self.is_empty() {
1476 let tail = self.tail;
1477 self.tail = self.wrap_add(self.tail, 1);
1478 unsafe { Some(self.buffer_read(tail)) }
1482 /// Removes the last element from the deque and returns it, or `None` if
1488 /// use std::collections::VecDeque;
1490 /// let mut buf = VecDeque::new();
1491 /// assert_eq!(buf.pop_back(), None);
1492 /// buf.push_back(1);
1493 /// buf.push_back(3);
1494 /// assert_eq!(buf.pop_back(), Some(3));
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 pub fn pop_back(&mut self) -> Option<T> {
1498 if self.is_empty() {
1501 self.head = self.wrap_sub(self.head, 1);
1502 let head = self.head;
1503 unsafe { Some(self.buffer_read(head)) }
1507 /// Prepends an element to the deque.
1512 /// use std::collections::VecDeque;
1514 /// let mut d = VecDeque::new();
1515 /// d.push_front(1);
1516 /// d.push_front(2);
1517 /// assert_eq!(d.front(), Some(&2));
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 pub fn push_front(&mut self, value: T) {
1525 self.tail = self.wrap_sub(self.tail, 1);
1526 let tail = self.tail;
1528 self.buffer_write(tail, value);
1532 /// Appends an element to the back of the deque.
1537 /// use std::collections::VecDeque;
1539 /// let mut buf = VecDeque::new();
1540 /// buf.push_back(1);
1541 /// buf.push_back(3);
1542 /// assert_eq!(3, *buf.back().unwrap());
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 pub fn push_back(&mut self, value: T) {
1550 let head = self.head;
1551 self.head = self.wrap_add(self.head, 1);
1552 unsafe { self.buffer_write(head, value) }
1556 fn is_contiguous(&self) -> bool {
1557 // FIXME: Should we consider `head == 0` to mean
1558 // that `self` is contiguous?
1559 self.tail <= self.head
1562 /// Removes an element from anywhere in the deque and returns it,
1563 /// replacing it with the first element.
1565 /// This does not preserve ordering, but is *O*(1).
1567 /// Returns `None` if `index` is out of bounds.
1569 /// Element at index 0 is the front of the queue.
1574 /// use std::collections::VecDeque;
1576 /// let mut buf = VecDeque::new();
1577 /// assert_eq!(buf.swap_remove_front(0), None);
1578 /// buf.push_back(1);
1579 /// buf.push_back(2);
1580 /// buf.push_back(3);
1581 /// assert_eq!(buf, [1, 2, 3]);
1583 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1584 /// assert_eq!(buf, [2, 1]);
1586 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1587 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1588 let length = self.len();
1589 if length > 0 && index < length && index != 0 {
1590 self.swap(index, 0);
1591 } else if index >= length {
1597 /// Removes an element from anywhere in the deque and returns it,
1598 /// replacing it with the last element.
1600 /// This does not preserve ordering, but is *O*(1).
1602 /// Returns `None` if `index` is out of bounds.
1604 /// Element at index 0 is the front of the queue.
1609 /// use std::collections::VecDeque;
1611 /// let mut buf = VecDeque::new();
1612 /// assert_eq!(buf.swap_remove_back(0), None);
1613 /// buf.push_back(1);
1614 /// buf.push_back(2);
1615 /// buf.push_back(3);
1616 /// assert_eq!(buf, [1, 2, 3]);
1618 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1619 /// assert_eq!(buf, [3, 2]);
1621 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1622 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1623 let length = self.len();
1624 if length > 0 && index < length - 1 {
1625 self.swap(index, length - 1);
1626 } else if index >= length {
1632 /// Inserts an element at `index` within the deque, shifting all elements
1633 /// with indices greater than or equal to `index` towards the back.
1635 /// Element at index 0 is the front of the queue.
1639 /// Panics if `index` is greater than deque's length
1644 /// use std::collections::VecDeque;
1646 /// let mut vec_deque = VecDeque::new();
1647 /// vec_deque.push_back('a');
1648 /// vec_deque.push_back('b');
1649 /// vec_deque.push_back('c');
1650 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1652 /// vec_deque.insert(1, 'd');
1653 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1655 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1656 pub fn insert(&mut self, index: usize, value: T) {
1657 assert!(index <= self.len(), "index out of bounds");
1662 // Move the least number of elements in the ring buffer and insert
1665 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1667 // There are three main cases:
1668 // Elements are contiguous
1669 // - special case when tail is 0
1670 // Elements are discontiguous and the insert is in the tail section
1671 // Elements are discontiguous and the insert is in the head section
1673 // For each of those there are two more cases:
1674 // Insert is closer to tail
1675 // Insert is closer to head
1677 // Key: H - self.head
1679 // o - Valid element
1680 // I - Insertion element
1681 // A - The element that should be after the insertion point
1682 // M - Indicates element was moved
1684 let idx = self.wrap_add(self.tail, index);
1686 let distance_to_tail = index;
1687 let distance_to_head = self.len() - index;
1689 let contiguous = self.is_contiguous();
1691 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1692 (true, true, _) if index == 0 => {
1697 // [A o o o o o o . . . . . . . . .]
1700 // [A o o o o o o o . . . . . I]
1703 self.tail = self.wrap_sub(self.tail, 1);
1705 (true, true, _) => {
1707 // contiguous, insert closer to tail:
1710 // [. . . o o A o o o o . . . . . .]
1713 // [. . o o I A o o o o . . . . . .]
1716 // contiguous, insert closer to tail and tail is 0:
1720 // [o o A o o o o . . . . . . . . .]
1723 // [o I A o o o o o . . . . . . . o]
1726 let new_tail = self.wrap_sub(self.tail, 1);
1728 self.copy(new_tail, self.tail, 1);
1729 // Already moved the tail, so we only copy `index - 1` elements.
1730 self.copy(self.tail, self.tail + 1, index - 1);
1732 self.tail = new_tail;
1735 (true, false, _) => {
1737 // contiguous, insert closer to head:
1740 // [. . . o o o o A o o . . . . . .]
1743 // [. . . o o o o I A o o . . . . .]
1746 self.copy(idx + 1, idx, self.head - idx);
1747 self.head = self.wrap_add(self.head, 1);
1750 (false, true, true) => {
1752 // discontiguous, insert closer to tail, tail section:
1755 // [o o o o o o . . . . . o o A o o]
1758 // [o o o o o o . . . . o o I A o o]
1761 self.copy(self.tail - 1, self.tail, index);
1765 (false, false, true) => {
1767 // discontiguous, insert closer to head, tail section:
1770 // [o o . . . . . . . o o o o o A o]
1773 // [o o o . . . . . . o o o o o I A]
1776 // copy elements up to new head
1777 self.copy(1, 0, self.head);
1779 // copy last element into empty spot at bottom of buffer
1780 self.copy(0, self.cap() - 1, 1);
1782 // move elements from idx to end forward not including ^ element
1783 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1788 (false, true, false) if idx == 0 => {
1790 // discontiguous, insert is closer to tail, head section,
1791 // and is at index zero in the internal buffer:
1794 // [A o o o o o o o o o . . . o o o]
1797 // [A o o o o o o o o o . . o o o I]
1800 // copy elements up to new tail
1801 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1803 // copy last element into empty spot at bottom of buffer
1804 self.copy(self.cap() - 1, 0, 1);
1809 (false, true, false) => {
1811 // discontiguous, insert closer to tail, head section:
1814 // [o o o A o o o o o o . . . o o o]
1817 // [o o I A o o o o o o . . o o o o]
1820 // copy elements up to new tail
1821 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1823 // copy last element into empty spot at bottom of buffer
1824 self.copy(self.cap() - 1, 0, 1);
1826 // move elements from idx-1 to end forward not including ^ element
1827 self.copy(0, 1, idx - 1);
1832 (false, false, false) => {
1834 // discontiguous, insert closer to head, head section:
1837 // [o o o o A o o . . . . . . o o o]
1840 // [o o o o I A o o . . . . . o o o]
1843 self.copy(idx + 1, idx, self.head - idx);
1849 // tail might've been changed so we need to recalculate
1850 let new_idx = self.wrap_add(self.tail, index);
1852 self.buffer_write(new_idx, value);
1856 /// Removes and returns the element at `index` from the deque.
1857 /// Whichever end is closer to the removal point will be moved to make
1858 /// room, and all the affected elements will be moved to new positions.
1859 /// Returns `None` if `index` is out of bounds.
1861 /// Element at index 0 is the front of the queue.
1866 /// use std::collections::VecDeque;
1868 /// let mut buf = VecDeque::new();
1869 /// buf.push_back(1);
1870 /// buf.push_back(2);
1871 /// buf.push_back(3);
1872 /// assert_eq!(buf, [1, 2, 3]);
1874 /// assert_eq!(buf.remove(1), Some(2));
1875 /// assert_eq!(buf, [1, 3]);
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 pub fn remove(&mut self, index: usize) -> Option<T> {
1879 if self.is_empty() || self.len() <= index {
1883 // There are three main cases:
1884 // Elements are contiguous
1885 // Elements are discontiguous and the removal is in the tail section
1886 // Elements are discontiguous and the removal is in the head section
1887 // - special case when elements are technically contiguous,
1888 // but self.head = 0
1890 // For each of those there are two more cases:
1891 // Insert is closer to tail
1892 // Insert is closer to head
1894 // Key: H - self.head
1896 // o - Valid element
1897 // x - Element marked for removal
1898 // R - Indicates element that is being removed
1899 // M - Indicates element was moved
1901 let idx = self.wrap_add(self.tail, index);
1903 let elem = unsafe { Some(self.buffer_read(idx)) };
1905 let distance_to_tail = index;
1906 let distance_to_head = self.len() - index;
1908 let contiguous = self.is_contiguous();
1910 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1911 (true, true, _) => {
1913 // contiguous, remove closer to tail:
1916 // [. . . o o x o o o o . . . . . .]
1919 // [. . . . o o o o o o . . . . . .]
1922 self.copy(self.tail + 1, self.tail, index);
1926 (true, false, _) => {
1928 // contiguous, remove closer to head:
1931 // [. . . o o o o x o o . . . . . .]
1934 // [. . . o o o o o o . . . . . . .]
1937 self.copy(idx, idx + 1, self.head - idx - 1);
1941 (false, true, true) => {
1943 // discontiguous, remove closer to tail, tail section:
1946 // [o o o o o o . . . . . o o x o o]
1949 // [o o o o o o . . . . . . o o o o]
1952 self.copy(self.tail + 1, self.tail, index);
1953 self.tail = self.wrap_add(self.tail, 1);
1956 (false, false, false) => {
1958 // discontiguous, remove closer to head, head section:
1961 // [o o o o x o o . . . . . . o o o]
1964 // [o o o o o o . . . . . . . o o o]
1967 self.copy(idx, idx + 1, self.head - idx - 1);
1971 (false, false, true) => {
1973 // discontiguous, remove closer to head, tail section:
1976 // [o o o . . . . . . o o o o o x o]
1979 // [o o . . . . . . . o o o o o o o]
1982 // or quasi-discontiguous, remove next to head, tail section:
1985 // [. . . . . . . . . o o o o o x o]
1988 // [. . . . . . . . . o o o o o o .]
1991 // draw in elements in the tail section
1992 self.copy(idx, idx + 1, self.cap() - idx - 1);
1994 // Prevents underflow.
1996 // copy first element into empty spot
1997 self.copy(self.cap() - 1, 0, 1);
1999 // move elements in the head section backwards
2000 self.copy(0, 1, self.head - 1);
2003 self.head = self.wrap_sub(self.head, 1);
2006 (false, true, false) => {
2008 // discontiguous, remove closer to tail, head section:
2011 // [o o x o o o o o o o . . . o o o]
2014 // [o o o o o o o o o o . . . . o o]
2017 // draw in elements up to idx
2018 self.copy(1, 0, idx);
2020 // copy last element into empty spot
2021 self.copy(0, self.cap() - 1, 1);
2023 // move elements from tail to end forward, excluding the last one
2024 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
2026 self.tail = self.wrap_add(self.tail, 1);
2034 /// Splits the deque into two at the given index.
2036 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2037 /// and the returned deque contains elements `[at, len)`.
2039 /// Note that the capacity of `self` does not change.
2041 /// Element at index 0 is the front of the queue.
2045 /// Panics if `at > len`.
2050 /// use std::collections::VecDeque;
2052 /// let mut buf: VecDeque<_> = [1, 2, 3].into();
2053 /// let buf2 = buf.split_off(1);
2054 /// assert_eq!(buf, [1]);
2055 /// assert_eq!(buf2, [2, 3]);
2058 #[must_use = "use `.truncate()` if you don't need the other half"]
2059 #[stable(feature = "split_off", since = "1.4.0")]
2060 pub fn split_off(&mut self, at: usize) -> Self
2064 let len = self.len();
2065 assert!(at <= len, "`at` out of bounds");
2067 let other_len = len - at;
2068 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2071 let (first_half, second_half) = self.as_slices();
2073 let first_len = first_half.len();
2074 let second_len = second_half.len();
2076 // `at` lies in the first half.
2077 let amount_in_first = first_len - at;
2079 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2081 // just take all of the second half.
2082 ptr::copy_nonoverlapping(
2083 second_half.as_ptr(),
2084 other.ptr().add(amount_in_first),
2088 // `at` lies in the second half, need to factor in the elements we skipped
2089 // in the first half.
2090 let offset = at - first_len;
2091 let amount_in_second = second_len - offset;
2092 ptr::copy_nonoverlapping(
2093 second_half.as_ptr().add(offset),
2100 // Cleanup where the ends of the buffers are
2101 self.head = self.wrap_sub(self.head, other_len);
2102 other.head = other.wrap_index(other_len);
2107 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2111 /// Panics if the new number of elements in self overflows a `usize`.
2116 /// use std::collections::VecDeque;
2118 /// let mut buf: VecDeque<_> = [1, 2].into();
2119 /// let mut buf2: VecDeque<_> = [3, 4].into();
2120 /// buf.append(&mut buf2);
2121 /// assert_eq!(buf, [1, 2, 3, 4]);
2122 /// assert_eq!(buf2, []);
2125 #[stable(feature = "append", since = "1.4.0")]
2126 pub fn append(&mut self, other: &mut Self) {
2127 self.reserve(other.len());
2129 let (left, right) = other.as_slices();
2130 self.copy_slice(self.head, left);
2131 self.copy_slice(self.wrap_add(self.head, left.len()), right);
2133 // SAFETY: Update pointers after copying to avoid leaving doppelganger
2134 // in case of panics.
2135 self.head = self.wrap_add(self.head, other.len());
2136 // Silently drop values in `other`.
2137 other.tail = other.head;
2140 /// Retains only the elements specified by the predicate.
2142 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2143 /// This method operates in place, visiting each element exactly once in the
2144 /// original order, and preserves the order of the retained elements.
2149 /// use std::collections::VecDeque;
2151 /// let mut buf = VecDeque::new();
2152 /// buf.extend(1..5);
2153 /// buf.retain(|&x| x % 2 == 0);
2154 /// assert_eq!(buf, [2, 4]);
2157 /// Because the elements are visited exactly once in the original order,
2158 /// external state may be used to decide which elements to keep.
2161 /// use std::collections::VecDeque;
2163 /// let mut buf = VecDeque::new();
2164 /// buf.extend(1..6);
2166 /// let keep = [false, true, true, false, true];
2167 /// let mut iter = keep.iter();
2168 /// buf.retain(|_| *iter.next().unwrap());
2169 /// assert_eq!(buf, [2, 3, 5]);
2171 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2172 pub fn retain<F>(&mut self, mut f: F)
2174 F: FnMut(&T) -> bool,
2176 self.retain_mut(|elem| f(elem));
2179 /// Retains only the elements specified by the predicate.
2181 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2182 /// This method operates in place, visiting each element exactly once in the
2183 /// original order, and preserves the order of the retained elements.
2188 /// use std::collections::VecDeque;
2190 /// let mut buf = VecDeque::new();
2191 /// buf.extend(1..5);
2192 /// buf.retain_mut(|x| if *x % 2 == 0 {
2198 /// assert_eq!(buf, [3, 5]);
2200 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2201 pub fn retain_mut<F>(&mut self, mut f: F)
2203 F: FnMut(&mut T) -> bool,
2205 let len = self.len();
2209 // Stage 1: All values are retained.
2211 if !f(&mut self[cur]) {
2218 // Stage 2: Swap retained value into current idx.
2220 if !f(&mut self[cur]) {
2225 self.swap(idx, cur);
2229 // Stage 3: Truncate all values after idx.
2235 // Double the buffer size. This method is inline(never), so we expect it to only
2236 // be called in cold paths.
2237 // This may panic or abort
2239 fn grow(&mut self) {
2240 // Extend or possibly remove this assertion when valid use-cases for growing the
2241 // buffer without it being full emerge
2242 debug_assert!(self.is_full());
2243 let old_cap = self.cap();
2244 self.buf.reserve_exact(old_cap, old_cap);
2245 assert!(self.cap() == old_cap * 2);
2247 self.handle_capacity_increase(old_cap);
2249 debug_assert!(!self.is_full());
2252 /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2253 /// either by removing excess elements from the back or by appending
2254 /// elements generated by calling `generator` to the back.
2259 /// use std::collections::VecDeque;
2261 /// let mut buf = VecDeque::new();
2262 /// buf.push_back(5);
2263 /// buf.push_back(10);
2264 /// buf.push_back(15);
2265 /// assert_eq!(buf, [5, 10, 15]);
2267 /// buf.resize_with(5, Default::default);
2268 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2270 /// buf.resize_with(2, || unreachable!());
2271 /// assert_eq!(buf, [5, 10]);
2273 /// let mut state = 100;
2274 /// buf.resize_with(5, || { state += 1; state });
2275 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2277 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2278 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2279 let len = self.len();
2282 self.extend(repeat_with(generator).take(new_len - len))
2284 self.truncate(new_len);
2288 /// Rearranges the internal storage of this deque so it is one contiguous
2289 /// slice, which is then returned.
2291 /// This method does not allocate and does not change the order of the
2292 /// inserted elements. As it returns a mutable slice, this can be used to
2295 /// Once the internal storage is contiguous, the [`as_slices`] and
2296 /// [`as_mut_slices`] methods will return the entire contents of the
2297 /// deque in a single slice.
2299 /// [`as_slices`]: VecDeque::as_slices
2300 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2304 /// Sorting the content of a deque.
2307 /// use std::collections::VecDeque;
2309 /// let mut buf = VecDeque::with_capacity(15);
2311 /// buf.push_back(2);
2312 /// buf.push_back(1);
2313 /// buf.push_front(3);
2315 /// // sorting the deque
2316 /// buf.make_contiguous().sort();
2317 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2319 /// // sorting it in reverse order
2320 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2321 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2324 /// Getting immutable access to the contiguous slice.
2327 /// use std::collections::VecDeque;
2329 /// let mut buf = VecDeque::new();
2331 /// buf.push_back(2);
2332 /// buf.push_back(1);
2333 /// buf.push_front(3);
2335 /// buf.make_contiguous();
2336 /// if let (slice, &[]) = buf.as_slices() {
2337 /// // we can now be sure that `slice` contains all elements of the deque,
2338 /// // while still having immutable access to `buf`.
2339 /// assert_eq!(buf.len(), slice.len());
2340 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2343 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2344 pub fn make_contiguous(&mut self) -> &mut [T] {
2345 if self.is_contiguous() {
2346 let tail = self.tail;
2347 let head = self.head;
2349 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2350 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2352 MaybeUninit::slice_assume_init_mut(
2353 RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2358 let buf = self.buf.ptr();
2359 let cap = self.cap();
2360 let len = self.len();
2362 let free = self.tail - self.head;
2363 let tail_len = cap - self.tail;
2365 if free >= tail_len {
2366 // there is enough free space to copy the tail in one go,
2367 // this means that we first shift the head backwards, and then
2368 // copy the tail to the correct position.
2370 // from: DEFGH....ABC
2373 ptr::copy(buf, buf.add(tail_len), self.head);
2375 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2381 } else if free > self.head {
2382 // FIXME: We currently do not consider ....ABCDEFGH
2383 // to be contiguous because `head` would be `0` in this
2384 // case. While we probably want to change this it
2385 // isn't trivial as a few places expect `is_contiguous`
2386 // to mean that we can just slice using `buf[tail..head]`.
2388 // there is enough free space to copy the head in one go,
2389 // this means that we first shift the tail forwards, and then
2390 // copy the head to the correct position.
2392 // from: FGH....ABCDE
2395 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2397 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2400 self.tail = self.head;
2401 self.head = self.wrap_add(self.tail, len);
2404 // free is smaller than both head and tail,
2405 // this means we have to slowly "swap" the tail and the head.
2407 // from: EFGHI...ABCD or HIJK.ABCDEFG
2408 // to: ABCDEFGHI... or ABCDEFGHIJK.
2409 let mut left_edge: usize = 0;
2410 let mut right_edge: usize = self.tail;
2412 // The general problem looks like this
2413 // GHIJKLM...ABCDEF - before any swaps
2414 // ABCDEFM...GHIJKL - after 1 pass of swaps
2415 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2416 // - then restart the algorithm with a new (smaller) store
2417 // Sometimes the temp store is reached when the right edge is at the end
2418 // of the buffer - this means we've hit the right order with fewer swaps!
2421 // ABCDEF.. - after four only swaps we've finished
2422 while left_edge < len && right_edge != cap {
2423 let mut right_offset = 0;
2424 for i in left_edge..right_edge {
2425 right_offset = (i - left_edge) % (cap - right_edge);
2426 let src: isize = (right_edge + right_offset) as isize;
2427 ptr::swap(buf.add(i), buf.offset(src));
2429 let n_ops = right_edge - left_edge;
2431 right_edge += right_offset + 1;
2439 let tail = self.tail;
2440 let head = self.head;
2442 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2443 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2445 MaybeUninit::slice_assume_init_mut(
2446 RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2451 /// Rotates the double-ended queue `mid` places to the left.
2454 /// - Rotates item `mid` into the first position.
2455 /// - Pops the first `mid` items and pushes them to the end.
2456 /// - Rotates `len() - mid` places to the right.
2460 /// If `mid` is greater than `len()`. Note that `mid == len()`
2461 /// does _not_ panic and is a no-op rotation.
2465 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2470 /// use std::collections::VecDeque;
2472 /// let mut buf: VecDeque<_> = (0..10).collect();
2474 /// buf.rotate_left(3);
2475 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2477 /// for i in 1..10 {
2478 /// assert_eq!(i * 3 % 10, buf[0]);
2479 /// buf.rotate_left(3);
2481 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2483 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2484 pub fn rotate_left(&mut self, mid: usize) {
2485 assert!(mid <= self.len());
2486 let k = self.len() - mid;
2488 unsafe { self.rotate_left_inner(mid) }
2490 unsafe { self.rotate_right_inner(k) }
2494 /// Rotates the double-ended queue `k` places to the right.
2497 /// - Rotates the first item into position `k`.
2498 /// - Pops the last `k` items and pushes them to the front.
2499 /// - Rotates `len() - k` places to the left.
2503 /// If `k` is greater than `len()`. Note that `k == len()`
2504 /// does _not_ panic and is a no-op rotation.
2508 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2513 /// use std::collections::VecDeque;
2515 /// let mut buf: VecDeque<_> = (0..10).collect();
2517 /// buf.rotate_right(3);
2518 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2520 /// for i in 1..10 {
2521 /// assert_eq!(0, buf[i * 3 % 10]);
2522 /// buf.rotate_right(3);
2524 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2526 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2527 pub fn rotate_right(&mut self, k: usize) {
2528 assert!(k <= self.len());
2529 let mid = self.len() - k;
2531 unsafe { self.rotate_right_inner(k) }
2533 unsafe { self.rotate_left_inner(mid) }
2537 // SAFETY: the following two methods require that the rotation amount
2538 // be less than half the length of the deque.
2540 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2541 // but than `min` is never more than half the capacity, regardless of x,
2542 // so it's sound to call here because we're calling with something
2543 // less than half the length, which is never above half the capacity.
2545 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2546 debug_assert!(mid * 2 <= self.len());
2548 self.wrap_copy(self.head, self.tail, mid);
2550 self.head = self.wrap_add(self.head, mid);
2551 self.tail = self.wrap_add(self.tail, mid);
2554 unsafe fn rotate_right_inner(&mut self, k: usize) {
2555 debug_assert!(k * 2 <= self.len());
2556 self.head = self.wrap_sub(self.head, k);
2557 self.tail = self.wrap_sub(self.tail, k);
2559 self.wrap_copy(self.tail, self.head, k);
2563 /// Binary searches the sorted deque for a given element.
2565 /// If the value is found then [`Result::Ok`] is returned, containing the
2566 /// index of the matching element. If there are multiple matches, then any
2567 /// one of the matches could be returned. If the value is not found then
2568 /// [`Result::Err`] is returned, containing the index where a matching
2569 /// element could be inserted while maintaining sorted order.
2571 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2573 /// [`binary_search_by`]: VecDeque::binary_search_by
2574 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2575 /// [`partition_point`]: VecDeque::partition_point
2579 /// Looks up a series of four elements. The first is found, with a
2580 /// uniquely determined position; the second and third are not
2581 /// found; the fourth could match any position in `[1, 4]`.
2584 /// use std::collections::VecDeque;
2586 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2588 /// assert_eq!(deque.binary_search(&13), Ok(9));
2589 /// assert_eq!(deque.binary_search(&4), Err(7));
2590 /// assert_eq!(deque.binary_search(&100), Err(13));
2591 /// let r = deque.binary_search(&1);
2592 /// assert!(matches!(r, Ok(1..=4)));
2595 /// If you want to insert an item to a sorted deque, while maintaining
2596 /// sort order, consider using [`partition_point`]:
2599 /// use std::collections::VecDeque;
2601 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2603 /// let idx = deque.partition_point(|&x| x < num);
2604 /// // The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
2605 /// deque.insert(idx, num);
2606 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2608 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2610 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2614 self.binary_search_by(|e| e.cmp(x))
2617 /// Binary searches the sorted deque with a comparator function.
2619 /// The comparator function should implement an order consistent
2620 /// with the sort order of the deque, returning an order code that
2621 /// indicates whether its argument is `Less`, `Equal` or `Greater`
2622 /// than the desired target.
2624 /// If the value is found then [`Result::Ok`] is returned, containing the
2625 /// index of the matching element. If there are multiple matches, then any
2626 /// one of the matches could be returned. If the value is not found then
2627 /// [`Result::Err`] is returned, containing the index where a matching
2628 /// element could be inserted while maintaining sorted order.
2630 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2632 /// [`binary_search`]: VecDeque::binary_search
2633 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2634 /// [`partition_point`]: VecDeque::partition_point
2638 /// Looks up a series of four elements. The first is found, with a
2639 /// uniquely determined position; the second and third are not
2640 /// found; the fourth could match any position in `[1, 4]`.
2643 /// use std::collections::VecDeque;
2645 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2647 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2648 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2649 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2650 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2651 /// assert!(matches!(r, Ok(1..=4)));
2653 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2654 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2656 F: FnMut(&'a T) -> Ordering,
2658 let (front, back) = self.as_slices();
2659 let cmp_back = back.first().map(|elem| f(elem));
2661 if let Some(Ordering::Equal) = cmp_back {
2663 } else if let Some(Ordering::Less) = cmp_back {
2664 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2666 front.binary_search_by(f)
2670 /// Binary searches the sorted deque with a key extraction function.
2672 /// Assumes that the deque is sorted by the key, for instance with
2673 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2675 /// If the value is found then [`Result::Ok`] is returned, containing the
2676 /// index of the matching element. If there are multiple matches, then any
2677 /// one of the matches could be returned. If the value is not found then
2678 /// [`Result::Err`] is returned, containing the index where a matching
2679 /// element could be inserted while maintaining sorted order.
2681 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2683 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2684 /// [`binary_search`]: VecDeque::binary_search
2685 /// [`binary_search_by`]: VecDeque::binary_search_by
2686 /// [`partition_point`]: VecDeque::partition_point
2690 /// Looks up a series of four elements in a slice of pairs sorted by
2691 /// their second elements. The first is found, with a uniquely
2692 /// determined position; the second and third are not found; the
2693 /// fourth could match any position in `[1, 4]`.
2696 /// use std::collections::VecDeque;
2698 /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
2699 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2700 /// (1, 21), (2, 34), (4, 55)].into();
2702 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2703 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2704 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2705 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2706 /// assert!(matches!(r, Ok(1..=4)));
2708 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2710 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2712 F: FnMut(&'a T) -> B,
2715 self.binary_search_by(|k| f(k).cmp(b))
2718 /// Returns the index of the partition point according to the given predicate
2719 /// (the index of the first element of the second partition).
2721 /// The deque is assumed to be partitioned according to the given predicate.
2722 /// This means that all elements for which the predicate returns true are at the start of the deque
2723 /// and all elements for which the predicate returns false are at the end.
2724 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2725 /// (all odd numbers are at the start, all even at the end).
2727 /// If the deque is not partitioned, the returned result is unspecified and meaningless,
2728 /// as this method performs a kind of binary search.
2730 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2732 /// [`binary_search`]: VecDeque::binary_search
2733 /// [`binary_search_by`]: VecDeque::binary_search_by
2734 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2739 /// use std::collections::VecDeque;
2741 /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
2742 /// let i = deque.partition_point(|&x| x < 5);
2744 /// assert_eq!(i, 4);
2745 /// assert!(deque.iter().take(i).all(|&x| x < 5));
2746 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2749 /// If you want to insert an item to a sorted deque, while maintaining
2753 /// use std::collections::VecDeque;
2755 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2757 /// let idx = deque.partition_point(|&x| x < num);
2758 /// deque.insert(idx, num);
2759 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2761 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2762 pub fn partition_point<P>(&self, mut pred: P) -> usize
2764 P: FnMut(&T) -> bool,
2766 let (front, back) = self.as_slices();
2768 if let Some(true) = back.first().map(|v| pred(v)) {
2769 back.partition_point(pred) + front.len()
2771 front.partition_point(pred)
2776 impl<T: Clone, A: Allocator> VecDeque<T, A> {
2777 /// Modifies the deque in-place so that `len()` is equal to new_len,
2778 /// either by removing excess elements from the back or by appending clones of `value`
2784 /// use std::collections::VecDeque;
2786 /// let mut buf = VecDeque::new();
2787 /// buf.push_back(5);
2788 /// buf.push_back(10);
2789 /// buf.push_back(15);
2790 /// assert_eq!(buf, [5, 10, 15]);
2792 /// buf.resize(2, 0);
2793 /// assert_eq!(buf, [5, 10]);
2795 /// buf.resize(5, 20);
2796 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2798 #[stable(feature = "deque_extras", since = "1.16.0")]
2799 pub fn resize(&mut self, new_len: usize, value: T) {
2800 self.resize_with(new_len, || value.clone());
2804 /// Returns the index in the underlying buffer for a given logical element index.
2806 fn wrap_index(index: usize, size: usize) -> usize {
2807 // size is always a power of 2
2808 debug_assert!(size.is_power_of_two());
2812 /// Calculate the number of elements left to be read in the buffer
2814 fn count(tail: usize, head: usize, size: usize) -> usize {
2815 // size is always a power of 2
2816 (head.wrapping_sub(tail)) & (size - 1)
2819 #[stable(feature = "rust1", since = "1.0.0")]
2820 impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
2821 fn eq(&self, other: &Self) -> bool {
2822 if self.len() != other.len() {
2825 let (sa, sb) = self.as_slices();
2826 let (oa, ob) = other.as_slices();
2827 if sa.len() == oa.len() {
2828 sa == oa && sb == ob
2829 } else if sa.len() < oa.len() {
2830 // Always divisible in three sections, for example:
2831 // self: [a b c|d e f]
2832 // other: [0 1 2 3|4 5]
2833 // front = 3, mid = 1,
2834 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2835 let front = sa.len();
2836 let mid = oa.len() - front;
2838 let (oa_front, oa_mid) = oa.split_at(front);
2839 let (sb_mid, sb_back) = sb.split_at(mid);
2840 debug_assert_eq!(sa.len(), oa_front.len());
2841 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2842 debug_assert_eq!(sb_back.len(), ob.len());
2843 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2845 let front = oa.len();
2846 let mid = sa.len() - front;
2848 let (sa_front, sa_mid) = sa.split_at(front);
2849 let (ob_mid, ob_back) = ob.split_at(mid);
2850 debug_assert_eq!(sa_front.len(), oa.len());
2851 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2852 debug_assert_eq!(sb.len(), ob_back.len());
2853 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2858 #[stable(feature = "rust1", since = "1.0.0")]
2859 impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
2861 __impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2862 __impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2863 __impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2864 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2865 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2866 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2868 #[stable(feature = "rust1", since = "1.0.0")]
2869 impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
2870 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2871 self.iter().partial_cmp(other.iter())
2875 #[stable(feature = "rust1", since = "1.0.0")]
2876 impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
2878 fn cmp(&self, other: &Self) -> Ordering {
2879 self.iter().cmp(other.iter())
2883 #[stable(feature = "rust1", since = "1.0.0")]
2884 impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
2885 fn hash<H: Hasher>(&self, state: &mut H) {
2886 self.len().hash(state);
2887 // It's not possible to use Hash::hash_slice on slices
2888 // returned by as_slices method as their length can vary
2889 // in otherwise identical deques.
2891 // Hasher only guarantees equivalence for the exact same
2892 // set of calls to its methods.
2893 self.iter().for_each(|elem| elem.hash(state));
2897 #[stable(feature = "rust1", since = "1.0.0")]
2898 impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
2902 fn index(&self, index: usize) -> &T {
2903 self.get(index).expect("Out of bounds access")
2907 #[stable(feature = "rust1", since = "1.0.0")]
2908 impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
2910 fn index_mut(&mut self, index: usize) -> &mut T {
2911 self.get_mut(index).expect("Out of bounds access")
2915 #[stable(feature = "rust1", since = "1.0.0")]
2916 impl<T> FromIterator<T> for VecDeque<T> {
2917 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
2918 let iterator = iter.into_iter();
2919 let (lower, _) = iterator.size_hint();
2920 let mut deq = VecDeque::with_capacity(lower);
2921 deq.extend(iterator);
2926 #[stable(feature = "rust1", since = "1.0.0")]
2927 impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
2929 type IntoIter = IntoIter<T, A>;
2931 /// Consumes the deque into a front-to-back iterator yielding elements by
2933 fn into_iter(self) -> IntoIter<T, A> {
2938 #[stable(feature = "rust1", since = "1.0.0")]
2939 impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
2941 type IntoIter = Iter<'a, T>;
2943 fn into_iter(self) -> Iter<'a, T> {
2948 #[stable(feature = "rust1", since = "1.0.0")]
2949 impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
2950 type Item = &'a mut T;
2951 type IntoIter = IterMut<'a, T>;
2953 fn into_iter(self) -> IterMut<'a, T> {
2958 #[stable(feature = "rust1", since = "1.0.0")]
2959 impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
2960 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2961 // This function should be the moral equivalent of:
2963 // for item in iter.into_iter() {
2964 // self.push_back(item);
2966 let mut iter = iter.into_iter();
2967 while let Some(element) = iter.next() {
2968 if self.len() == self.capacity() {
2969 let (lower, _) = iter.size_hint();
2970 self.reserve(lower.saturating_add(1));
2973 let head = self.head;
2974 self.head = self.wrap_add(self.head, 1);
2976 self.buffer_write(head, element);
2982 fn extend_one(&mut self, elem: T) {
2983 self.push_back(elem);
2987 fn extend_reserve(&mut self, additional: usize) {
2988 self.reserve(additional);
2992 #[stable(feature = "extend_ref", since = "1.2.0")]
2993 impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
2994 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2995 self.extend(iter.into_iter().cloned());
2999 fn extend_one(&mut self, &elem: &T) {
3000 self.push_back(elem);
3004 fn extend_reserve(&mut self, additional: usize) {
3005 self.reserve(additional);
3009 #[stable(feature = "rust1", since = "1.0.0")]
3010 impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
3011 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3012 f.debug_list().entries(self).finish()
3016 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3017 impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
3018 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3020 /// [`Vec<T>`]: crate::vec::Vec
3021 /// [`VecDeque<T>`]: crate::collections::VecDeque
3023 /// This avoids reallocating where possible, but the conditions for that are
3024 /// strict, and subject to change, and so shouldn't be relied upon unless the
3025 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
3026 fn from(mut other: Vec<T, A>) -> Self {
3027 let len = other.len();
3028 if mem::size_of::<T>() == 0 {
3029 // There's no actual allocation for ZSTs to worry about capacity,
3030 // but `VecDeque` can't handle as much length as `Vec`.
3031 assert!(len < MAXIMUM_ZST_CAPACITY, "capacity overflow");
3033 // We need to resize if the capacity is not a power of two, too small or
3034 // doesn't have at least one free space. We do this while it's still in
3035 // the `Vec` so the items will drop on panic.
3036 let min_cap = cmp::max(MINIMUM_CAPACITY, len) + 1;
3037 let cap = cmp::max(min_cap, other.capacity()).next_power_of_two();
3038 if other.capacity() != cap {
3039 other.reserve_exact(cap - len);
3044 let (other_buf, len, capacity, alloc) = other.into_raw_parts_with_alloc();
3045 let buf = RawVec::from_raw_parts_in(other_buf, capacity, alloc);
3046 VecDeque { tail: 0, head: len, buf }
3051 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3052 impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
3053 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
3055 /// [`Vec<T>`]: crate::vec::Vec
3056 /// [`VecDeque<T>`]: crate::collections::VecDeque
3058 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
3059 /// the circular buffer doesn't happen to be at the beginning of the allocation.
3064 /// use std::collections::VecDeque;
3066 /// // This one is *O*(1).
3067 /// let deque: VecDeque<_> = (1..5).collect();
3068 /// let ptr = deque.as_slices().0.as_ptr();
3069 /// let vec = Vec::from(deque);
3070 /// assert_eq!(vec, [1, 2, 3, 4]);
3071 /// assert_eq!(vec.as_ptr(), ptr);
3073 /// // This one needs data rearranging.
3074 /// let mut deque: VecDeque<_> = (1..5).collect();
3075 /// deque.push_front(9);
3076 /// deque.push_front(8);
3077 /// let ptr = deque.as_slices().1.as_ptr();
3078 /// let vec = Vec::from(deque);
3079 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
3080 /// assert_eq!(vec.as_ptr(), ptr);
3082 fn from(mut other: VecDeque<T, A>) -> Self {
3083 other.make_contiguous();
3086 let other = ManuallyDrop::new(other);
3087 let buf = other.buf.ptr();
3088 let len = other.len();
3089 let cap = other.cap();
3090 let alloc = ptr::read(other.allocator());
3092 if other.tail != 0 {
3093 ptr::copy(buf.add(other.tail), buf, len);
3095 Vec::from_raw_parts_in(buf, len, cap, alloc)
3100 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
3101 impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
3102 /// Converts a `[T; N]` into a `VecDeque<T>`.
3105 /// use std::collections::VecDeque;
3107 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
3108 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
3109 /// assert_eq!(deq1, deq2);
3111 fn from(arr: [T; N]) -> Self {
3112 let mut deq = VecDeque::with_capacity(N);
3113 let arr = ManuallyDrop::new(arr);
3114 if mem::size_of::<T>() != 0 {
3115 // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
3117 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);