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
1345 /// This operation is *O*(*n*).
1347 /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
1349 /// [`binary_search`]: VecDeque::binary_search
1354 /// use std::collections::VecDeque;
1356 /// let mut deque: VecDeque<u32> = VecDeque::new();
1358 /// deque.push_back(0);
1359 /// deque.push_back(1);
1361 /// assert_eq!(deque.contains(&1), true);
1362 /// assert_eq!(deque.contains(&10), false);
1364 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1365 pub fn contains(&self, x: &T) -> bool
1369 let (a, b) = self.as_slices();
1370 a.contains(x) || b.contains(x)
1373 /// Provides a reference to the front element, or `None` if the deque is
1379 /// use std::collections::VecDeque;
1381 /// let mut d = VecDeque::new();
1382 /// assert_eq!(d.front(), None);
1386 /// assert_eq!(d.front(), Some(&1));
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 pub fn front(&self) -> Option<&T> {
1393 /// Provides a mutable reference to the front element, or `None` if the
1399 /// use std::collections::VecDeque;
1401 /// let mut d = VecDeque::new();
1402 /// assert_eq!(d.front_mut(), None);
1406 /// match d.front_mut() {
1407 /// Some(x) => *x = 9,
1410 /// assert_eq!(d.front(), Some(&9));
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 pub fn front_mut(&mut self) -> Option<&mut T> {
1417 /// Provides a reference to the back element, or `None` if the deque is
1423 /// use std::collections::VecDeque;
1425 /// let mut d = VecDeque::new();
1426 /// assert_eq!(d.back(), None);
1430 /// assert_eq!(d.back(), Some(&2));
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 pub fn back(&self) -> Option<&T> {
1434 self.get(self.len().wrapping_sub(1))
1437 /// Provides a mutable reference to the back element, or `None` if the
1443 /// use std::collections::VecDeque;
1445 /// let mut d = VecDeque::new();
1446 /// assert_eq!(d.back(), None);
1450 /// match d.back_mut() {
1451 /// Some(x) => *x = 9,
1454 /// assert_eq!(d.back(), Some(&9));
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 pub fn back_mut(&mut self) -> Option<&mut T> {
1458 self.get_mut(self.len().wrapping_sub(1))
1461 /// Removes the first element and returns it, or `None` if the deque is
1467 /// use std::collections::VecDeque;
1469 /// let mut d = VecDeque::new();
1473 /// assert_eq!(d.pop_front(), Some(1));
1474 /// assert_eq!(d.pop_front(), Some(2));
1475 /// assert_eq!(d.pop_front(), None);
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 pub fn pop_front(&mut self) -> Option<T> {
1479 if self.is_empty() {
1482 let tail = self.tail;
1483 self.tail = self.wrap_add(self.tail, 1);
1484 unsafe { Some(self.buffer_read(tail)) }
1488 /// Removes the last element from the deque and returns it, or `None` if
1494 /// use std::collections::VecDeque;
1496 /// let mut buf = VecDeque::new();
1497 /// assert_eq!(buf.pop_back(), None);
1498 /// buf.push_back(1);
1499 /// buf.push_back(3);
1500 /// assert_eq!(buf.pop_back(), Some(3));
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 pub fn pop_back(&mut self) -> Option<T> {
1504 if self.is_empty() {
1507 self.head = self.wrap_sub(self.head, 1);
1508 let head = self.head;
1509 unsafe { Some(self.buffer_read(head)) }
1513 /// Prepends an element to the deque.
1518 /// use std::collections::VecDeque;
1520 /// let mut d = VecDeque::new();
1521 /// d.push_front(1);
1522 /// d.push_front(2);
1523 /// assert_eq!(d.front(), Some(&2));
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 pub fn push_front(&mut self, value: T) {
1531 self.tail = self.wrap_sub(self.tail, 1);
1532 let tail = self.tail;
1534 self.buffer_write(tail, value);
1538 /// Appends an element to the back of the deque.
1543 /// use std::collections::VecDeque;
1545 /// let mut buf = VecDeque::new();
1546 /// buf.push_back(1);
1547 /// buf.push_back(3);
1548 /// assert_eq!(3, *buf.back().unwrap());
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 pub fn push_back(&mut self, value: T) {
1556 let head = self.head;
1557 self.head = self.wrap_add(self.head, 1);
1558 unsafe { self.buffer_write(head, value) }
1562 fn is_contiguous(&self) -> bool {
1563 // FIXME: Should we consider `head == 0` to mean
1564 // that `self` is contiguous?
1565 self.tail <= self.head
1568 /// Removes an element from anywhere in the deque and returns it,
1569 /// replacing it with the first element.
1571 /// This does not preserve ordering, but is *O*(1).
1573 /// Returns `None` if `index` is out of bounds.
1575 /// Element at index 0 is the front of the queue.
1580 /// use std::collections::VecDeque;
1582 /// let mut buf = VecDeque::new();
1583 /// assert_eq!(buf.swap_remove_front(0), None);
1584 /// buf.push_back(1);
1585 /// buf.push_back(2);
1586 /// buf.push_back(3);
1587 /// assert_eq!(buf, [1, 2, 3]);
1589 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1590 /// assert_eq!(buf, [2, 1]);
1592 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1593 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1594 let length = self.len();
1595 if length > 0 && index < length && index != 0 {
1596 self.swap(index, 0);
1597 } else if index >= length {
1603 /// Removes an element from anywhere in the deque and returns it,
1604 /// replacing it with the last element.
1606 /// This does not preserve ordering, but is *O*(1).
1608 /// Returns `None` if `index` is out of bounds.
1610 /// Element at index 0 is the front of the queue.
1615 /// use std::collections::VecDeque;
1617 /// let mut buf = VecDeque::new();
1618 /// assert_eq!(buf.swap_remove_back(0), None);
1619 /// buf.push_back(1);
1620 /// buf.push_back(2);
1621 /// buf.push_back(3);
1622 /// assert_eq!(buf, [1, 2, 3]);
1624 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1625 /// assert_eq!(buf, [3, 2]);
1627 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1628 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1629 let length = self.len();
1630 if length > 0 && index < length - 1 {
1631 self.swap(index, length - 1);
1632 } else if index >= length {
1638 /// Inserts an element at `index` within the deque, shifting all elements
1639 /// with indices greater than or equal to `index` towards the back.
1641 /// Element at index 0 is the front of the queue.
1645 /// Panics if `index` is greater than deque's length
1650 /// use std::collections::VecDeque;
1652 /// let mut vec_deque = VecDeque::new();
1653 /// vec_deque.push_back('a');
1654 /// vec_deque.push_back('b');
1655 /// vec_deque.push_back('c');
1656 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1658 /// vec_deque.insert(1, 'd');
1659 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1661 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1662 pub fn insert(&mut self, index: usize, value: T) {
1663 assert!(index <= self.len(), "index out of bounds");
1668 // Move the least number of elements in the ring buffer and insert
1671 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1673 // There are three main cases:
1674 // Elements are contiguous
1675 // - special case when tail is 0
1676 // Elements are discontiguous and the insert is in the tail section
1677 // Elements are discontiguous and the insert is in the head section
1679 // For each of those there are two more cases:
1680 // Insert is closer to tail
1681 // Insert is closer to head
1683 // Key: H - self.head
1685 // o - Valid element
1686 // I - Insertion element
1687 // A - The element that should be after the insertion point
1688 // M - Indicates element was moved
1690 let idx = self.wrap_add(self.tail, index);
1692 let distance_to_tail = index;
1693 let distance_to_head = self.len() - index;
1695 let contiguous = self.is_contiguous();
1697 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1698 (true, true, _) if index == 0 => {
1703 // [A o o o o o o . . . . . . . . .]
1706 // [A o o o o o o o . . . . . I]
1709 self.tail = self.wrap_sub(self.tail, 1);
1711 (true, true, _) => {
1713 // contiguous, insert closer to tail:
1716 // [. . . o o A o o o o . . . . . .]
1719 // [. . o o I A o o o o . . . . . .]
1722 // contiguous, insert closer to tail and tail is 0:
1726 // [o o A o o o o . . . . . . . . .]
1729 // [o I A o o o o o . . . . . . . o]
1732 let new_tail = self.wrap_sub(self.tail, 1);
1734 self.copy(new_tail, self.tail, 1);
1735 // Already moved the tail, so we only copy `index - 1` elements.
1736 self.copy(self.tail, self.tail + 1, index - 1);
1738 self.tail = new_tail;
1741 (true, false, _) => {
1743 // contiguous, insert closer to head:
1746 // [. . . o o o o A o o . . . . . .]
1749 // [. . . o o o o I A o o . . . . .]
1752 self.copy(idx + 1, idx, self.head - idx);
1753 self.head = self.wrap_add(self.head, 1);
1756 (false, true, true) => {
1758 // discontiguous, insert closer to tail, tail section:
1761 // [o o o o o o . . . . . o o A o o]
1764 // [o o o o o o . . . . o o I A o o]
1767 self.copy(self.tail - 1, self.tail, index);
1771 (false, false, true) => {
1773 // discontiguous, insert closer to head, tail section:
1776 // [o o . . . . . . . o o o o o A o]
1779 // [o o o . . . . . . o o o o o I A]
1782 // copy elements up to new head
1783 self.copy(1, 0, self.head);
1785 // copy last element into empty spot at bottom of buffer
1786 self.copy(0, self.cap() - 1, 1);
1788 // move elements from idx to end forward not including ^ element
1789 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1794 (false, true, false) if idx == 0 => {
1796 // discontiguous, insert is closer to tail, head section,
1797 // and is at index zero in the internal buffer:
1800 // [A o o o o o o o o o . . . o o o]
1803 // [A o o o o o o o o o . . o o o I]
1806 // copy elements up to new tail
1807 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1809 // copy last element into empty spot at bottom of buffer
1810 self.copy(self.cap() - 1, 0, 1);
1815 (false, true, false) => {
1817 // discontiguous, insert closer to tail, head section:
1820 // [o o o A o o o o o o . . . o o o]
1823 // [o o I A o o o o o o . . o o o o]
1826 // copy elements up to new tail
1827 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1829 // copy last element into empty spot at bottom of buffer
1830 self.copy(self.cap() - 1, 0, 1);
1832 // move elements from idx-1 to end forward not including ^ element
1833 self.copy(0, 1, idx - 1);
1838 (false, false, false) => {
1840 // discontiguous, insert closer to head, head section:
1843 // [o o o o A o o . . . . . . o o o]
1846 // [o o o o I A o o . . . . . o o o]
1849 self.copy(idx + 1, idx, self.head - idx);
1855 // tail might've been changed so we need to recalculate
1856 let new_idx = self.wrap_add(self.tail, index);
1858 self.buffer_write(new_idx, value);
1862 /// Removes and returns the element at `index` from the deque.
1863 /// Whichever end is closer to the removal point will be moved to make
1864 /// room, and all the affected elements will be moved to new positions.
1865 /// Returns `None` if `index` is out of bounds.
1867 /// Element at index 0 is the front of the queue.
1872 /// use std::collections::VecDeque;
1874 /// let mut buf = VecDeque::new();
1875 /// buf.push_back(1);
1876 /// buf.push_back(2);
1877 /// buf.push_back(3);
1878 /// assert_eq!(buf, [1, 2, 3]);
1880 /// assert_eq!(buf.remove(1), Some(2));
1881 /// assert_eq!(buf, [1, 3]);
1883 #[stable(feature = "rust1", since = "1.0.0")]
1884 pub fn remove(&mut self, index: usize) -> Option<T> {
1885 if self.is_empty() || self.len() <= index {
1889 // There are three main cases:
1890 // Elements are contiguous
1891 // Elements are discontiguous and the removal is in the tail section
1892 // Elements are discontiguous and the removal is in the head section
1893 // - special case when elements are technically contiguous,
1894 // but self.head = 0
1896 // For each of those there are two more cases:
1897 // Insert is closer to tail
1898 // Insert is closer to head
1900 // Key: H - self.head
1902 // o - Valid element
1903 // x - Element marked for removal
1904 // R - Indicates element that is being removed
1905 // M - Indicates element was moved
1907 let idx = self.wrap_add(self.tail, index);
1909 let elem = unsafe { Some(self.buffer_read(idx)) };
1911 let distance_to_tail = index;
1912 let distance_to_head = self.len() - index;
1914 let contiguous = self.is_contiguous();
1916 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1917 (true, true, _) => {
1919 // contiguous, remove closer to tail:
1922 // [. . . o o x o o o o . . . . . .]
1925 // [. . . . o o o o o o . . . . . .]
1928 self.copy(self.tail + 1, self.tail, index);
1932 (true, false, _) => {
1934 // contiguous, remove closer to head:
1937 // [. . . o o o o x o o . . . . . .]
1940 // [. . . o o o o o o . . . . . . .]
1943 self.copy(idx, idx + 1, self.head - idx - 1);
1947 (false, true, true) => {
1949 // discontiguous, remove closer to tail, tail section:
1952 // [o o o o o o . . . . . o o x o o]
1955 // [o o o o o o . . . . . . o o o o]
1958 self.copy(self.tail + 1, self.tail, index);
1959 self.tail = self.wrap_add(self.tail, 1);
1962 (false, false, false) => {
1964 // discontiguous, remove closer to head, head section:
1967 // [o o o o x o o . . . . . . o o o]
1970 // [o o o o o o . . . . . . . o o o]
1973 self.copy(idx, idx + 1, self.head - idx - 1);
1977 (false, false, true) => {
1979 // discontiguous, remove closer to head, tail section:
1982 // [o o o . . . . . . o o o o o x o]
1985 // [o o . . . . . . . o o o o o o o]
1988 // or quasi-discontiguous, remove next to head, tail section:
1991 // [. . . . . . . . . o o o o o x o]
1994 // [. . . . . . . . . o o o o o o .]
1997 // draw in elements in the tail section
1998 self.copy(idx, idx + 1, self.cap() - idx - 1);
2000 // Prevents underflow.
2002 // copy first element into empty spot
2003 self.copy(self.cap() - 1, 0, 1);
2005 // move elements in the head section backwards
2006 self.copy(0, 1, self.head - 1);
2009 self.head = self.wrap_sub(self.head, 1);
2012 (false, true, false) => {
2014 // discontiguous, remove closer to tail, head section:
2017 // [o o x o o o o o o o . . . o o o]
2020 // [o o o o o o o o o o . . . . o o]
2023 // draw in elements up to idx
2024 self.copy(1, 0, idx);
2026 // copy last element into empty spot
2027 self.copy(0, self.cap() - 1, 1);
2029 // move elements from tail to end forward, excluding the last one
2030 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
2032 self.tail = self.wrap_add(self.tail, 1);
2040 /// Splits the deque into two at the given index.
2042 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2043 /// and the returned deque contains elements `[at, len)`.
2045 /// Note that the capacity of `self` does not change.
2047 /// Element at index 0 is the front of the queue.
2051 /// Panics if `at > len`.
2056 /// use std::collections::VecDeque;
2058 /// let mut buf: VecDeque<_> = [1, 2, 3].into();
2059 /// let buf2 = buf.split_off(1);
2060 /// assert_eq!(buf, [1]);
2061 /// assert_eq!(buf2, [2, 3]);
2064 #[must_use = "use `.truncate()` if you don't need the other half"]
2065 #[stable(feature = "split_off", since = "1.4.0")]
2066 pub fn split_off(&mut self, at: usize) -> Self
2070 let len = self.len();
2071 assert!(at <= len, "`at` out of bounds");
2073 let other_len = len - at;
2074 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2077 let (first_half, second_half) = self.as_slices();
2079 let first_len = first_half.len();
2080 let second_len = second_half.len();
2082 // `at` lies in the first half.
2083 let amount_in_first = first_len - at;
2085 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2087 // just take all of the second half.
2088 ptr::copy_nonoverlapping(
2089 second_half.as_ptr(),
2090 other.ptr().add(amount_in_first),
2094 // `at` lies in the second half, need to factor in the elements we skipped
2095 // in the first half.
2096 let offset = at - first_len;
2097 let amount_in_second = second_len - offset;
2098 ptr::copy_nonoverlapping(
2099 second_half.as_ptr().add(offset),
2106 // Cleanup where the ends of the buffers are
2107 self.head = self.wrap_sub(self.head, other_len);
2108 other.head = other.wrap_index(other_len);
2113 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2117 /// Panics if the new number of elements in self overflows a `usize`.
2122 /// use std::collections::VecDeque;
2124 /// let mut buf: VecDeque<_> = [1, 2].into();
2125 /// let mut buf2: VecDeque<_> = [3, 4].into();
2126 /// buf.append(&mut buf2);
2127 /// assert_eq!(buf, [1, 2, 3, 4]);
2128 /// assert_eq!(buf2, []);
2131 #[stable(feature = "append", since = "1.4.0")]
2132 pub fn append(&mut self, other: &mut Self) {
2133 self.reserve(other.len());
2135 let (left, right) = other.as_slices();
2136 self.copy_slice(self.head, left);
2137 self.copy_slice(self.wrap_add(self.head, left.len()), right);
2139 // SAFETY: Update pointers after copying to avoid leaving doppelganger
2140 // in case of panics.
2141 self.head = self.wrap_add(self.head, other.len());
2142 // Silently drop values in `other`.
2143 other.tail = other.head;
2146 /// Retains only the elements specified by the predicate.
2148 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2149 /// This method operates in place, visiting each element exactly once in the
2150 /// original order, and preserves the order of the retained elements.
2155 /// use std::collections::VecDeque;
2157 /// let mut buf = VecDeque::new();
2158 /// buf.extend(1..5);
2159 /// buf.retain(|&x| x % 2 == 0);
2160 /// assert_eq!(buf, [2, 4]);
2163 /// Because the elements are visited exactly once in the original order,
2164 /// external state may be used to decide which elements to keep.
2167 /// use std::collections::VecDeque;
2169 /// let mut buf = VecDeque::new();
2170 /// buf.extend(1..6);
2172 /// let keep = [false, true, true, false, true];
2173 /// let mut iter = keep.iter();
2174 /// buf.retain(|_| *iter.next().unwrap());
2175 /// assert_eq!(buf, [2, 3, 5]);
2177 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2178 pub fn retain<F>(&mut self, mut f: F)
2180 F: FnMut(&T) -> bool,
2182 self.retain_mut(|elem| f(elem));
2185 /// Retains only the elements specified by the predicate.
2187 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2188 /// This method operates in place, visiting each element exactly once in the
2189 /// original order, and preserves the order of the retained elements.
2194 /// use std::collections::VecDeque;
2196 /// let mut buf = VecDeque::new();
2197 /// buf.extend(1..5);
2198 /// buf.retain_mut(|x| if *x % 2 == 0 {
2204 /// assert_eq!(buf, [3, 5]);
2206 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2207 pub fn retain_mut<F>(&mut self, mut f: F)
2209 F: FnMut(&mut T) -> bool,
2211 let len = self.len();
2215 // Stage 1: All values are retained.
2217 if !f(&mut self[cur]) {
2224 // Stage 2: Swap retained value into current idx.
2226 if !f(&mut self[cur]) {
2231 self.swap(idx, cur);
2235 // Stage 3: Truncate all values after idx.
2241 // Double the buffer size. This method is inline(never), so we expect it to only
2242 // be called in cold paths.
2243 // This may panic or abort
2245 fn grow(&mut self) {
2246 // Extend or possibly remove this assertion when valid use-cases for growing the
2247 // buffer without it being full emerge
2248 debug_assert!(self.is_full());
2249 let old_cap = self.cap();
2250 self.buf.reserve_exact(old_cap, old_cap);
2251 assert!(self.cap() == old_cap * 2);
2253 self.handle_capacity_increase(old_cap);
2255 debug_assert!(!self.is_full());
2258 /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2259 /// either by removing excess elements from the back or by appending
2260 /// elements generated by calling `generator` to the back.
2265 /// use std::collections::VecDeque;
2267 /// let mut buf = VecDeque::new();
2268 /// buf.push_back(5);
2269 /// buf.push_back(10);
2270 /// buf.push_back(15);
2271 /// assert_eq!(buf, [5, 10, 15]);
2273 /// buf.resize_with(5, Default::default);
2274 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2276 /// buf.resize_with(2, || unreachable!());
2277 /// assert_eq!(buf, [5, 10]);
2279 /// let mut state = 100;
2280 /// buf.resize_with(5, || { state += 1; state });
2281 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2283 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2284 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2285 let len = self.len();
2288 self.extend(repeat_with(generator).take(new_len - len))
2290 self.truncate(new_len);
2294 /// Rearranges the internal storage of this deque so it is one contiguous
2295 /// slice, which is then returned.
2297 /// This method does not allocate and does not change the order of the
2298 /// inserted elements. As it returns a mutable slice, this can be used to
2301 /// Once the internal storage is contiguous, the [`as_slices`] and
2302 /// [`as_mut_slices`] methods will return the entire contents of the
2303 /// deque in a single slice.
2305 /// [`as_slices`]: VecDeque::as_slices
2306 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2310 /// Sorting the content of a deque.
2313 /// use std::collections::VecDeque;
2315 /// let mut buf = VecDeque::with_capacity(15);
2317 /// buf.push_back(2);
2318 /// buf.push_back(1);
2319 /// buf.push_front(3);
2321 /// // sorting the deque
2322 /// buf.make_contiguous().sort();
2323 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2325 /// // sorting it in reverse order
2326 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2327 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2330 /// Getting immutable access to the contiguous slice.
2333 /// use std::collections::VecDeque;
2335 /// let mut buf = VecDeque::new();
2337 /// buf.push_back(2);
2338 /// buf.push_back(1);
2339 /// buf.push_front(3);
2341 /// buf.make_contiguous();
2342 /// if let (slice, &[]) = buf.as_slices() {
2343 /// // we can now be sure that `slice` contains all elements of the deque,
2344 /// // while still having immutable access to `buf`.
2345 /// assert_eq!(buf.len(), slice.len());
2346 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2349 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2350 pub fn make_contiguous(&mut self) -> &mut [T] {
2351 if self.is_contiguous() {
2352 let tail = self.tail;
2353 let head = self.head;
2355 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2356 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2358 MaybeUninit::slice_assume_init_mut(
2359 RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2364 let buf = self.buf.ptr();
2365 let cap = self.cap();
2366 let len = self.len();
2368 let free = self.tail - self.head;
2369 let tail_len = cap - self.tail;
2371 if free >= tail_len {
2372 // there is enough free space to copy the tail in one go,
2373 // this means that we first shift the head backwards, and then
2374 // copy the tail to the correct position.
2376 // from: DEFGH....ABC
2379 ptr::copy(buf, buf.add(tail_len), self.head);
2381 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2387 } else if free > self.head {
2388 // FIXME: We currently do not consider ....ABCDEFGH
2389 // to be contiguous because `head` would be `0` in this
2390 // case. While we probably want to change this it
2391 // isn't trivial as a few places expect `is_contiguous`
2392 // to mean that we can just slice using `buf[tail..head]`.
2394 // there is enough free space to copy the head in one go,
2395 // this means that we first shift the tail forwards, and then
2396 // copy the head to the correct position.
2398 // from: FGH....ABCDE
2401 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2403 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2406 self.tail = self.head;
2407 self.head = self.wrap_add(self.tail, len);
2410 // free is smaller than both head and tail,
2411 // this means we have to slowly "swap" the tail and the head.
2413 // from: EFGHI...ABCD or HIJK.ABCDEFG
2414 // to: ABCDEFGHI... or ABCDEFGHIJK.
2415 let mut left_edge: usize = 0;
2416 let mut right_edge: usize = self.tail;
2418 // The general problem looks like this
2419 // GHIJKLM...ABCDEF - before any swaps
2420 // ABCDEFM...GHIJKL - after 1 pass of swaps
2421 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2422 // - then restart the algorithm with a new (smaller) store
2423 // Sometimes the temp store is reached when the right edge is at the end
2424 // of the buffer - this means we've hit the right order with fewer swaps!
2427 // ABCDEF.. - after four only swaps we've finished
2428 while left_edge < len && right_edge != cap {
2429 let mut right_offset = 0;
2430 for i in left_edge..right_edge {
2431 right_offset = (i - left_edge) % (cap - right_edge);
2432 let src: isize = (right_edge + right_offset) as isize;
2433 ptr::swap(buf.add(i), buf.offset(src));
2435 let n_ops = right_edge - left_edge;
2437 right_edge += right_offset + 1;
2445 let tail = self.tail;
2446 let head = self.head;
2448 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2449 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2451 MaybeUninit::slice_assume_init_mut(
2452 RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2457 /// Rotates the double-ended queue `mid` places to the left.
2460 /// - Rotates item `mid` into the first position.
2461 /// - Pops the first `mid` items and pushes them to the end.
2462 /// - Rotates `len() - mid` places to the right.
2466 /// If `mid` is greater than `len()`. Note that `mid == len()`
2467 /// does _not_ panic and is a no-op rotation.
2471 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2476 /// use std::collections::VecDeque;
2478 /// let mut buf: VecDeque<_> = (0..10).collect();
2480 /// buf.rotate_left(3);
2481 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2483 /// for i in 1..10 {
2484 /// assert_eq!(i * 3 % 10, buf[0]);
2485 /// buf.rotate_left(3);
2487 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2489 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2490 pub fn rotate_left(&mut self, mid: usize) {
2491 assert!(mid <= self.len());
2492 let k = self.len() - mid;
2494 unsafe { self.rotate_left_inner(mid) }
2496 unsafe { self.rotate_right_inner(k) }
2500 /// Rotates the double-ended queue `k` places to the right.
2503 /// - Rotates the first item into position `k`.
2504 /// - Pops the last `k` items and pushes them to the front.
2505 /// - Rotates `len() - k` places to the left.
2509 /// If `k` is greater than `len()`. Note that `k == len()`
2510 /// does _not_ panic and is a no-op rotation.
2514 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2519 /// use std::collections::VecDeque;
2521 /// let mut buf: VecDeque<_> = (0..10).collect();
2523 /// buf.rotate_right(3);
2524 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2526 /// for i in 1..10 {
2527 /// assert_eq!(0, buf[i * 3 % 10]);
2528 /// buf.rotate_right(3);
2530 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2532 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2533 pub fn rotate_right(&mut self, k: usize) {
2534 assert!(k <= self.len());
2535 let mid = self.len() - k;
2537 unsafe { self.rotate_right_inner(k) }
2539 unsafe { self.rotate_left_inner(mid) }
2543 // SAFETY: the following two methods require that the rotation amount
2544 // be less than half the length of the deque.
2546 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2547 // but than `min` is never more than half the capacity, regardless of x,
2548 // so it's sound to call here because we're calling with something
2549 // less than half the length, which is never above half the capacity.
2551 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2552 debug_assert!(mid * 2 <= self.len());
2554 self.wrap_copy(self.head, self.tail, mid);
2556 self.head = self.wrap_add(self.head, mid);
2557 self.tail = self.wrap_add(self.tail, mid);
2560 unsafe fn rotate_right_inner(&mut self, k: usize) {
2561 debug_assert!(k * 2 <= self.len());
2562 self.head = self.wrap_sub(self.head, k);
2563 self.tail = self.wrap_sub(self.tail, k);
2565 self.wrap_copy(self.tail, self.head, k);
2569 /// Binary searches this `VecDeque` for a given element.
2570 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2572 /// If the value is found then [`Result::Ok`] is returned, containing the
2573 /// index of the matching element. If there are multiple matches, then any
2574 /// one of the matches could be returned. If the value is not found then
2575 /// [`Result::Err`] is returned, containing the index where a matching
2576 /// element could be inserted while maintaining sorted order.
2578 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2580 /// [`contains`]: VecDeque::contains
2581 /// [`binary_search_by`]: VecDeque::binary_search_by
2582 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2583 /// [`partition_point`]: VecDeque::partition_point
2587 /// Looks up a series of four elements. The first is found, with a
2588 /// uniquely determined position; the second and third are not
2589 /// found; the fourth could match any position in `[1, 4]`.
2592 /// use std::collections::VecDeque;
2594 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2596 /// assert_eq!(deque.binary_search(&13), Ok(9));
2597 /// assert_eq!(deque.binary_search(&4), Err(7));
2598 /// assert_eq!(deque.binary_search(&100), Err(13));
2599 /// let r = deque.binary_search(&1);
2600 /// assert!(matches!(r, Ok(1..=4)));
2603 /// If you want to insert an item to a sorted deque, while maintaining
2604 /// sort order, consider using [`partition_point`]:
2607 /// use std::collections::VecDeque;
2609 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2611 /// let idx = deque.partition_point(|&x| x < num);
2612 /// // The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
2613 /// deque.insert(idx, num);
2614 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2616 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2618 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2622 self.binary_search_by(|e| e.cmp(x))
2625 /// Binary searches this `VecDeque` with a comparator function.
2626 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2628 /// The comparator function should implement an order consistent
2629 /// with the sort order of the deque, returning an order code that
2630 /// indicates whether its argument is `Less`, `Equal` or `Greater`
2631 /// than the desired target.
2633 /// If the value is found then [`Result::Ok`] is returned, containing the
2634 /// index of the matching element. If there are multiple matches, then any
2635 /// one of the matches could be returned. If the value is not found then
2636 /// [`Result::Err`] is returned, containing the index where a matching
2637 /// element could be inserted while maintaining sorted order.
2639 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2641 /// [`contains`]: VecDeque::contains
2642 /// [`binary_search`]: VecDeque::binary_search
2643 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2644 /// [`partition_point`]: VecDeque::partition_point
2648 /// Looks up a series of four elements. The first is found, with a
2649 /// uniquely determined position; the second and third are not
2650 /// found; the fourth could match any position in `[1, 4]`.
2653 /// use std::collections::VecDeque;
2655 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2657 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2658 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2659 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2660 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2661 /// assert!(matches!(r, Ok(1..=4)));
2663 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2664 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2666 F: FnMut(&'a T) -> Ordering,
2668 let (front, back) = self.as_slices();
2669 let cmp_back = back.first().map(|elem| f(elem));
2671 if let Some(Ordering::Equal) = cmp_back {
2673 } else if let Some(Ordering::Less) = cmp_back {
2674 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2676 front.binary_search_by(f)
2680 /// Binary searches this `VecDeque` with a key extraction function.
2681 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2683 /// Assumes that the deque is sorted by the key, for instance with
2684 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2686 /// If the value is found then [`Result::Ok`] is returned, containing the
2687 /// index of the matching element. If there are multiple matches, then any
2688 /// one of the matches could be returned. If the value is not found then
2689 /// [`Result::Err`] is returned, containing the index where a matching
2690 /// element could be inserted while maintaining sorted order.
2692 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2694 /// [`contains`]: VecDeque::contains
2695 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2696 /// [`binary_search`]: VecDeque::binary_search
2697 /// [`binary_search_by`]: VecDeque::binary_search_by
2698 /// [`partition_point`]: VecDeque::partition_point
2702 /// Looks up a series of four elements in a slice of pairs sorted by
2703 /// their second elements. The first is found, with a uniquely
2704 /// determined position; the second and third are not found; the
2705 /// fourth could match any position in `[1, 4]`.
2708 /// use std::collections::VecDeque;
2710 /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
2711 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2712 /// (1, 21), (2, 34), (4, 55)].into();
2714 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2715 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2716 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2717 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2718 /// assert!(matches!(r, Ok(1..=4)));
2720 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2722 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2724 F: FnMut(&'a T) -> B,
2727 self.binary_search_by(|k| f(k).cmp(b))
2730 /// Returns the index of the partition point according to the given predicate
2731 /// (the index of the first element of the second partition).
2733 /// The deque is assumed to be partitioned according to the given predicate.
2734 /// This means that all elements for which the predicate returns true are at the start of the deque
2735 /// and all elements for which the predicate returns false are at the end.
2736 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2737 /// (all odd numbers are at the start, all even at the end).
2739 /// If the deque is not partitioned, the returned result is unspecified and meaningless,
2740 /// as this method performs a kind of binary search.
2742 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2744 /// [`binary_search`]: VecDeque::binary_search
2745 /// [`binary_search_by`]: VecDeque::binary_search_by
2746 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2751 /// use std::collections::VecDeque;
2753 /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
2754 /// let i = deque.partition_point(|&x| x < 5);
2756 /// assert_eq!(i, 4);
2757 /// assert!(deque.iter().take(i).all(|&x| x < 5));
2758 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2761 /// If you want to insert an item to a sorted deque, while maintaining
2765 /// use std::collections::VecDeque;
2767 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2769 /// let idx = deque.partition_point(|&x| x < num);
2770 /// deque.insert(idx, num);
2771 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2773 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2774 pub fn partition_point<P>(&self, mut pred: P) -> usize
2776 P: FnMut(&T) -> bool,
2778 let (front, back) = self.as_slices();
2780 if let Some(true) = back.first().map(|v| pred(v)) {
2781 back.partition_point(pred) + front.len()
2783 front.partition_point(pred)
2788 impl<T: Clone, A: Allocator> VecDeque<T, A> {
2789 /// Modifies the deque in-place so that `len()` is equal to new_len,
2790 /// either by removing excess elements from the back or by appending clones of `value`
2796 /// use std::collections::VecDeque;
2798 /// let mut buf = VecDeque::new();
2799 /// buf.push_back(5);
2800 /// buf.push_back(10);
2801 /// buf.push_back(15);
2802 /// assert_eq!(buf, [5, 10, 15]);
2804 /// buf.resize(2, 0);
2805 /// assert_eq!(buf, [5, 10]);
2807 /// buf.resize(5, 20);
2808 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2810 #[stable(feature = "deque_extras", since = "1.16.0")]
2811 pub fn resize(&mut self, new_len: usize, value: T) {
2812 self.resize_with(new_len, || value.clone());
2816 /// Returns the index in the underlying buffer for a given logical element index.
2818 fn wrap_index(index: usize, size: usize) -> usize {
2819 // size is always a power of 2
2820 debug_assert!(size.is_power_of_two());
2824 /// Calculate the number of elements left to be read in the buffer
2826 fn count(tail: usize, head: usize, size: usize) -> usize {
2827 // size is always a power of 2
2828 (head.wrapping_sub(tail)) & (size - 1)
2831 #[stable(feature = "rust1", since = "1.0.0")]
2832 impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
2833 fn eq(&self, other: &Self) -> bool {
2834 if self.len() != other.len() {
2837 let (sa, sb) = self.as_slices();
2838 let (oa, ob) = other.as_slices();
2839 if sa.len() == oa.len() {
2840 sa == oa && sb == ob
2841 } else if sa.len() < oa.len() {
2842 // Always divisible in three sections, for example:
2843 // self: [a b c|d e f]
2844 // other: [0 1 2 3|4 5]
2845 // front = 3, mid = 1,
2846 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2847 let front = sa.len();
2848 let mid = oa.len() - front;
2850 let (oa_front, oa_mid) = oa.split_at(front);
2851 let (sb_mid, sb_back) = sb.split_at(mid);
2852 debug_assert_eq!(sa.len(), oa_front.len());
2853 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2854 debug_assert_eq!(sb_back.len(), ob.len());
2855 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2857 let front = oa.len();
2858 let mid = sa.len() - front;
2860 let (sa_front, sa_mid) = sa.split_at(front);
2861 let (ob_mid, ob_back) = ob.split_at(mid);
2862 debug_assert_eq!(sa_front.len(), oa.len());
2863 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2864 debug_assert_eq!(sb.len(), ob_back.len());
2865 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2870 #[stable(feature = "rust1", since = "1.0.0")]
2871 impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
2873 __impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2874 __impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2875 __impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2876 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2877 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2878 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2880 #[stable(feature = "rust1", since = "1.0.0")]
2881 impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
2882 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2883 self.iter().partial_cmp(other.iter())
2887 #[stable(feature = "rust1", since = "1.0.0")]
2888 impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
2890 fn cmp(&self, other: &Self) -> Ordering {
2891 self.iter().cmp(other.iter())
2895 #[stable(feature = "rust1", since = "1.0.0")]
2896 impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
2897 fn hash<H: Hasher>(&self, state: &mut H) {
2898 self.len().hash(state);
2899 // It's not possible to use Hash::hash_slice on slices
2900 // returned by as_slices method as their length can vary
2901 // in otherwise identical deques.
2903 // Hasher only guarantees equivalence for the exact same
2904 // set of calls to its methods.
2905 self.iter().for_each(|elem| elem.hash(state));
2909 #[stable(feature = "rust1", since = "1.0.0")]
2910 impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
2914 fn index(&self, index: usize) -> &T {
2915 self.get(index).expect("Out of bounds access")
2919 #[stable(feature = "rust1", since = "1.0.0")]
2920 impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
2922 fn index_mut(&mut self, index: usize) -> &mut T {
2923 self.get_mut(index).expect("Out of bounds access")
2927 #[stable(feature = "rust1", since = "1.0.0")]
2928 impl<T> FromIterator<T> for VecDeque<T> {
2929 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
2930 let iterator = iter.into_iter();
2931 let (lower, _) = iterator.size_hint();
2932 let mut deq = VecDeque::with_capacity(lower);
2933 deq.extend(iterator);
2938 #[stable(feature = "rust1", since = "1.0.0")]
2939 impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
2941 type IntoIter = IntoIter<T, A>;
2943 /// Consumes the deque into a front-to-back iterator yielding elements by
2945 fn into_iter(self) -> IntoIter<T, A> {
2950 #[stable(feature = "rust1", since = "1.0.0")]
2951 impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
2953 type IntoIter = Iter<'a, T>;
2955 fn into_iter(self) -> Iter<'a, T> {
2960 #[stable(feature = "rust1", since = "1.0.0")]
2961 impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
2962 type Item = &'a mut T;
2963 type IntoIter = IterMut<'a, T>;
2965 fn into_iter(self) -> IterMut<'a, T> {
2970 #[stable(feature = "rust1", since = "1.0.0")]
2971 impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
2972 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2973 // This function should be the moral equivalent of:
2975 // for item in iter.into_iter() {
2976 // self.push_back(item);
2978 let mut iter = iter.into_iter();
2979 while let Some(element) = iter.next() {
2980 if self.len() == self.capacity() {
2981 let (lower, _) = iter.size_hint();
2982 self.reserve(lower.saturating_add(1));
2985 let head = self.head;
2986 self.head = self.wrap_add(self.head, 1);
2988 self.buffer_write(head, element);
2994 fn extend_one(&mut self, elem: T) {
2995 self.push_back(elem);
2999 fn extend_reserve(&mut self, additional: usize) {
3000 self.reserve(additional);
3004 #[stable(feature = "extend_ref", since = "1.2.0")]
3005 impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
3006 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3007 self.extend(iter.into_iter().cloned());
3011 fn extend_one(&mut self, &elem: &T) {
3012 self.push_back(elem);
3016 fn extend_reserve(&mut self, additional: usize) {
3017 self.reserve(additional);
3021 #[stable(feature = "rust1", since = "1.0.0")]
3022 impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
3023 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3024 f.debug_list().entries(self).finish()
3028 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3029 impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
3030 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3032 /// [`Vec<T>`]: crate::vec::Vec
3033 /// [`VecDeque<T>`]: crate::collections::VecDeque
3035 /// This avoids reallocating where possible, but the conditions for that are
3036 /// strict, and subject to change, and so shouldn't be relied upon unless the
3037 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
3038 fn from(mut other: Vec<T, A>) -> Self {
3039 let len = other.len();
3040 if mem::size_of::<T>() == 0 {
3041 // There's no actual allocation for ZSTs to worry about capacity,
3042 // but `VecDeque` can't handle as much length as `Vec`.
3043 assert!(len < MAXIMUM_ZST_CAPACITY, "capacity overflow");
3045 // We need to resize if the capacity is not a power of two, too small or
3046 // doesn't have at least one free space. We do this while it's still in
3047 // the `Vec` so the items will drop on panic.
3048 let min_cap = cmp::max(MINIMUM_CAPACITY, len) + 1;
3049 let cap = cmp::max(min_cap, other.capacity()).next_power_of_two();
3050 if other.capacity() != cap {
3051 other.reserve_exact(cap - len);
3056 let (other_buf, len, capacity, alloc) = other.into_raw_parts_with_alloc();
3057 let buf = RawVec::from_raw_parts_in(other_buf, capacity, alloc);
3058 VecDeque { tail: 0, head: len, buf }
3063 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3064 impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
3065 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
3067 /// [`Vec<T>`]: crate::vec::Vec
3068 /// [`VecDeque<T>`]: crate::collections::VecDeque
3070 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
3071 /// the circular buffer doesn't happen to be at the beginning of the allocation.
3076 /// use std::collections::VecDeque;
3078 /// // This one is *O*(1).
3079 /// let deque: VecDeque<_> = (1..5).collect();
3080 /// let ptr = deque.as_slices().0.as_ptr();
3081 /// let vec = Vec::from(deque);
3082 /// assert_eq!(vec, [1, 2, 3, 4]);
3083 /// assert_eq!(vec.as_ptr(), ptr);
3085 /// // This one needs data rearranging.
3086 /// let mut deque: VecDeque<_> = (1..5).collect();
3087 /// deque.push_front(9);
3088 /// deque.push_front(8);
3089 /// let ptr = deque.as_slices().1.as_ptr();
3090 /// let vec = Vec::from(deque);
3091 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
3092 /// assert_eq!(vec.as_ptr(), ptr);
3094 fn from(mut other: VecDeque<T, A>) -> Self {
3095 other.make_contiguous();
3098 let other = ManuallyDrop::new(other);
3099 let buf = other.buf.ptr();
3100 let len = other.len();
3101 let cap = other.cap();
3102 let alloc = ptr::read(other.allocator());
3104 if other.tail != 0 {
3105 ptr::copy(buf.add(other.tail), buf, len);
3107 Vec::from_raw_parts_in(buf, len, cap, alloc)
3112 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
3113 impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
3114 /// Converts a `[T; N]` into a `VecDeque<T>`.
3117 /// use std::collections::VecDeque;
3119 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
3120 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
3121 /// assert_eq!(deq1, deq2);
3123 fn from(arr: [T; N]) -> Self {
3124 let mut deq = VecDeque::with_capacity(N);
3125 let arr = ManuallyDrop::new(arr);
3126 if mem::size_of::<T>() != 0 {
3127 // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
3129 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);