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;
57 use self::spec_extend::SpecExtend;
64 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
65 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
67 const MAXIMUM_ZST_CAPACITY: usize = 1 << (usize::BITS - 1); // Largest possible power of two
69 /// A double-ended queue implemented with a growable ring buffer.
71 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
72 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
73 /// push onto the back in this manner, and iterating over `VecDeque` goes front
76 /// A `VecDeque` with a known list of items can be initialized from an array:
79 /// use std::collections::VecDeque;
81 /// let deq = VecDeque::from([-1, 0, 1]);
84 /// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
85 /// in memory. If you want to access the elements as a single slice, such as for
86 /// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
87 /// so that its elements do not wrap, and returns a mutable slice to the
88 /// now-contiguous element sequence.
90 /// [`push_back`]: VecDeque::push_back
91 /// [`pop_front`]: VecDeque::pop_front
92 /// [`extend`]: VecDeque::extend
93 /// [`append`]: VecDeque::append
94 /// [`make_contiguous`]: VecDeque::make_contiguous
95 #[cfg_attr(not(test), rustc_diagnostic_item = "VecDeque")]
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[rustc_insignificant_dtor]
100 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
102 // tail and head are pointers into the buffer. Tail always points
103 // to the first element that could be read, Head always points
104 // to where data should be written.
105 // If tail == head the buffer is empty. The length of the ringbuffer
106 // is defined as the distance between the two.
112 #[stable(feature = "rust1", since = "1.0.0")]
113 impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A> {
114 fn clone(&self) -> Self {
115 let mut deq = Self::with_capacity_in(self.len(), self.allocator().clone());
116 deq.extend(self.iter().cloned());
120 fn clone_from(&mut self, other: &Self) {
121 self.truncate(other.len());
123 let mut iter = PairSlices::from(self, other);
124 while let Some((dst, src)) = iter.next() {
125 dst.clone_from_slice(&src);
128 if iter.has_remainder() {
129 for remainder in iter.remainder() {
130 self.extend(remainder.iter().cloned());
136 #[stable(feature = "rust1", since = "1.0.0")]
137 unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
139 /// Runs the destructor for all items in the slice when it gets dropped (normally or
140 /// during unwinding).
141 struct Dropper<'a, T>(&'a mut [T]);
143 impl<'a, T> Drop for Dropper<'a, T> {
146 ptr::drop_in_place(self.0);
151 let (front, back) = self.as_mut_slices();
153 let _back_dropper = Dropper(back);
155 ptr::drop_in_place(front);
157 // RawVec handles deallocation
161 #[stable(feature = "rust1", since = "1.0.0")]
162 impl<T> Default for VecDeque<T> {
163 /// Creates an empty deque.
165 fn default() -> VecDeque<T> {
170 impl<T, A: Allocator> VecDeque<T, A> {
171 /// Marginally more convenient
173 fn ptr(&self) -> *mut T {
177 /// Marginally more convenient
179 fn cap(&self) -> usize {
180 if mem::size_of::<T>() == 0 {
181 // For zero sized types, we are always at maximum capacity
188 /// Turn ptr into a slice, since the elements of the backing buffer may be uninitialized,
189 /// we will return a slice of [`MaybeUninit<T>`].
191 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
192 /// incorrect usage of this method.
194 /// [zeroed]: mem::MaybeUninit::zeroed
196 unsafe fn buffer_as_slice(&self) -> &[MaybeUninit<T>] {
197 unsafe { slice::from_raw_parts(self.ptr() as *mut MaybeUninit<T>, self.cap()) }
200 /// Turn ptr into a mut slice, since the elements of the backing buffer may be uninitialized,
201 /// we will return a slice of [`MaybeUninit<T>`].
203 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
204 /// incorrect usage of this method.
206 /// [zeroed]: mem::MaybeUninit::zeroed
208 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [MaybeUninit<T>] {
209 unsafe { slice::from_raw_parts_mut(self.ptr() as *mut MaybeUninit<T>, self.cap()) }
212 /// Moves an element out of the buffer
214 unsafe fn buffer_read(&mut self, off: usize) -> T {
215 unsafe { ptr::read(self.ptr().add(off)) }
218 /// Writes an element into the buffer, moving it.
220 unsafe fn buffer_write(&mut self, off: usize, value: T) {
222 ptr::write(self.ptr().add(off), value);
226 /// Returns `true` if the buffer is at full capacity.
228 fn is_full(&self) -> bool {
229 self.cap() - self.len() == 1
232 /// Returns the index in the underlying buffer for a given logical element
235 fn wrap_index(&self, idx: usize) -> usize {
236 wrap_index(idx, self.cap())
239 /// Returns the index in the underlying buffer for a given logical element
242 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
243 wrap_index(idx.wrapping_add(addend), self.cap())
246 /// Returns the index in the underlying buffer for a given logical element
247 /// index - subtrahend.
249 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
250 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
253 /// Copies a contiguous block of memory len long from src to dst
255 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
257 dst + len <= self.cap(),
258 "cpy dst={} src={} len={} cap={}",
265 src + len <= self.cap(),
266 "cpy dst={} src={} len={} cap={}",
273 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
277 /// Copies a contiguous block of memory len long from src to dst
279 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
281 dst + len <= self.cap(),
282 "cno dst={} src={} len={} cap={}",
289 src + len <= self.cap(),
290 "cno dst={} src={} len={} cap={}",
297 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
301 /// Copies a potentially wrapping block of memory len long from src to dest.
302 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
303 /// most one continuous overlapping region between src and dest).
304 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
306 fn diff(a: usize, b: usize) -> usize {
307 if a <= b { b - a } else { a - b }
310 cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
311 "wrc dst={} src={} len={} cap={}",
318 if src == dst || len == 0 {
322 let dst_after_src = self.wrap_sub(dst, src) < len;
324 let src_pre_wrap_len = self.cap() - src;
325 let dst_pre_wrap_len = self.cap() - dst;
326 let src_wraps = src_pre_wrap_len < len;
327 let dst_wraps = dst_pre_wrap_len < len;
329 match (dst_after_src, src_wraps, dst_wraps) {
330 (_, false, false) => {
331 // src doesn't wrap, dst doesn't wrap
334 // 1 [_ _ A A B B C C _]
335 // 2 [_ _ A A A A B B _]
339 self.copy(dst, src, len);
342 (false, false, true) => {
343 // dst before src, src doesn't wrap, dst wraps
346 // 1 [A A B B _ _ _ C C]
347 // 2 [A A B B _ _ _ A A]
348 // 3 [B B B B _ _ _ A A]
352 self.copy(dst, src, dst_pre_wrap_len);
353 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
356 (true, false, true) => {
357 // src before dst, src doesn't wrap, dst wraps
360 // 1 [C C _ _ _ A A B B]
361 // 2 [B B _ _ _ A A B B]
362 // 3 [B B _ _ _ A A A A]
366 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
367 self.copy(dst, src, dst_pre_wrap_len);
370 (false, true, false) => {
371 // dst before src, src wraps, dst doesn't wrap
374 // 1 [C C _ _ _ A A B B]
375 // 2 [C C _ _ _ B B B B]
376 // 3 [C C _ _ _ B B C C]
380 self.copy(dst, src, src_pre_wrap_len);
381 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
384 (true, true, false) => {
385 // src before dst, src wraps, dst doesn't wrap
388 // 1 [A A B B _ _ _ C C]
389 // 2 [A A A A _ _ _ C C]
390 // 3 [C C A A _ _ _ C C]
394 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
395 self.copy(dst, src, src_pre_wrap_len);
398 (false, true, true) => {
399 // dst before src, src wraps, dst wraps
402 // 1 [A B C D _ E F G H]
403 // 2 [A B C D _ E G H H]
404 // 3 [A B C D _ E G H A]
405 // 4 [B C C D _ E G H A]
408 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
409 let delta = dst_pre_wrap_len - src_pre_wrap_len;
411 self.copy(dst, src, src_pre_wrap_len);
412 self.copy(dst + src_pre_wrap_len, 0, delta);
413 self.copy(0, delta, len - dst_pre_wrap_len);
416 (true, true, true) => {
417 // src before dst, src wraps, dst wraps
420 // 1 [A B C D _ E F G H]
421 // 2 [A A B D _ E F G H]
422 // 3 [H A B D _ E F G H]
423 // 4 [H A B D _ E F F G]
426 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
427 let delta = src_pre_wrap_len - dst_pre_wrap_len;
429 self.copy(delta, 0, len - src_pre_wrap_len);
430 self.copy(0, self.cap() - delta, delta);
431 self.copy(dst, src, dst_pre_wrap_len);
437 /// Copies all values from `src` to `dst`, wrapping around if needed.
438 /// Assumes capacity is sufficient.
440 unsafe fn copy_slice(&mut self, dst: usize, src: &[T]) {
441 debug_assert!(src.len() <= self.cap());
442 let head_room = self.cap() - dst;
443 if src.len() <= head_room {
445 ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst), src.len());
448 let (left, right) = src.split_at(head_room);
450 ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst), left.len());
451 ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
456 /// Writes all values from `iter` to `dst`.
460 /// Assumes no wrapping around happens.
461 /// Assumes capacity is sufficient.
463 unsafe fn write_iter(
466 iter: impl Iterator<Item = T>,
469 iter.enumerate().for_each(|(i, element)| unsafe {
470 self.buffer_write(dst + i, element);
475 /// Frobs the head and tail sections around to handle the fact that we
476 /// just reallocated. Unsafe because it trusts old_capacity.
478 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
479 let new_capacity = self.cap();
481 // Move the shortest contiguous section of the ring buffer
483 // [o o o o o o o . ]
485 // A [o o o o o o o . . . . . . . . . ]
487 // [o o . o o o o o ]
489 // B [. . . o o o o o o o . . . . . . ]
491 // [o o o o o . o o ]
493 // C [o o o o o . . . . . . . . . o o ]
495 if self.tail <= self.head {
498 } else if self.head < old_capacity - self.tail {
501 self.copy_nonoverlapping(old_capacity, 0, self.head);
503 self.head += old_capacity;
504 debug_assert!(self.head > self.tail);
507 let new_tail = new_capacity - (old_capacity - self.tail);
509 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
511 self.tail = new_tail;
512 debug_assert!(self.head < self.tail);
514 debug_assert!(self.head < self.cap());
515 debug_assert!(self.tail < self.cap());
516 debug_assert!(self.cap().count_ones() == 1);
520 impl<T> VecDeque<T> {
521 /// Creates an empty deque.
526 /// use std::collections::VecDeque;
528 /// let deque: VecDeque<u32> = VecDeque::new();
531 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn new() -> VecDeque<T> {
534 VecDeque::new_in(Global)
537 /// Creates an empty deque with space for at least `capacity` elements.
542 /// use std::collections::VecDeque;
544 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
547 #[stable(feature = "rust1", since = "1.0.0")]
549 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
550 Self::with_capacity_in(capacity, Global)
554 impl<T, A: Allocator> VecDeque<T, A> {
555 /// Creates an empty deque.
560 /// use std::collections::VecDeque;
562 /// let deque: VecDeque<u32> = VecDeque::new();
565 #[unstable(feature = "allocator_api", issue = "32838")]
566 pub fn new_in(alloc: A) -> VecDeque<T, A> {
567 VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc)
570 /// Creates an empty deque with space for at least `capacity` elements.
575 /// use std::collections::VecDeque;
577 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
579 #[unstable(feature = "allocator_api", issue = "32838")]
580 pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
581 assert!(capacity < 1_usize << usize::BITS - 1, "capacity overflow");
582 // +1 since the ringbuffer always leaves one space empty
583 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
585 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) }
588 /// Provides a reference to the element at the given index.
590 /// Element at index 0 is the front of the queue.
595 /// use std::collections::VecDeque;
597 /// let mut buf = VecDeque::new();
598 /// buf.push_back(3);
599 /// buf.push_back(4);
600 /// buf.push_back(5);
601 /// assert_eq!(buf.get(1), Some(&4));
603 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn get(&self, index: usize) -> Option<&T> {
605 if index < self.len() {
606 let idx = self.wrap_add(self.tail, index);
607 unsafe { Some(&*self.ptr().add(idx)) }
613 /// Provides a mutable reference to the element at the given index.
615 /// Element at index 0 is the front of the queue.
620 /// use std::collections::VecDeque;
622 /// let mut buf = VecDeque::new();
623 /// buf.push_back(3);
624 /// buf.push_back(4);
625 /// buf.push_back(5);
626 /// if let Some(elem) = buf.get_mut(1) {
630 /// assert_eq!(buf[1], 7);
632 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
634 if index < self.len() {
635 let idx = self.wrap_add(self.tail, index);
636 unsafe { Some(&mut *self.ptr().add(idx)) }
642 /// Swaps elements at indices `i` and `j`.
644 /// `i` and `j` may be equal.
646 /// Element at index 0 is the front of the queue.
650 /// Panics if either index is out of bounds.
655 /// use std::collections::VecDeque;
657 /// let mut buf = VecDeque::new();
658 /// buf.push_back(3);
659 /// buf.push_back(4);
660 /// buf.push_back(5);
661 /// assert_eq!(buf, [3, 4, 5]);
663 /// assert_eq!(buf, [5, 4, 3]);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn swap(&mut self, i: usize, j: usize) {
667 assert!(i < self.len());
668 assert!(j < self.len());
669 let ri = self.wrap_add(self.tail, i);
670 let rj = self.wrap_add(self.tail, j);
671 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
674 /// Returns the number of elements the deque can hold without
680 /// use std::collections::VecDeque;
682 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
683 /// assert!(buf.capacity() >= 10);
686 #[stable(feature = "rust1", since = "1.0.0")]
687 pub fn capacity(&self) -> usize {
691 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
692 /// given deque. Does nothing if the capacity is already sufficient.
694 /// Note that the allocator may give the collection more space than it requests. Therefore
695 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
696 /// insertions are expected.
700 /// Panics if the new capacity overflows `usize`.
705 /// use std::collections::VecDeque;
707 /// let mut buf: VecDeque<i32> = [1].into();
708 /// buf.reserve_exact(10);
709 /// assert!(buf.capacity() >= 11);
712 /// [`reserve`]: VecDeque::reserve
713 #[stable(feature = "rust1", since = "1.0.0")]
714 pub fn reserve_exact(&mut self, additional: usize) {
715 self.reserve(additional);
718 /// Reserves capacity for at least `additional` more elements to be inserted in the given
719 /// deque. The collection may reserve more space to avoid frequent reallocations.
723 /// Panics if the new capacity overflows `usize`.
728 /// use std::collections::VecDeque;
730 /// let mut buf: VecDeque<i32> = [1].into();
732 /// assert!(buf.capacity() >= 11);
734 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn reserve(&mut self, additional: usize) {
736 let old_cap = self.cap();
737 let used_cap = self.len() + 1;
738 let new_cap = used_cap
739 .checked_add(additional)
740 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
741 .expect("capacity overflow");
743 if new_cap > old_cap {
744 self.buf.reserve_exact(used_cap, new_cap - used_cap);
746 self.handle_capacity_increase(old_cap);
751 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
752 /// be inserted in the given deque. After calling `try_reserve_exact`,
753 /// capacity will be greater than or equal to `self.len() + additional`.
754 /// Does nothing if the capacity is already sufficient.
756 /// Note that the allocator may give the collection more space than it
757 /// requests. Therefore, capacity can not be relied upon to be precisely
758 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
760 /// [`try_reserve`]: VecDeque::try_reserve
764 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
770 /// use std::collections::TryReserveError;
771 /// use std::collections::VecDeque;
773 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
774 /// let mut output = VecDeque::new();
776 /// // Pre-reserve the memory, exiting if we can't
777 /// output.try_reserve_exact(data.len())?;
779 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
780 /// output.extend(data.iter().map(|&val| {
781 /// val * 2 + 5 // very complicated
786 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
788 #[stable(feature = "try_reserve", since = "1.57.0")]
789 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
790 self.try_reserve(additional)
793 /// Tries to reserve capacity for at least `additional` more elements to be inserted
794 /// in the given deque. The collection may reserve more space to avoid
795 /// frequent reallocations. After calling `try_reserve`, capacity will be
796 /// greater than or equal to `self.len() + additional`. Does nothing if
797 /// capacity is already sufficient.
801 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
807 /// use std::collections::TryReserveError;
808 /// use std::collections::VecDeque;
810 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
811 /// let mut output = VecDeque::new();
813 /// // Pre-reserve the memory, exiting if we can't
814 /// output.try_reserve(data.len())?;
816 /// // Now we know this can't OOM in the middle of our complex work
817 /// output.extend(data.iter().map(|&val| {
818 /// val * 2 + 5 // very complicated
823 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
825 #[stable(feature = "try_reserve", since = "1.57.0")]
826 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
827 let old_cap = self.cap();
828 let used_cap = self.len() + 1;
829 let new_cap = used_cap
830 .checked_add(additional)
831 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
832 .ok_or(TryReserveErrorKind::CapacityOverflow)?;
834 if new_cap > old_cap {
835 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
837 self.handle_capacity_increase(old_cap);
843 /// Shrinks the capacity of the deque as much as possible.
845 /// It will drop down as close as possible to the length but the allocator may still inform the
846 /// deque that there is space for a few more elements.
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_fit();
857 /// assert!(buf.capacity() >= 4);
859 #[stable(feature = "deque_extras_15", since = "1.5.0")]
860 pub fn shrink_to_fit(&mut self) {
864 /// Shrinks the capacity of the deque with a lower bound.
866 /// The capacity will remain at least as large as both the length
867 /// and the supplied value.
869 /// If the current capacity is less than the lower limit, this is a no-op.
874 /// use std::collections::VecDeque;
876 /// let mut buf = VecDeque::with_capacity(15);
877 /// buf.extend(0..4);
878 /// assert_eq!(buf.capacity(), 15);
879 /// buf.shrink_to(6);
880 /// assert!(buf.capacity() >= 6);
881 /// buf.shrink_to(0);
882 /// assert!(buf.capacity() >= 4);
884 #[stable(feature = "shrink_to", since = "1.56.0")]
885 pub fn shrink_to(&mut self, min_capacity: usize) {
886 let min_capacity = cmp::min(min_capacity, self.capacity());
887 // We don't have to worry about an overflow as neither `self.len()` nor `self.capacity()`
888 // can ever be `usize::MAX`. +1 as the ringbuffer always leaves one space empty.
889 let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
890 .next_power_of_two();
892 if target_cap < self.cap() {
893 // There are three cases of interest:
894 // All elements are out of desired bounds
895 // Elements are contiguous, and head is out of desired bounds
896 // Elements are discontiguous, and tail is out of desired bounds
898 // At all other times, element positions are unaffected.
900 // Indicates that elements at the head should be moved.
901 let head_outside = self.head == 0 || self.head >= target_cap;
902 // Move elements from out of desired bounds (positions after target_cap)
903 if self.tail >= target_cap && head_outside {
905 // [. . . . . . . . o o o o o o o . ]
907 // [o o o o o o o . ]
909 self.copy_nonoverlapping(0, self.tail, self.len());
911 self.head = self.len();
913 } else if self.tail != 0 && self.tail < target_cap && head_outside {
915 // [. . . o o o o o o o . . . . . . ]
917 // [o o . o o o o o ]
918 let len = self.wrap_sub(self.head, target_cap);
920 self.copy_nonoverlapping(0, target_cap, len);
923 debug_assert!(self.head < self.tail);
924 } else if self.tail >= target_cap {
926 // [o o o o o . . . . . . . . . o o ]
928 // [o o o o o . o o ]
929 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
930 let len = self.cap() - self.tail;
931 let new_tail = target_cap - len;
933 self.copy_nonoverlapping(new_tail, self.tail, len);
935 self.tail = new_tail;
936 debug_assert!(self.head < self.tail);
939 self.buf.shrink_to_fit(target_cap);
941 debug_assert!(self.head < self.cap());
942 debug_assert!(self.tail < self.cap());
943 debug_assert!(self.cap().count_ones() == 1);
947 /// Shortens the deque, keeping the first `len` elements and dropping
950 /// If `len` is greater than the deque's current length, this has no
956 /// use std::collections::VecDeque;
958 /// let mut buf = VecDeque::new();
959 /// buf.push_back(5);
960 /// buf.push_back(10);
961 /// buf.push_back(15);
962 /// assert_eq!(buf, [5, 10, 15]);
964 /// assert_eq!(buf, [5]);
966 #[stable(feature = "deque_extras", since = "1.16.0")]
967 pub fn truncate(&mut self, len: usize) {
968 /// Runs the destructor for all items in the slice when it gets dropped (normally or
969 /// during unwinding).
970 struct Dropper<'a, T>(&'a mut [T]);
972 impl<'a, T> Drop for Dropper<'a, T> {
975 ptr::drop_in_place(self.0);
982 // * Any slice passed to `drop_in_place` is valid; the second case has
983 // `len <= front.len()` and returning on `len > self.len()` ensures
984 // `begin <= back.len()` in the first case
985 // * The head of the VecDeque is moved before calling `drop_in_place`,
986 // so no value is dropped twice if `drop_in_place` panics
988 if len > self.len() {
991 let num_dropped = self.len() - len;
992 let (front, back) = self.as_mut_slices();
993 if len > front.len() {
994 let begin = len - front.len();
995 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
996 self.head = self.wrap_sub(self.head, num_dropped);
997 ptr::drop_in_place(drop_back);
999 let drop_back = back as *mut _;
1000 let drop_front = front.get_unchecked_mut(len..) as *mut _;
1001 self.head = self.wrap_sub(self.head, num_dropped);
1003 // Make sure the second half is dropped even when a destructor
1004 // in the first one panics.
1005 let _back_dropper = Dropper(&mut *drop_back);
1006 ptr::drop_in_place(drop_front);
1011 /// Returns a reference to the underlying allocator.
1012 #[unstable(feature = "allocator_api", issue = "32838")]
1014 pub fn allocator(&self) -> &A {
1015 self.buf.allocator()
1018 /// Returns a front-to-back iterator.
1023 /// use std::collections::VecDeque;
1025 /// let mut buf = VecDeque::new();
1026 /// buf.push_back(5);
1027 /// buf.push_back(3);
1028 /// buf.push_back(4);
1029 /// let b: &[_] = &[&5, &3, &4];
1030 /// let c: Vec<&i32> = buf.iter().collect();
1031 /// assert_eq!(&c[..], b);
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 pub fn iter(&self) -> Iter<'_, T> {
1035 Iter::new(unsafe { self.buffer_as_slice() }, self.tail, self.head)
1038 /// Returns a front-to-back iterator that returns mutable references.
1043 /// use std::collections::VecDeque;
1045 /// let mut buf = VecDeque::new();
1046 /// buf.push_back(5);
1047 /// buf.push_back(3);
1048 /// buf.push_back(4);
1049 /// for num in buf.iter_mut() {
1050 /// *num = *num - 2;
1052 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1053 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1057 // SAFETY: The internal `IterMut` safety invariant is established because the
1058 // `ring` we create is a dereferenceable slice for lifetime '_.
1059 let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1061 unsafe { IterMut::new(ring, self.tail, self.head, PhantomData) }
1064 /// Returns a pair of slices which contain, in order, the contents of the
1067 /// If [`make_contiguous`] was previously called, all elements of the
1068 /// deque will be in the first slice and the second slice will be empty.
1070 /// [`make_contiguous`]: VecDeque::make_contiguous
1075 /// use std::collections::VecDeque;
1077 /// let mut deque = VecDeque::new();
1079 /// deque.push_back(0);
1080 /// deque.push_back(1);
1081 /// deque.push_back(2);
1083 /// assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..]));
1085 /// deque.push_front(10);
1086 /// deque.push_front(9);
1088 /// assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1091 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1092 pub fn as_slices(&self) -> (&[T], &[T]) {
1094 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
1095 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
1097 let buf = self.buffer_as_slice();
1098 let (front, back) = RingSlices::ring_slices(buf, self.head, self.tail);
1099 (MaybeUninit::slice_assume_init_ref(front), MaybeUninit::slice_assume_init_ref(back))
1103 /// Returns a pair of slices which contain, in order, the contents of the
1106 /// If [`make_contiguous`] was previously called, all elements of the
1107 /// deque will be in the first slice and the second slice will be empty.
1109 /// [`make_contiguous`]: VecDeque::make_contiguous
1114 /// use std::collections::VecDeque;
1116 /// let mut deque = VecDeque::new();
1118 /// deque.push_back(0);
1119 /// deque.push_back(1);
1121 /// deque.push_front(10);
1122 /// deque.push_front(9);
1124 /// deque.as_mut_slices().0[0] = 42;
1125 /// deque.as_mut_slices().1[0] = 24;
1126 /// assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
1129 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1130 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1132 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
1133 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
1135 let head = self.head;
1136 let tail = self.tail;
1137 let buf = self.buffer_as_mut_slice();
1138 let (front, back) = RingSlices::ring_slices(buf, head, tail);
1139 (MaybeUninit::slice_assume_init_mut(front), MaybeUninit::slice_assume_init_mut(back))
1143 /// Returns the number of elements in the deque.
1148 /// use std::collections::VecDeque;
1150 /// let mut deque = VecDeque::new();
1151 /// assert_eq!(deque.len(), 0);
1152 /// deque.push_back(1);
1153 /// assert_eq!(deque.len(), 1);
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub fn len(&self) -> usize {
1157 count(self.tail, self.head, self.cap())
1160 /// Returns `true` if the deque is empty.
1165 /// use std::collections::VecDeque;
1167 /// let mut deque = VecDeque::new();
1168 /// assert!(deque.is_empty());
1169 /// deque.push_front(1);
1170 /// assert!(!deque.is_empty());
1172 #[stable(feature = "rust1", since = "1.0.0")]
1173 pub fn is_empty(&self) -> bool {
1174 self.tail == self.head
1177 fn range_tail_head<R>(&self, range: R) -> (usize, usize)
1179 R: RangeBounds<usize>,
1181 let Range { start, end } = slice::range(range, ..self.len());
1182 let tail = self.wrap_add(self.tail, start);
1183 let head = self.wrap_add(self.tail, end);
1187 /// Creates an iterator that covers the specified range in the deque.
1191 /// Panics if the starting point is greater than the end point or if
1192 /// the end point is greater than the length of the deque.
1197 /// use std::collections::VecDeque;
1199 /// let deque: VecDeque<_> = [1, 2, 3].into();
1200 /// let range = deque.range(2..).copied().collect::<VecDeque<_>>();
1201 /// assert_eq!(range, [3]);
1203 /// // A full range covers all contents
1204 /// let all = deque.range(..);
1205 /// assert_eq!(all.len(), 3);
1208 #[stable(feature = "deque_range", since = "1.51.0")]
1209 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1211 R: RangeBounds<usize>,
1213 let (tail, head) = self.range_tail_head(range);
1214 // The shared reference we have in &self is maintained in the '_ of Iter.
1215 Iter::new(unsafe { self.buffer_as_slice() }, tail, head)
1218 /// Creates an iterator that covers the specified mutable range in the deque.
1222 /// Panics if the starting point is greater than the end point or if
1223 /// the end point is greater than the length of the deque.
1228 /// use std::collections::VecDeque;
1230 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1231 /// for v in deque.range_mut(2..) {
1234 /// assert_eq!(deque, [1, 2, 6]);
1236 /// // A full range covers all contents
1237 /// for v in deque.range_mut(..) {
1240 /// assert_eq!(deque, [2, 4, 12]);
1243 #[stable(feature = "deque_range", since = "1.51.0")]
1244 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1246 R: RangeBounds<usize>,
1248 let (tail, head) = self.range_tail_head(range);
1250 // SAFETY: The internal `IterMut` safety invariant is established because the
1251 // `ring` we create is a dereferenceable slice for lifetime '_.
1252 let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1254 unsafe { IterMut::new(ring, tail, head, PhantomData) }
1257 /// Removes the specified range from the deque in bulk, returning all
1258 /// removed elements as an iterator. If the iterator is dropped before
1259 /// being fully consumed, it drops the remaining removed elements.
1261 /// The returned iterator keeps a mutable borrow on the queue to optimize
1262 /// its implementation.
1267 /// Panics if the starting point is greater than the end point or if
1268 /// the end point is greater than the length of the deque.
1272 /// If the returned iterator goes out of scope without being dropped (due to
1273 /// [`mem::forget`], for example), the deque may have lost and leaked
1274 /// elements arbitrarily, including elements outside the range.
1279 /// use std::collections::VecDeque;
1281 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1282 /// let drained = deque.drain(2..).collect::<VecDeque<_>>();
1283 /// assert_eq!(drained, [3]);
1284 /// assert_eq!(deque, [1, 2]);
1286 /// // A full range clears all contents, like `clear()` does
1287 /// deque.drain(..);
1288 /// assert!(deque.is_empty());
1291 #[stable(feature = "drain", since = "1.6.0")]
1292 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1294 R: RangeBounds<usize>,
1298 // When the Drain is first created, the source deque is shortened to
1299 // make sure no uninitialized or moved-from elements are accessible at
1300 // all if the Drain's destructor never gets to run.
1302 // Drain will ptr::read out the values to remove.
1303 // When finished, the remaining data will be copied back to cover the hole,
1304 // and the head/tail values will be restored correctly.
1306 let (drain_tail, drain_head) = self.range_tail_head(range);
1308 // The deque's elements are parted into three segments:
1309 // * self.tail -> drain_tail
1310 // * drain_tail -> drain_head
1311 // * drain_head -> self.head
1313 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1315 // We store drain_tail as self.head, and drain_head and self.head as
1316 // after_tail and after_head respectively on the Drain. This also
1317 // truncates the effective array such that if the Drain is leaked, we
1318 // have forgotten about the potentially moved values after the start of
1322 // [. . . o o x x o o . . .]
1324 let head = self.head;
1326 // "forget" about the values after the start of the drain until after
1327 // the drain is complete and the Drain destructor is run.
1328 self.head = drain_tail;
1330 let deque = NonNull::from(&mut *self);
1332 // Crucially, we only create shared references from `self` here and read from
1333 // it. We do not write to `self` nor reborrow to a mutable reference.
1334 // Hence the raw pointer we created above, for `deque`, remains valid.
1335 let ring = self.buffer_as_slice();
1336 let iter = Iter::new(ring, drain_tail, drain_head);
1338 Drain::new(drain_head, head, iter, deque)
1342 /// Clears the deque, removing all values.
1347 /// use std::collections::VecDeque;
1349 /// let mut deque = VecDeque::new();
1350 /// deque.push_back(1);
1352 /// assert!(deque.is_empty());
1354 #[stable(feature = "rust1", since = "1.0.0")]
1356 pub fn clear(&mut self) {
1360 /// Returns `true` if the deque contains an element equal to the
1363 /// This operation is *O*(*n*).
1365 /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
1367 /// [`binary_search`]: VecDeque::binary_search
1372 /// use std::collections::VecDeque;
1374 /// let mut deque: VecDeque<u32> = VecDeque::new();
1376 /// deque.push_back(0);
1377 /// deque.push_back(1);
1379 /// assert_eq!(deque.contains(&1), true);
1380 /// assert_eq!(deque.contains(&10), false);
1382 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1383 pub fn contains(&self, x: &T) -> bool
1387 let (a, b) = self.as_slices();
1388 a.contains(x) || b.contains(x)
1391 /// Provides a reference to the front element, or `None` if the deque is
1397 /// use std::collections::VecDeque;
1399 /// let mut d = VecDeque::new();
1400 /// assert_eq!(d.front(), None);
1404 /// assert_eq!(d.front(), Some(&1));
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 pub fn front(&self) -> Option<&T> {
1411 /// Provides a mutable reference to the front element, or `None` if the
1417 /// use std::collections::VecDeque;
1419 /// let mut d = VecDeque::new();
1420 /// assert_eq!(d.front_mut(), None);
1424 /// match d.front_mut() {
1425 /// Some(x) => *x = 9,
1428 /// assert_eq!(d.front(), Some(&9));
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 pub fn front_mut(&mut self) -> Option<&mut T> {
1435 /// Provides a reference to the back element, or `None` if the deque is
1441 /// use std::collections::VecDeque;
1443 /// let mut d = VecDeque::new();
1444 /// assert_eq!(d.back(), None);
1448 /// assert_eq!(d.back(), Some(&2));
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 pub fn back(&self) -> Option<&T> {
1452 self.get(self.len().wrapping_sub(1))
1455 /// Provides a mutable reference to the back element, or `None` if the
1461 /// use std::collections::VecDeque;
1463 /// let mut d = VecDeque::new();
1464 /// assert_eq!(d.back(), None);
1468 /// match d.back_mut() {
1469 /// Some(x) => *x = 9,
1472 /// assert_eq!(d.back(), Some(&9));
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 pub fn back_mut(&mut self) -> Option<&mut T> {
1476 self.get_mut(self.len().wrapping_sub(1))
1479 /// Removes the first element and returns it, or `None` if the deque is
1485 /// use std::collections::VecDeque;
1487 /// let mut d = VecDeque::new();
1491 /// assert_eq!(d.pop_front(), Some(1));
1492 /// assert_eq!(d.pop_front(), Some(2));
1493 /// assert_eq!(d.pop_front(), None);
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 pub fn pop_front(&mut self) -> Option<T> {
1497 if self.is_empty() {
1500 let tail = self.tail;
1501 self.tail = self.wrap_add(self.tail, 1);
1502 unsafe { Some(self.buffer_read(tail)) }
1506 /// Removes the last element from the deque and returns it, or `None` if
1512 /// use std::collections::VecDeque;
1514 /// let mut buf = VecDeque::new();
1515 /// assert_eq!(buf.pop_back(), None);
1516 /// buf.push_back(1);
1517 /// buf.push_back(3);
1518 /// assert_eq!(buf.pop_back(), Some(3));
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 pub fn pop_back(&mut self) -> Option<T> {
1522 if self.is_empty() {
1525 self.head = self.wrap_sub(self.head, 1);
1526 let head = self.head;
1527 unsafe { Some(self.buffer_read(head)) }
1531 /// Prepends an element to the deque.
1536 /// use std::collections::VecDeque;
1538 /// let mut d = VecDeque::new();
1539 /// d.push_front(1);
1540 /// d.push_front(2);
1541 /// assert_eq!(d.front(), Some(&2));
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 pub fn push_front(&mut self, value: T) {
1549 self.tail = self.wrap_sub(self.tail, 1);
1550 let tail = self.tail;
1552 self.buffer_write(tail, value);
1556 /// Appends an element to the back of the deque.
1561 /// use std::collections::VecDeque;
1563 /// let mut buf = VecDeque::new();
1564 /// buf.push_back(1);
1565 /// buf.push_back(3);
1566 /// assert_eq!(3, *buf.back().unwrap());
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 pub fn push_back(&mut self, value: T) {
1574 let head = self.head;
1575 self.head = self.wrap_add(self.head, 1);
1576 unsafe { self.buffer_write(head, value) }
1580 fn is_contiguous(&self) -> bool {
1581 // FIXME: Should we consider `head == 0` to mean
1582 // that `self` is contiguous?
1583 self.tail <= self.head
1586 /// Removes an element from anywhere in the deque and returns it,
1587 /// replacing it with the first element.
1589 /// This does not preserve ordering, but is *O*(1).
1591 /// Returns `None` if `index` is out of bounds.
1593 /// Element at index 0 is the front of the queue.
1598 /// use std::collections::VecDeque;
1600 /// let mut buf = VecDeque::new();
1601 /// assert_eq!(buf.swap_remove_front(0), None);
1602 /// buf.push_back(1);
1603 /// buf.push_back(2);
1604 /// buf.push_back(3);
1605 /// assert_eq!(buf, [1, 2, 3]);
1607 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1608 /// assert_eq!(buf, [2, 1]);
1610 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1611 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1612 let length = self.len();
1613 if length > 0 && index < length && index != 0 {
1614 self.swap(index, 0);
1615 } else if index >= length {
1621 /// Removes an element from anywhere in the deque and returns it,
1622 /// replacing it with the last element.
1624 /// This does not preserve ordering, but is *O*(1).
1626 /// Returns `None` if `index` is out of bounds.
1628 /// Element at index 0 is the front of the queue.
1633 /// use std::collections::VecDeque;
1635 /// let mut buf = VecDeque::new();
1636 /// assert_eq!(buf.swap_remove_back(0), None);
1637 /// buf.push_back(1);
1638 /// buf.push_back(2);
1639 /// buf.push_back(3);
1640 /// assert_eq!(buf, [1, 2, 3]);
1642 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1643 /// assert_eq!(buf, [3, 2]);
1645 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1646 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1647 let length = self.len();
1648 if length > 0 && index < length - 1 {
1649 self.swap(index, length - 1);
1650 } else if index >= length {
1656 /// Inserts an element at `index` within the deque, shifting all elements
1657 /// with indices greater than or equal to `index` towards the back.
1659 /// Element at index 0 is the front of the queue.
1663 /// Panics if `index` is greater than deque's length
1668 /// use std::collections::VecDeque;
1670 /// let mut vec_deque = VecDeque::new();
1671 /// vec_deque.push_back('a');
1672 /// vec_deque.push_back('b');
1673 /// vec_deque.push_back('c');
1674 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1676 /// vec_deque.insert(1, 'd');
1677 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1679 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1680 pub fn insert(&mut self, index: usize, value: T) {
1681 assert!(index <= self.len(), "index out of bounds");
1686 // Move the least number of elements in the ring buffer and insert
1689 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1691 // There are three main cases:
1692 // Elements are contiguous
1693 // - special case when tail is 0
1694 // Elements are discontiguous and the insert is in the tail section
1695 // Elements are discontiguous and the insert is in the head section
1697 // For each of those there are two more cases:
1698 // Insert is closer to tail
1699 // Insert is closer to head
1701 // Key: H - self.head
1703 // o - Valid element
1704 // I - Insertion element
1705 // A - The element that should be after the insertion point
1706 // M - Indicates element was moved
1708 let idx = self.wrap_add(self.tail, index);
1710 let distance_to_tail = index;
1711 let distance_to_head = self.len() - index;
1713 let contiguous = self.is_contiguous();
1715 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1716 (true, true, _) if index == 0 => {
1721 // [A o o o o o o . . . . . . . . .]
1724 // [A o o o o o o o . . . . . I]
1727 self.tail = self.wrap_sub(self.tail, 1);
1729 (true, true, _) => {
1731 // contiguous, insert closer to tail:
1734 // [. . . o o A o o o o . . . . . .]
1737 // [. . o o I A o o o o . . . . . .]
1740 // contiguous, insert closer to tail and tail is 0:
1744 // [o o A o o o o . . . . . . . . .]
1747 // [o I A o o o o o . . . . . . . o]
1750 let new_tail = self.wrap_sub(self.tail, 1);
1752 self.copy(new_tail, self.tail, 1);
1753 // Already moved the tail, so we only copy `index - 1` elements.
1754 self.copy(self.tail, self.tail + 1, index - 1);
1756 self.tail = new_tail;
1759 (true, false, _) => {
1761 // contiguous, insert closer to head:
1764 // [. . . o o o o A o o . . . . . .]
1767 // [. . . o o o o I A o o . . . . .]
1770 self.copy(idx + 1, idx, self.head - idx);
1771 self.head = self.wrap_add(self.head, 1);
1774 (false, true, true) => {
1776 // discontiguous, insert closer to tail, tail section:
1779 // [o o o o o o . . . . . o o A o o]
1782 // [o o o o o o . . . . o o I A o o]
1785 self.copy(self.tail - 1, self.tail, index);
1789 (false, false, true) => {
1791 // discontiguous, insert closer to head, tail section:
1794 // [o o . . . . . . . o o o o o A o]
1797 // [o o o . . . . . . o o o o o I A]
1800 // copy elements up to new head
1801 self.copy(1, 0, self.head);
1803 // copy last element into empty spot at bottom of buffer
1804 self.copy(0, self.cap() - 1, 1);
1806 // move elements from idx to end forward not including ^ element
1807 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1812 (false, true, false) if idx == 0 => {
1814 // discontiguous, insert is closer to tail, head section,
1815 // and is at index zero in the internal buffer:
1818 // [A o o o o o o o o o . . . o o o]
1821 // [A o o o o o o o o o . . o o o I]
1824 // copy elements up to new tail
1825 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1827 // copy last element into empty spot at bottom of buffer
1828 self.copy(self.cap() - 1, 0, 1);
1833 (false, true, false) => {
1835 // discontiguous, insert closer to tail, head section:
1838 // [o o o A o o o o o o . . . o o o]
1841 // [o o I A o o o o o o . . o o o o]
1844 // copy elements up to new tail
1845 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1847 // copy last element into empty spot at bottom of buffer
1848 self.copy(self.cap() - 1, 0, 1);
1850 // move elements from idx-1 to end forward not including ^ element
1851 self.copy(0, 1, idx - 1);
1856 (false, false, false) => {
1858 // discontiguous, insert closer to head, head section:
1861 // [o o o o A o o . . . . . . o o o]
1864 // [o o o o I A o o . . . . . o o o]
1867 self.copy(idx + 1, idx, self.head - idx);
1873 // tail might've been changed so we need to recalculate
1874 let new_idx = self.wrap_add(self.tail, index);
1876 self.buffer_write(new_idx, value);
1880 /// Removes and returns the element at `index` from the deque.
1881 /// Whichever end is closer to the removal point will be moved to make
1882 /// room, and all the affected elements will be moved to new positions.
1883 /// Returns `None` if `index` is out of bounds.
1885 /// Element at index 0 is the front of the queue.
1890 /// use std::collections::VecDeque;
1892 /// let mut buf = VecDeque::new();
1893 /// buf.push_back(1);
1894 /// buf.push_back(2);
1895 /// buf.push_back(3);
1896 /// assert_eq!(buf, [1, 2, 3]);
1898 /// assert_eq!(buf.remove(1), Some(2));
1899 /// assert_eq!(buf, [1, 3]);
1901 #[stable(feature = "rust1", since = "1.0.0")]
1902 pub fn remove(&mut self, index: usize) -> Option<T> {
1903 if self.is_empty() || self.len() <= index {
1907 // There are three main cases:
1908 // Elements are contiguous
1909 // Elements are discontiguous and the removal is in the tail section
1910 // Elements are discontiguous and the removal is in the head section
1911 // - special case when elements are technically contiguous,
1912 // but self.head = 0
1914 // For each of those there are two more cases:
1915 // Insert is closer to tail
1916 // Insert is closer to head
1918 // Key: H - self.head
1920 // o - Valid element
1921 // x - Element marked for removal
1922 // R - Indicates element that is being removed
1923 // M - Indicates element was moved
1925 let idx = self.wrap_add(self.tail, index);
1927 let elem = unsafe { Some(self.buffer_read(idx)) };
1929 let distance_to_tail = index;
1930 let distance_to_head = self.len() - index;
1932 let contiguous = self.is_contiguous();
1934 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1935 (true, true, _) => {
1937 // contiguous, remove closer to tail:
1940 // [. . . o o x o o o o . . . . . .]
1943 // [. . . . o o o o o o . . . . . .]
1946 self.copy(self.tail + 1, self.tail, index);
1950 (true, false, _) => {
1952 // contiguous, remove closer to head:
1955 // [. . . o o o o x o o . . . . . .]
1958 // [. . . o o o o o o . . . . . . .]
1961 self.copy(idx, idx + 1, self.head - idx - 1);
1965 (false, true, true) => {
1967 // discontiguous, remove closer to tail, tail section:
1970 // [o o o o o o . . . . . o o x o o]
1973 // [o o o o o o . . . . . . o o o o]
1976 self.copy(self.tail + 1, self.tail, index);
1977 self.tail = self.wrap_add(self.tail, 1);
1980 (false, false, false) => {
1982 // discontiguous, remove closer to head, head section:
1985 // [o o o o x o o . . . . . . o o o]
1988 // [o o o o o o . . . . . . . o o o]
1991 self.copy(idx, idx + 1, self.head - idx - 1);
1995 (false, false, true) => {
1997 // discontiguous, remove closer to head, tail section:
2000 // [o o o . . . . . . o o o o o x o]
2003 // [o o . . . . . . . o o o o o o o]
2006 // or quasi-discontiguous, remove next to head, tail section:
2009 // [. . . . . . . . . o o o o o x o]
2012 // [. . . . . . . . . o o o o o o .]
2015 // draw in elements in the tail section
2016 self.copy(idx, idx + 1, self.cap() - idx - 1);
2018 // Prevents underflow.
2020 // copy first element into empty spot
2021 self.copy(self.cap() - 1, 0, 1);
2023 // move elements in the head section backwards
2024 self.copy(0, 1, self.head - 1);
2027 self.head = self.wrap_sub(self.head, 1);
2030 (false, true, false) => {
2032 // discontiguous, remove closer to tail, head section:
2035 // [o o x o o o o o o o . . . o o o]
2038 // [o o o o o o o o o o . . . . o o]
2041 // draw in elements up to idx
2042 self.copy(1, 0, idx);
2044 // copy last element into empty spot
2045 self.copy(0, self.cap() - 1, 1);
2047 // move elements from tail to end forward, excluding the last one
2048 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
2050 self.tail = self.wrap_add(self.tail, 1);
2058 /// Splits the deque into two at the given index.
2060 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2061 /// and the returned deque contains elements `[at, len)`.
2063 /// Note that the capacity of `self` does not change.
2065 /// Element at index 0 is the front of the queue.
2069 /// Panics if `at > len`.
2074 /// use std::collections::VecDeque;
2076 /// let mut buf: VecDeque<_> = [1, 2, 3].into();
2077 /// let buf2 = buf.split_off(1);
2078 /// assert_eq!(buf, [1]);
2079 /// assert_eq!(buf2, [2, 3]);
2082 #[must_use = "use `.truncate()` if you don't need the other half"]
2083 #[stable(feature = "split_off", since = "1.4.0")]
2084 pub fn split_off(&mut self, at: usize) -> Self
2088 let len = self.len();
2089 assert!(at <= len, "`at` out of bounds");
2091 let other_len = len - at;
2092 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2095 let (first_half, second_half) = self.as_slices();
2097 let first_len = first_half.len();
2098 let second_len = second_half.len();
2100 // `at` lies in the first half.
2101 let amount_in_first = first_len - at;
2103 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2105 // just take all of the second half.
2106 ptr::copy_nonoverlapping(
2107 second_half.as_ptr(),
2108 other.ptr().add(amount_in_first),
2112 // `at` lies in the second half, need to factor in the elements we skipped
2113 // in the first half.
2114 let offset = at - first_len;
2115 let amount_in_second = second_len - offset;
2116 ptr::copy_nonoverlapping(
2117 second_half.as_ptr().add(offset),
2124 // Cleanup where the ends of the buffers are
2125 self.head = self.wrap_sub(self.head, other_len);
2126 other.head = other.wrap_index(other_len);
2131 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2135 /// Panics if the new number of elements in self overflows a `usize`.
2140 /// use std::collections::VecDeque;
2142 /// let mut buf: VecDeque<_> = [1, 2].into();
2143 /// let mut buf2: VecDeque<_> = [3, 4].into();
2144 /// buf.append(&mut buf2);
2145 /// assert_eq!(buf, [1, 2, 3, 4]);
2146 /// assert_eq!(buf2, []);
2149 #[stable(feature = "append", since = "1.4.0")]
2150 pub fn append(&mut self, other: &mut Self) {
2151 self.reserve(other.len());
2153 let (left, right) = other.as_slices();
2154 self.copy_slice(self.head, left);
2155 self.copy_slice(self.wrap_add(self.head, left.len()), right);
2157 // SAFETY: Update pointers after copying to avoid leaving doppelganger
2158 // in case of panics.
2159 self.head = self.wrap_add(self.head, other.len());
2160 // Silently drop values in `other`.
2161 other.tail = other.head;
2164 /// Retains only the elements specified by the predicate.
2166 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2167 /// This method operates in place, visiting each element exactly once in the
2168 /// original order, and preserves the order of the retained elements.
2173 /// use std::collections::VecDeque;
2175 /// let mut buf = VecDeque::new();
2176 /// buf.extend(1..5);
2177 /// buf.retain(|&x| x % 2 == 0);
2178 /// assert_eq!(buf, [2, 4]);
2181 /// Because the elements are visited exactly once in the original order,
2182 /// external state may be used to decide which elements to keep.
2185 /// use std::collections::VecDeque;
2187 /// let mut buf = VecDeque::new();
2188 /// buf.extend(1..6);
2190 /// let keep = [false, true, true, false, true];
2191 /// let mut iter = keep.iter();
2192 /// buf.retain(|_| *iter.next().unwrap());
2193 /// assert_eq!(buf, [2, 3, 5]);
2195 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2196 pub fn retain<F>(&mut self, mut f: F)
2198 F: FnMut(&T) -> bool,
2200 self.retain_mut(|elem| f(elem));
2203 /// Retains only the elements specified by the predicate.
2205 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2206 /// This method operates in place, visiting each element exactly once in the
2207 /// original order, and preserves the order of the retained elements.
2212 /// use std::collections::VecDeque;
2214 /// let mut buf = VecDeque::new();
2215 /// buf.extend(1..5);
2216 /// buf.retain_mut(|x| if *x % 2 == 0 {
2222 /// assert_eq!(buf, [3, 5]);
2224 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2225 pub fn retain_mut<F>(&mut self, mut f: F)
2227 F: FnMut(&mut T) -> bool,
2229 let len = self.len();
2233 // Stage 1: All values are retained.
2235 if !f(&mut self[cur]) {
2242 // Stage 2: Swap retained value into current idx.
2244 if !f(&mut self[cur]) {
2249 self.swap(idx, cur);
2253 // Stage 3: Truncate all values after idx.
2259 // Double the buffer size. This method is inline(never), so we expect it to only
2260 // be called in cold paths.
2261 // This may panic or abort
2263 fn grow(&mut self) {
2264 // Extend or possibly remove this assertion when valid use-cases for growing the
2265 // buffer without it being full emerge
2266 debug_assert!(self.is_full());
2267 let old_cap = self.cap();
2268 self.buf.reserve_exact(old_cap, old_cap);
2269 assert!(self.cap() == old_cap * 2);
2271 self.handle_capacity_increase(old_cap);
2273 debug_assert!(!self.is_full());
2276 /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2277 /// either by removing excess elements from the back or by appending
2278 /// elements generated by calling `generator` to the back.
2283 /// use std::collections::VecDeque;
2285 /// let mut buf = VecDeque::new();
2286 /// buf.push_back(5);
2287 /// buf.push_back(10);
2288 /// buf.push_back(15);
2289 /// assert_eq!(buf, [5, 10, 15]);
2291 /// buf.resize_with(5, Default::default);
2292 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2294 /// buf.resize_with(2, || unreachable!());
2295 /// assert_eq!(buf, [5, 10]);
2297 /// let mut state = 100;
2298 /// buf.resize_with(5, || { state += 1; state });
2299 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2301 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2302 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2303 let len = self.len();
2306 self.extend(repeat_with(generator).take(new_len - len))
2308 self.truncate(new_len);
2312 /// Rearranges the internal storage of this deque so it is one contiguous
2313 /// slice, which is then returned.
2315 /// This method does not allocate and does not change the order of the
2316 /// inserted elements. As it returns a mutable slice, this can be used to
2319 /// Once the internal storage is contiguous, the [`as_slices`] and
2320 /// [`as_mut_slices`] methods will return the entire contents of the
2321 /// deque in a single slice.
2323 /// [`as_slices`]: VecDeque::as_slices
2324 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2328 /// Sorting the content of a deque.
2331 /// use std::collections::VecDeque;
2333 /// let mut buf = VecDeque::with_capacity(15);
2335 /// buf.push_back(2);
2336 /// buf.push_back(1);
2337 /// buf.push_front(3);
2339 /// // sorting the deque
2340 /// buf.make_contiguous().sort();
2341 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2343 /// // sorting it in reverse order
2344 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2345 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2348 /// Getting immutable access to the contiguous slice.
2351 /// use std::collections::VecDeque;
2353 /// let mut buf = VecDeque::new();
2355 /// buf.push_back(2);
2356 /// buf.push_back(1);
2357 /// buf.push_front(3);
2359 /// buf.make_contiguous();
2360 /// if let (slice, &[]) = buf.as_slices() {
2361 /// // we can now be sure that `slice` contains all elements of the deque,
2362 /// // while still having immutable access to `buf`.
2363 /// assert_eq!(buf.len(), slice.len());
2364 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2367 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2368 pub fn make_contiguous(&mut self) -> &mut [T] {
2369 if self.is_contiguous() {
2370 let tail = self.tail;
2371 let head = self.head;
2373 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2374 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2376 MaybeUninit::slice_assume_init_mut(
2377 RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2382 let buf = self.buf.ptr();
2383 let cap = self.cap();
2384 let len = self.len();
2386 let free = self.tail - self.head;
2387 let tail_len = cap - self.tail;
2389 if free >= tail_len {
2390 // there is enough free space to copy the tail in one go,
2391 // this means that we first shift the head backwards, and then
2392 // copy the tail to the correct position.
2394 // from: DEFGH....ABC
2397 ptr::copy(buf, buf.add(tail_len), self.head);
2399 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2405 } else if free > self.head {
2406 // FIXME: We currently do not consider ....ABCDEFGH
2407 // to be contiguous because `head` would be `0` in this
2408 // case. While we probably want to change this it
2409 // isn't trivial as a few places expect `is_contiguous`
2410 // to mean that we can just slice using `buf[tail..head]`.
2412 // there is enough free space to copy the head in one go,
2413 // this means that we first shift the tail forwards, and then
2414 // copy the head to the correct position.
2416 // from: FGH....ABCDE
2419 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2421 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2424 self.tail = self.head;
2425 self.head = self.wrap_add(self.tail, len);
2428 // free is smaller than both head and tail,
2429 // this means we have to slowly "swap" the tail and the head.
2431 // from: EFGHI...ABCD or HIJK.ABCDEFG
2432 // to: ABCDEFGHI... or ABCDEFGHIJK.
2433 let mut left_edge: usize = 0;
2434 let mut right_edge: usize = self.tail;
2436 // The general problem looks like this
2437 // GHIJKLM...ABCDEF - before any swaps
2438 // ABCDEFM...GHIJKL - after 1 pass of swaps
2439 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2440 // - then restart the algorithm with a new (smaller) store
2441 // Sometimes the temp store is reached when the right edge is at the end
2442 // of the buffer - this means we've hit the right order with fewer swaps!
2445 // ABCDEF.. - after four only swaps we've finished
2446 while left_edge < len && right_edge != cap {
2447 let mut right_offset = 0;
2448 for i in left_edge..right_edge {
2449 right_offset = (i - left_edge) % (cap - right_edge);
2450 let src: isize = (right_edge + right_offset) as isize;
2451 ptr::swap(buf.add(i), buf.offset(src));
2453 let n_ops = right_edge - left_edge;
2455 right_edge += right_offset + 1;
2463 let tail = self.tail;
2464 let head = self.head;
2466 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2467 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2469 MaybeUninit::slice_assume_init_mut(
2470 RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2475 /// Rotates the double-ended queue `mid` places to the left.
2478 /// - Rotates item `mid` into the first position.
2479 /// - Pops the first `mid` items and pushes them to the end.
2480 /// - Rotates `len() - mid` places to the right.
2484 /// If `mid` is greater than `len()`. Note that `mid == len()`
2485 /// does _not_ panic and is a no-op rotation.
2489 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2494 /// use std::collections::VecDeque;
2496 /// let mut buf: VecDeque<_> = (0..10).collect();
2498 /// buf.rotate_left(3);
2499 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2501 /// for i in 1..10 {
2502 /// assert_eq!(i * 3 % 10, buf[0]);
2503 /// buf.rotate_left(3);
2505 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2507 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2508 pub fn rotate_left(&mut self, mid: usize) {
2509 assert!(mid <= self.len());
2510 let k = self.len() - mid;
2512 unsafe { self.rotate_left_inner(mid) }
2514 unsafe { self.rotate_right_inner(k) }
2518 /// Rotates the double-ended queue `k` places to the right.
2521 /// - Rotates the first item into position `k`.
2522 /// - Pops the last `k` items and pushes them to the front.
2523 /// - Rotates `len() - k` places to the left.
2527 /// If `k` is greater than `len()`. Note that `k == len()`
2528 /// does _not_ panic and is a no-op rotation.
2532 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2537 /// use std::collections::VecDeque;
2539 /// let mut buf: VecDeque<_> = (0..10).collect();
2541 /// buf.rotate_right(3);
2542 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2544 /// for i in 1..10 {
2545 /// assert_eq!(0, buf[i * 3 % 10]);
2546 /// buf.rotate_right(3);
2548 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2550 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2551 pub fn rotate_right(&mut self, k: usize) {
2552 assert!(k <= self.len());
2553 let mid = self.len() - k;
2555 unsafe { self.rotate_right_inner(k) }
2557 unsafe { self.rotate_left_inner(mid) }
2561 // SAFETY: the following two methods require that the rotation amount
2562 // be less than half the length of the deque.
2564 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2565 // but than `min` is never more than half the capacity, regardless of x,
2566 // so it's sound to call here because we're calling with something
2567 // less than half the length, which is never above half the capacity.
2569 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2570 debug_assert!(mid * 2 <= self.len());
2572 self.wrap_copy(self.head, self.tail, mid);
2574 self.head = self.wrap_add(self.head, mid);
2575 self.tail = self.wrap_add(self.tail, mid);
2578 unsafe fn rotate_right_inner(&mut self, k: usize) {
2579 debug_assert!(k * 2 <= self.len());
2580 self.head = self.wrap_sub(self.head, k);
2581 self.tail = self.wrap_sub(self.tail, k);
2583 self.wrap_copy(self.tail, self.head, k);
2587 /// Binary searches this `VecDeque` for a given element.
2588 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2590 /// If the value is found then [`Result::Ok`] is returned, containing the
2591 /// index of the matching element. If there are multiple matches, then any
2592 /// one of the matches could be returned. If the value is not found then
2593 /// [`Result::Err`] is returned, containing the index where a matching
2594 /// element could be inserted while maintaining sorted order.
2596 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2598 /// [`contains`]: VecDeque::contains
2599 /// [`binary_search_by`]: VecDeque::binary_search_by
2600 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2601 /// [`partition_point`]: VecDeque::partition_point
2605 /// Looks up a series of four elements. The first is found, with a
2606 /// uniquely determined position; the second and third are not
2607 /// found; the fourth could match any position in `[1, 4]`.
2610 /// use std::collections::VecDeque;
2612 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2614 /// assert_eq!(deque.binary_search(&13), Ok(9));
2615 /// assert_eq!(deque.binary_search(&4), Err(7));
2616 /// assert_eq!(deque.binary_search(&100), Err(13));
2617 /// let r = deque.binary_search(&1);
2618 /// assert!(matches!(r, Ok(1..=4)));
2621 /// If you want to insert an item to a sorted deque, while maintaining
2622 /// sort order, consider using [`partition_point`]:
2625 /// use std::collections::VecDeque;
2627 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2629 /// let idx = deque.partition_point(|&x| x < num);
2630 /// // The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
2631 /// deque.insert(idx, num);
2632 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2634 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2636 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2640 self.binary_search_by(|e| e.cmp(x))
2643 /// Binary searches this `VecDeque` with a comparator function.
2644 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2646 /// The comparator function should implement an order consistent
2647 /// with the sort order of the deque, returning an order code that
2648 /// indicates whether its argument is `Less`, `Equal` or `Greater`
2649 /// than the desired target.
2651 /// If the value is found then [`Result::Ok`] is returned, containing the
2652 /// index of the matching element. If there are multiple matches, then any
2653 /// one of the matches could be returned. If the value is not found then
2654 /// [`Result::Err`] is returned, containing the index where a matching
2655 /// element could be inserted while maintaining sorted order.
2657 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2659 /// [`contains`]: VecDeque::contains
2660 /// [`binary_search`]: VecDeque::binary_search
2661 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2662 /// [`partition_point`]: VecDeque::partition_point
2666 /// Looks up a series of four elements. The first is found, with a
2667 /// uniquely determined position; the second and third are not
2668 /// found; the fourth could match any position in `[1, 4]`.
2671 /// use std::collections::VecDeque;
2673 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2675 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2676 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2677 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2678 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2679 /// assert!(matches!(r, Ok(1..=4)));
2681 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2682 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2684 F: FnMut(&'a T) -> Ordering,
2686 let (front, back) = self.as_slices();
2687 let cmp_back = back.first().map(|elem| f(elem));
2689 if let Some(Ordering::Equal) = cmp_back {
2691 } else if let Some(Ordering::Less) = cmp_back {
2692 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2694 front.binary_search_by(f)
2698 /// Binary searches this `VecDeque` with a key extraction function.
2699 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2701 /// Assumes that the deque is sorted by the key, for instance with
2702 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2704 /// If the value is found then [`Result::Ok`] is returned, containing the
2705 /// index of the matching element. If there are multiple matches, then any
2706 /// one of the matches could be returned. If the value is not found then
2707 /// [`Result::Err`] is returned, containing the index where a matching
2708 /// element could be inserted while maintaining sorted order.
2710 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2712 /// [`contains`]: VecDeque::contains
2713 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2714 /// [`binary_search`]: VecDeque::binary_search
2715 /// [`binary_search_by`]: VecDeque::binary_search_by
2716 /// [`partition_point`]: VecDeque::partition_point
2720 /// Looks up a series of four elements in a slice of pairs sorted by
2721 /// their second elements. The first is found, with a uniquely
2722 /// determined position; the second and third are not found; the
2723 /// fourth could match any position in `[1, 4]`.
2726 /// use std::collections::VecDeque;
2728 /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
2729 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2730 /// (1, 21), (2, 34), (4, 55)].into();
2732 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2733 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2734 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2735 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2736 /// assert!(matches!(r, Ok(1..=4)));
2738 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2740 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2742 F: FnMut(&'a T) -> B,
2745 self.binary_search_by(|k| f(k).cmp(b))
2748 /// Returns the index of the partition point according to the given predicate
2749 /// (the index of the first element of the second partition).
2751 /// The deque is assumed to be partitioned according to the given predicate.
2752 /// This means that all elements for which the predicate returns true are at the start of the deque
2753 /// and all elements for which the predicate returns false are at the end.
2754 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2755 /// (all odd numbers are at the start, all even at the end).
2757 /// If the deque is not partitioned, the returned result is unspecified and meaningless,
2758 /// as this method performs a kind of binary search.
2760 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2762 /// [`binary_search`]: VecDeque::binary_search
2763 /// [`binary_search_by`]: VecDeque::binary_search_by
2764 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2769 /// use std::collections::VecDeque;
2771 /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
2772 /// let i = deque.partition_point(|&x| x < 5);
2774 /// assert_eq!(i, 4);
2775 /// assert!(deque.iter().take(i).all(|&x| x < 5));
2776 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2779 /// If you want to insert an item to a sorted deque, while maintaining
2783 /// use std::collections::VecDeque;
2785 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2787 /// let idx = deque.partition_point(|&x| x < num);
2788 /// deque.insert(idx, num);
2789 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2791 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2792 pub fn partition_point<P>(&self, mut pred: P) -> usize
2794 P: FnMut(&T) -> bool,
2796 let (front, back) = self.as_slices();
2798 if let Some(true) = back.first().map(|v| pred(v)) {
2799 back.partition_point(pred) + front.len()
2801 front.partition_point(pred)
2806 impl<T: Clone, A: Allocator> VecDeque<T, A> {
2807 /// Modifies the deque in-place so that `len()` is equal to new_len,
2808 /// either by removing excess elements from the back or by appending clones of `value`
2814 /// use std::collections::VecDeque;
2816 /// let mut buf = VecDeque::new();
2817 /// buf.push_back(5);
2818 /// buf.push_back(10);
2819 /// buf.push_back(15);
2820 /// assert_eq!(buf, [5, 10, 15]);
2822 /// buf.resize(2, 0);
2823 /// assert_eq!(buf, [5, 10]);
2825 /// buf.resize(5, 20);
2826 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2828 #[stable(feature = "deque_extras", since = "1.16.0")]
2829 pub fn resize(&mut self, new_len: usize, value: T) {
2830 self.resize_with(new_len, || value.clone());
2834 /// Returns the index in the underlying buffer for a given logical element index.
2836 fn wrap_index(index: usize, size: usize) -> usize {
2837 // size is always a power of 2
2838 debug_assert!(size.is_power_of_two());
2842 /// Calculate the number of elements left to be read in the buffer
2844 fn count(tail: usize, head: usize, size: usize) -> usize {
2845 // size is always a power of 2
2846 (head.wrapping_sub(tail)) & (size - 1)
2849 #[stable(feature = "rust1", since = "1.0.0")]
2850 impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
2851 fn eq(&self, other: &Self) -> bool {
2852 if self.len() != other.len() {
2855 let (sa, sb) = self.as_slices();
2856 let (oa, ob) = other.as_slices();
2857 if sa.len() == oa.len() {
2858 sa == oa && sb == ob
2859 } else if sa.len() < oa.len() {
2860 // Always divisible in three sections, for example:
2861 // self: [a b c|d e f]
2862 // other: [0 1 2 3|4 5]
2863 // front = 3, mid = 1,
2864 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2865 let front = sa.len();
2866 let mid = oa.len() - front;
2868 let (oa_front, oa_mid) = oa.split_at(front);
2869 let (sb_mid, sb_back) = sb.split_at(mid);
2870 debug_assert_eq!(sa.len(), oa_front.len());
2871 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2872 debug_assert_eq!(sb_back.len(), ob.len());
2873 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2875 let front = oa.len();
2876 let mid = sa.len() - front;
2878 let (sa_front, sa_mid) = sa.split_at(front);
2879 let (ob_mid, ob_back) = ob.split_at(mid);
2880 debug_assert_eq!(sa_front.len(), oa.len());
2881 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2882 debug_assert_eq!(sb.len(), ob_back.len());
2883 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2888 #[stable(feature = "rust1", since = "1.0.0")]
2889 impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
2891 __impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2892 __impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2893 __impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2894 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2895 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2896 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2898 #[stable(feature = "rust1", since = "1.0.0")]
2899 impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
2900 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2901 self.iter().partial_cmp(other.iter())
2905 #[stable(feature = "rust1", since = "1.0.0")]
2906 impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
2908 fn cmp(&self, other: &Self) -> Ordering {
2909 self.iter().cmp(other.iter())
2913 #[stable(feature = "rust1", since = "1.0.0")]
2914 impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
2915 fn hash<H: Hasher>(&self, state: &mut H) {
2916 state.write_length_prefix(self.len());
2917 // It's not possible to use Hash::hash_slice on slices
2918 // returned by as_slices method as their length can vary
2919 // in otherwise identical deques.
2921 // Hasher only guarantees equivalence for the exact same
2922 // set of calls to its methods.
2923 self.iter().for_each(|elem| elem.hash(state));
2927 #[stable(feature = "rust1", since = "1.0.0")]
2928 impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
2932 fn index(&self, index: usize) -> &T {
2933 self.get(index).expect("Out of bounds access")
2937 #[stable(feature = "rust1", since = "1.0.0")]
2938 impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
2940 fn index_mut(&mut self, index: usize) -> &mut T {
2941 self.get_mut(index).expect("Out of bounds access")
2945 #[stable(feature = "rust1", since = "1.0.0")]
2946 impl<T> FromIterator<T> for VecDeque<T> {
2947 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
2948 let iterator = iter.into_iter();
2949 let (lower, _) = iterator.size_hint();
2950 let mut deq = VecDeque::with_capacity(lower);
2951 deq.extend(iterator);
2956 #[stable(feature = "rust1", since = "1.0.0")]
2957 impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
2959 type IntoIter = IntoIter<T, A>;
2961 /// Consumes the deque into a front-to-back iterator yielding elements by
2963 fn into_iter(self) -> IntoIter<T, A> {
2968 #[stable(feature = "rust1", since = "1.0.0")]
2969 impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
2971 type IntoIter = Iter<'a, T>;
2973 fn into_iter(self) -> Iter<'a, T> {
2978 #[stable(feature = "rust1", since = "1.0.0")]
2979 impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
2980 type Item = &'a mut T;
2981 type IntoIter = IterMut<'a, T>;
2983 fn into_iter(self) -> IterMut<'a, T> {
2988 #[stable(feature = "rust1", since = "1.0.0")]
2989 impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
2990 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2991 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter());
2995 fn extend_one(&mut self, elem: T) {
2996 self.push_back(elem);
3000 fn extend_reserve(&mut self, additional: usize) {
3001 self.reserve(additional);
3005 #[stable(feature = "extend_ref", since = "1.2.0")]
3006 impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
3007 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3008 self.spec_extend(iter.into_iter());
3012 fn extend_one(&mut self, &elem: &T) {
3013 self.push_back(elem);
3017 fn extend_reserve(&mut self, additional: usize) {
3018 self.reserve(additional);
3022 #[stable(feature = "rust1", since = "1.0.0")]
3023 impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
3024 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3025 f.debug_list().entries(self).finish()
3029 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3030 impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
3031 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3033 /// [`Vec<T>`]: crate::vec::Vec
3034 /// [`VecDeque<T>`]: crate::collections::VecDeque
3036 /// This avoids reallocating where possible, but the conditions for that are
3037 /// strict, and subject to change, and so shouldn't be relied upon unless the
3038 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
3039 fn from(mut other: Vec<T, A>) -> Self {
3040 let len = other.len();
3041 if mem::size_of::<T>() == 0 {
3042 // There's no actual allocation for ZSTs to worry about capacity,
3043 // but `VecDeque` can't handle as much length as `Vec`.
3044 assert!(len < MAXIMUM_ZST_CAPACITY, "capacity overflow");
3046 // We need to resize if the capacity is not a power of two, too small or
3047 // doesn't have at least one free space. We do this while it's still in
3048 // the `Vec` so the items will drop on panic.
3049 let min_cap = cmp::max(MINIMUM_CAPACITY, len) + 1;
3050 let cap = cmp::max(min_cap, other.capacity()).next_power_of_two();
3051 if other.capacity() != cap {
3052 other.reserve_exact(cap - len);
3057 let (other_buf, len, capacity, alloc) = other.into_raw_parts_with_alloc();
3058 let buf = RawVec::from_raw_parts_in(other_buf, capacity, alloc);
3059 VecDeque { tail: 0, head: len, buf }
3064 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3065 impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
3066 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
3068 /// [`Vec<T>`]: crate::vec::Vec
3069 /// [`VecDeque<T>`]: crate::collections::VecDeque
3071 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
3072 /// the circular buffer doesn't happen to be at the beginning of the allocation.
3077 /// use std::collections::VecDeque;
3079 /// // This one is *O*(1).
3080 /// let deque: VecDeque<_> = (1..5).collect();
3081 /// let ptr = deque.as_slices().0.as_ptr();
3082 /// let vec = Vec::from(deque);
3083 /// assert_eq!(vec, [1, 2, 3, 4]);
3084 /// assert_eq!(vec.as_ptr(), ptr);
3086 /// // This one needs data rearranging.
3087 /// let mut deque: VecDeque<_> = (1..5).collect();
3088 /// deque.push_front(9);
3089 /// deque.push_front(8);
3090 /// let ptr = deque.as_slices().1.as_ptr();
3091 /// let vec = Vec::from(deque);
3092 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
3093 /// assert_eq!(vec.as_ptr(), ptr);
3095 fn from(mut other: VecDeque<T, A>) -> Self {
3096 other.make_contiguous();
3099 let other = ManuallyDrop::new(other);
3100 let buf = other.buf.ptr();
3101 let len = other.len();
3102 let cap = other.cap();
3103 let alloc = ptr::read(other.allocator());
3105 if other.tail != 0 {
3106 ptr::copy(buf.add(other.tail), buf, len);
3108 Vec::from_raw_parts_in(buf, len, cap, alloc)
3113 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
3114 impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
3115 /// Converts a `[T; N]` into a `VecDeque<T>`.
3118 /// use std::collections::VecDeque;
3120 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
3121 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
3122 /// assert_eq!(deq1, deq2);
3124 fn from(arr: [T; N]) -> Self {
3125 let mut deq = VecDeque::with_capacity(N);
3126 let arr = ManuallyDrop::new(arr);
3127 if mem::size_of::<T>() != 0 {
3128 // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
3130 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);