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 /// Frobs the head and tail sections around to handle the fact that we
457 /// just reallocated. Unsafe because it trusts old_capacity.
459 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
460 let new_capacity = self.cap();
462 // Move the shortest contiguous section of the ring buffer
464 // [o o o o o o o . ]
466 // A [o o o o o o o . . . . . . . . . ]
468 // [o o . o o o o o ]
470 // B [. . . o o o o o o o . . . . . . ]
472 // [o o o o o . o o ]
474 // C [o o o o o . . . . . . . . . o o ]
476 if self.tail <= self.head {
479 } else if self.head < old_capacity - self.tail {
482 self.copy_nonoverlapping(old_capacity, 0, self.head);
484 self.head += old_capacity;
485 debug_assert!(self.head > self.tail);
488 let new_tail = new_capacity - (old_capacity - self.tail);
490 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
492 self.tail = new_tail;
493 debug_assert!(self.head < self.tail);
495 debug_assert!(self.head < self.cap());
496 debug_assert!(self.tail < self.cap());
497 debug_assert!(self.cap().count_ones() == 1);
501 impl<T> VecDeque<T> {
502 /// Creates an empty deque.
507 /// use std::collections::VecDeque;
509 /// let deque: VecDeque<u32> = VecDeque::new();
512 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn new() -> VecDeque<T> {
515 VecDeque::new_in(Global)
518 /// Creates an empty deque with space for at least `capacity` elements.
523 /// use std::collections::VecDeque;
525 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
528 #[stable(feature = "rust1", since = "1.0.0")]
530 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
531 Self::with_capacity_in(capacity, Global)
535 impl<T, A: Allocator> VecDeque<T, A> {
536 /// Creates an empty deque.
541 /// use std::collections::VecDeque;
543 /// let deque: VecDeque<u32> = VecDeque::new();
546 #[unstable(feature = "allocator_api", issue = "32838")]
547 pub fn new_in(alloc: A) -> VecDeque<T, A> {
548 VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc)
551 /// Creates an empty deque with space for at least `capacity` elements.
556 /// use std::collections::VecDeque;
558 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
560 #[unstable(feature = "allocator_api", issue = "32838")]
561 pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
562 assert!(capacity < 1_usize << usize::BITS - 1, "capacity overflow");
563 // +1 since the ringbuffer always leaves one space empty
564 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
566 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) }
569 /// Provides a reference to the element at the given index.
571 /// Element at index 0 is the front of the queue.
576 /// use std::collections::VecDeque;
578 /// let mut buf = VecDeque::new();
579 /// buf.push_back(3);
580 /// buf.push_back(4);
581 /// buf.push_back(5);
582 /// assert_eq!(buf.get(1), Some(&4));
584 #[stable(feature = "rust1", since = "1.0.0")]
585 pub fn get(&self, index: usize) -> Option<&T> {
586 if index < self.len() {
587 let idx = self.wrap_add(self.tail, index);
588 unsafe { Some(&*self.ptr().add(idx)) }
594 /// Provides a mutable reference to the element at the given index.
596 /// Element at index 0 is the front of the queue.
601 /// use std::collections::VecDeque;
603 /// let mut buf = VecDeque::new();
604 /// buf.push_back(3);
605 /// buf.push_back(4);
606 /// buf.push_back(5);
607 /// if let Some(elem) = buf.get_mut(1) {
611 /// assert_eq!(buf[1], 7);
613 #[stable(feature = "rust1", since = "1.0.0")]
614 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
615 if index < self.len() {
616 let idx = self.wrap_add(self.tail, index);
617 unsafe { Some(&mut *self.ptr().add(idx)) }
623 /// Swaps elements at indices `i` and `j`.
625 /// `i` and `j` may be equal.
627 /// Element at index 0 is the front of the queue.
631 /// Panics if either index is out of bounds.
636 /// use std::collections::VecDeque;
638 /// let mut buf = VecDeque::new();
639 /// buf.push_back(3);
640 /// buf.push_back(4);
641 /// buf.push_back(5);
642 /// assert_eq!(buf, [3, 4, 5]);
644 /// assert_eq!(buf, [5, 4, 3]);
646 #[stable(feature = "rust1", since = "1.0.0")]
647 pub fn swap(&mut self, i: usize, j: usize) {
648 assert!(i < self.len());
649 assert!(j < self.len());
650 let ri = self.wrap_add(self.tail, i);
651 let rj = self.wrap_add(self.tail, j);
652 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
655 /// Returns the number of elements the deque can hold without
661 /// use std::collections::VecDeque;
663 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
664 /// assert!(buf.capacity() >= 10);
667 #[stable(feature = "rust1", since = "1.0.0")]
668 pub fn capacity(&self) -> usize {
672 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
673 /// given deque. Does nothing if the capacity is already sufficient.
675 /// Note that the allocator may give the collection more space than it requests. Therefore
676 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
677 /// insertions are expected.
681 /// Panics if the new capacity overflows `usize`.
686 /// use std::collections::VecDeque;
688 /// let mut buf: VecDeque<i32> = [1].into();
689 /// buf.reserve_exact(10);
690 /// assert!(buf.capacity() >= 11);
693 /// [`reserve`]: VecDeque::reserve
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub fn reserve_exact(&mut self, additional: usize) {
696 self.reserve(additional);
699 /// Reserves capacity for at least `additional` more elements to be inserted in the given
700 /// deque. The collection may reserve more space to avoid frequent reallocations.
704 /// Panics if the new capacity overflows `usize`.
709 /// use std::collections::VecDeque;
711 /// let mut buf: VecDeque<i32> = [1].into();
713 /// assert!(buf.capacity() >= 11);
715 #[stable(feature = "rust1", since = "1.0.0")]
716 pub fn reserve(&mut self, additional: usize) {
717 let old_cap = self.cap();
718 let used_cap = self.len() + 1;
719 let new_cap = used_cap
720 .checked_add(additional)
721 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
722 .expect("capacity overflow");
724 if new_cap > old_cap {
725 self.buf.reserve_exact(used_cap, new_cap - used_cap);
727 self.handle_capacity_increase(old_cap);
732 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
733 /// be inserted in the given deque. After calling `try_reserve_exact`,
734 /// capacity will be greater than or equal to `self.len() + additional`.
735 /// Does nothing if the capacity is already sufficient.
737 /// Note that the allocator may give the collection more space than it
738 /// requests. Therefore, capacity can not be relied upon to be precisely
739 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
741 /// [`try_reserve`]: VecDeque::try_reserve
745 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
751 /// use std::collections::TryReserveError;
752 /// use std::collections::VecDeque;
754 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
755 /// let mut output = VecDeque::new();
757 /// // Pre-reserve the memory, exiting if we can't
758 /// output.try_reserve_exact(data.len())?;
760 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
761 /// output.extend(data.iter().map(|&val| {
762 /// val * 2 + 5 // very complicated
767 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
769 #[stable(feature = "try_reserve", since = "1.57.0")]
770 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
771 self.try_reserve(additional)
774 /// Tries to reserve capacity for at least `additional` more elements to be inserted
775 /// in the given deque. The collection may reserve more space to avoid
776 /// frequent reallocations. After calling `try_reserve`, capacity will be
777 /// greater than or equal to `self.len() + additional`. Does nothing if
778 /// capacity is already sufficient.
782 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
788 /// use std::collections::TryReserveError;
789 /// use std::collections::VecDeque;
791 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
792 /// let mut output = VecDeque::new();
794 /// // Pre-reserve the memory, exiting if we can't
795 /// output.try_reserve(data.len())?;
797 /// // Now we know this can't OOM in the middle of our complex work
798 /// output.extend(data.iter().map(|&val| {
799 /// val * 2 + 5 // very complicated
804 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
806 #[stable(feature = "try_reserve", since = "1.57.0")]
807 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
808 let old_cap = self.cap();
809 let used_cap = self.len() + 1;
810 let new_cap = used_cap
811 .checked_add(additional)
812 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
813 .ok_or(TryReserveErrorKind::CapacityOverflow)?;
815 if new_cap > old_cap {
816 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
818 self.handle_capacity_increase(old_cap);
824 /// Shrinks the capacity of the deque as much as possible.
826 /// It will drop down as close as possible to the length but the allocator may still inform the
827 /// deque that there is space for a few more elements.
832 /// use std::collections::VecDeque;
834 /// let mut buf = VecDeque::with_capacity(15);
835 /// buf.extend(0..4);
836 /// assert_eq!(buf.capacity(), 15);
837 /// buf.shrink_to_fit();
838 /// assert!(buf.capacity() >= 4);
840 #[stable(feature = "deque_extras_15", since = "1.5.0")]
841 pub fn shrink_to_fit(&mut self) {
845 /// Shrinks the capacity of the deque with a lower bound.
847 /// The capacity will remain at least as large as both the length
848 /// and the supplied value.
850 /// If the current capacity is less than the lower limit, this is a no-op.
855 /// use std::collections::VecDeque;
857 /// let mut buf = VecDeque::with_capacity(15);
858 /// buf.extend(0..4);
859 /// assert_eq!(buf.capacity(), 15);
860 /// buf.shrink_to(6);
861 /// assert!(buf.capacity() >= 6);
862 /// buf.shrink_to(0);
863 /// assert!(buf.capacity() >= 4);
865 #[stable(feature = "shrink_to", since = "1.56.0")]
866 pub fn shrink_to(&mut self, min_capacity: usize) {
867 let min_capacity = cmp::min(min_capacity, self.capacity());
868 // We don't have to worry about an overflow as neither `self.len()` nor `self.capacity()`
869 // can ever be `usize::MAX`. +1 as the ringbuffer always leaves one space empty.
870 let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
871 .next_power_of_two();
873 if target_cap < self.cap() {
874 // There are three cases of interest:
875 // All elements are out of desired bounds
876 // Elements are contiguous, and head is out of desired bounds
877 // Elements are discontiguous, and tail is out of desired bounds
879 // At all other times, element positions are unaffected.
881 // Indicates that elements at the head should be moved.
882 let head_outside = self.head == 0 || self.head >= target_cap;
883 // Move elements from out of desired bounds (positions after target_cap)
884 if self.tail >= target_cap && head_outside {
886 // [. . . . . . . . o o o o o o o . ]
888 // [o o o o o o o . ]
890 self.copy_nonoverlapping(0, self.tail, self.len());
892 self.head = self.len();
894 } else if self.tail != 0 && self.tail < target_cap && head_outside {
896 // [. . . o o o o o o o . . . . . . ]
898 // [o o . o o o o o ]
899 let len = self.wrap_sub(self.head, target_cap);
901 self.copy_nonoverlapping(0, target_cap, len);
904 debug_assert!(self.head < self.tail);
905 } else if self.tail >= target_cap {
907 // [o o o o o . . . . . . . . . o o ]
909 // [o o o o o . o o ]
910 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
911 let len = self.cap() - self.tail;
912 let new_tail = target_cap - len;
914 self.copy_nonoverlapping(new_tail, self.tail, len);
916 self.tail = new_tail;
917 debug_assert!(self.head < self.tail);
920 self.buf.shrink_to_fit(target_cap);
922 debug_assert!(self.head < self.cap());
923 debug_assert!(self.tail < self.cap());
924 debug_assert!(self.cap().count_ones() == 1);
928 /// Shortens the deque, keeping the first `len` elements and dropping
931 /// If `len` is greater than the deque's current length, this has no
937 /// use std::collections::VecDeque;
939 /// let mut buf = VecDeque::new();
940 /// buf.push_back(5);
941 /// buf.push_back(10);
942 /// buf.push_back(15);
943 /// assert_eq!(buf, [5, 10, 15]);
945 /// assert_eq!(buf, [5]);
947 #[stable(feature = "deque_extras", since = "1.16.0")]
948 pub fn truncate(&mut self, len: usize) {
949 /// Runs the destructor for all items in the slice when it gets dropped (normally or
950 /// during unwinding).
951 struct Dropper<'a, T>(&'a mut [T]);
953 impl<'a, T> Drop for Dropper<'a, T> {
956 ptr::drop_in_place(self.0);
963 // * Any slice passed to `drop_in_place` is valid; the second case has
964 // `len <= front.len()` and returning on `len > self.len()` ensures
965 // `begin <= back.len()` in the first case
966 // * The head of the VecDeque is moved before calling `drop_in_place`,
967 // so no value is dropped twice if `drop_in_place` panics
969 if len > self.len() {
972 let num_dropped = self.len() - len;
973 let (front, back) = self.as_mut_slices();
974 if len > front.len() {
975 let begin = len - front.len();
976 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
977 self.head = self.wrap_sub(self.head, num_dropped);
978 ptr::drop_in_place(drop_back);
980 let drop_back = back as *mut _;
981 let drop_front = front.get_unchecked_mut(len..) as *mut _;
982 self.head = self.wrap_sub(self.head, num_dropped);
984 // Make sure the second half is dropped even when a destructor
985 // in the first one panics.
986 let _back_dropper = Dropper(&mut *drop_back);
987 ptr::drop_in_place(drop_front);
992 /// Returns a reference to the underlying allocator.
993 #[unstable(feature = "allocator_api", issue = "32838")]
995 pub fn allocator(&self) -> &A {
999 /// Returns a front-to-back iterator.
1004 /// use std::collections::VecDeque;
1006 /// let mut buf = VecDeque::new();
1007 /// buf.push_back(5);
1008 /// buf.push_back(3);
1009 /// buf.push_back(4);
1010 /// let b: &[_] = &[&5, &3, &4];
1011 /// let c: Vec<&i32> = buf.iter().collect();
1012 /// assert_eq!(&c[..], b);
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 pub fn iter(&self) -> Iter<'_, T> {
1016 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } }
1019 /// Returns a front-to-back iterator that returns mutable references.
1024 /// use std::collections::VecDeque;
1026 /// let mut buf = VecDeque::new();
1027 /// buf.push_back(5);
1028 /// buf.push_back(3);
1029 /// buf.push_back(4);
1030 /// for num in buf.iter_mut() {
1031 /// *num = *num - 2;
1033 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1034 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1036 #[stable(feature = "rust1", since = "1.0.0")]
1037 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1038 // SAFETY: The internal `IterMut` safety invariant is established because the
1039 // `ring` we create is a dereferenceable slice for lifetime '_.
1040 let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1042 unsafe { IterMut::new(ring, self.tail, self.head, PhantomData) }
1045 /// Returns a pair of slices which contain, in order, the contents of the
1048 /// If [`make_contiguous`] was previously called, all elements of the
1049 /// deque will be in the first slice and the second slice will be empty.
1051 /// [`make_contiguous`]: VecDeque::make_contiguous
1056 /// use std::collections::VecDeque;
1058 /// let mut deque = VecDeque::new();
1060 /// deque.push_back(0);
1061 /// deque.push_back(1);
1062 /// deque.push_back(2);
1064 /// assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..]));
1066 /// deque.push_front(10);
1067 /// deque.push_front(9);
1069 /// assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1072 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1073 pub fn as_slices(&self) -> (&[T], &[T]) {
1075 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
1076 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
1078 let buf = self.buffer_as_slice();
1079 let (front, back) = RingSlices::ring_slices(buf, self.head, self.tail);
1080 (MaybeUninit::slice_assume_init_ref(front), MaybeUninit::slice_assume_init_ref(back))
1084 /// Returns a pair of slices which contain, in order, the contents of the
1087 /// If [`make_contiguous`] was previously called, all elements of the
1088 /// deque will be in the first slice and the second slice will be empty.
1090 /// [`make_contiguous`]: VecDeque::make_contiguous
1095 /// use std::collections::VecDeque;
1097 /// let mut deque = VecDeque::new();
1099 /// deque.push_back(0);
1100 /// deque.push_back(1);
1102 /// deque.push_front(10);
1103 /// deque.push_front(9);
1105 /// deque.as_mut_slices().0[0] = 42;
1106 /// deque.as_mut_slices().1[0] = 24;
1107 /// assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
1110 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1111 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1113 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
1114 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
1116 let head = self.head;
1117 let tail = self.tail;
1118 let buf = self.buffer_as_mut_slice();
1119 let (front, back) = RingSlices::ring_slices(buf, head, tail);
1120 (MaybeUninit::slice_assume_init_mut(front), MaybeUninit::slice_assume_init_mut(back))
1124 /// Returns the number of elements in the deque.
1129 /// use std::collections::VecDeque;
1131 /// let mut deque = VecDeque::new();
1132 /// assert_eq!(deque.len(), 0);
1133 /// deque.push_back(1);
1134 /// assert_eq!(deque.len(), 1);
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn len(&self) -> usize {
1138 count(self.tail, self.head, self.cap())
1141 /// Returns `true` if the deque is empty.
1146 /// use std::collections::VecDeque;
1148 /// let mut deque = VecDeque::new();
1149 /// assert!(deque.is_empty());
1150 /// deque.push_front(1);
1151 /// assert!(!deque.is_empty());
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 pub fn is_empty(&self) -> bool {
1155 self.tail == self.head
1158 fn range_tail_head<R>(&self, range: R) -> (usize, usize)
1160 R: RangeBounds<usize>,
1162 let Range { start, end } = slice::range(range, ..self.len());
1163 let tail = self.wrap_add(self.tail, start);
1164 let head = self.wrap_add(self.tail, end);
1168 /// Creates an iterator that covers the specified range in the deque.
1172 /// Panics if the starting point is greater than the end point or if
1173 /// the end point is greater than the length of the deque.
1178 /// use std::collections::VecDeque;
1180 /// let deque: VecDeque<_> = [1, 2, 3].into();
1181 /// let range = deque.range(2..).copied().collect::<VecDeque<_>>();
1182 /// assert_eq!(range, [3]);
1184 /// // A full range covers all contents
1185 /// let all = deque.range(..);
1186 /// assert_eq!(all.len(), 3);
1189 #[stable(feature = "deque_range", since = "1.51.0")]
1190 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1192 R: RangeBounds<usize>,
1194 let (tail, head) = self.range_tail_head(range);
1198 // The shared reference we have in &self is maintained in the '_ of Iter.
1199 ring: unsafe { self.buffer_as_slice() },
1203 /// Creates an iterator that covers the specified mutable range in the deque.
1207 /// Panics if the starting point is greater than the end point or if
1208 /// the end point is greater than the length of the deque.
1213 /// use std::collections::VecDeque;
1215 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1216 /// for v in deque.range_mut(2..) {
1219 /// assert_eq!(deque, [1, 2, 6]);
1221 /// // A full range covers all contents
1222 /// for v in deque.range_mut(..) {
1225 /// assert_eq!(deque, [2, 4, 12]);
1228 #[stable(feature = "deque_range", since = "1.51.0")]
1229 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1231 R: RangeBounds<usize>,
1233 let (tail, head) = self.range_tail_head(range);
1235 // SAFETY: The internal `IterMut` safety invariant is established because the
1236 // `ring` we create is a dereferenceable slice for lifetime '_.
1237 let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1239 unsafe { IterMut::new(ring, tail, head, PhantomData) }
1242 /// Removes the specified range from the deque in bulk, returning all
1243 /// removed elements as an iterator. If the iterator is dropped before
1244 /// being fully consumed, it drops the remaining removed elements.
1246 /// The returned iterator keeps a mutable borrow on the queue to optimize
1247 /// its implementation.
1252 /// Panics if the starting point is greater than the end point or if
1253 /// the end point is greater than the length of the deque.
1257 /// If the returned iterator goes out of scope without being dropped (due to
1258 /// [`mem::forget`], for example), the deque may have lost and leaked
1259 /// elements arbitrarily, including elements outside the range.
1264 /// use std::collections::VecDeque;
1266 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1267 /// let drained = deque.drain(2..).collect::<VecDeque<_>>();
1268 /// assert_eq!(drained, [3]);
1269 /// assert_eq!(deque, [1, 2]);
1271 /// // A full range clears all contents, like `clear()` does
1272 /// deque.drain(..);
1273 /// assert!(deque.is_empty());
1276 #[stable(feature = "drain", since = "1.6.0")]
1277 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1279 R: RangeBounds<usize>,
1283 // When the Drain is first created, the source deque is shortened to
1284 // make sure no uninitialized or moved-from elements are accessible at
1285 // all if the Drain's destructor never gets to run.
1287 // Drain will ptr::read out the values to remove.
1288 // When finished, the remaining data will be copied back to cover the hole,
1289 // and the head/tail values will be restored correctly.
1291 let (drain_tail, drain_head) = self.range_tail_head(range);
1293 // The deque's elements are parted into three segments:
1294 // * self.tail -> drain_tail
1295 // * drain_tail -> drain_head
1296 // * drain_head -> self.head
1298 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1300 // We store drain_tail as self.head, and drain_head and self.head as
1301 // after_tail and after_head respectively on the Drain. This also
1302 // truncates the effective array such that if the Drain is leaked, we
1303 // have forgotten about the potentially moved values after the start of
1307 // [. . . o o x x o o . . .]
1309 let head = self.head;
1311 // "forget" about the values after the start of the drain until after
1312 // the drain is complete and the Drain destructor is run.
1313 self.head = drain_tail;
1315 let deque = NonNull::from(&mut *self);
1319 // Crucially, we only create shared references from `self` here and read from
1320 // it. We do not write to `self` nor reborrow to a mutable reference.
1321 // Hence the raw pointer we created above, for `deque`, remains valid.
1322 ring: unsafe { self.buffer_as_slice() },
1325 unsafe { Drain::new(drain_head, head, iter, deque) }
1328 /// Clears the deque, removing all values.
1333 /// use std::collections::VecDeque;
1335 /// let mut deque = VecDeque::new();
1336 /// deque.push_back(1);
1338 /// assert!(deque.is_empty());
1340 #[stable(feature = "rust1", since = "1.0.0")]
1342 pub fn clear(&mut self) {
1346 /// Returns `true` if the deque contains an element equal to the
1349 /// This operation is *O*(*n*).
1351 /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
1353 /// [`binary_search`]: VecDeque::binary_search
1358 /// use std::collections::VecDeque;
1360 /// let mut deque: VecDeque<u32> = VecDeque::new();
1362 /// deque.push_back(0);
1363 /// deque.push_back(1);
1365 /// assert_eq!(deque.contains(&1), true);
1366 /// assert_eq!(deque.contains(&10), false);
1368 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1369 pub fn contains(&self, x: &T) -> bool
1373 let (a, b) = self.as_slices();
1374 a.contains(x) || b.contains(x)
1377 /// Provides a reference to the front element, or `None` if the deque is
1383 /// use std::collections::VecDeque;
1385 /// let mut d = VecDeque::new();
1386 /// assert_eq!(d.front(), None);
1390 /// assert_eq!(d.front(), Some(&1));
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 pub fn front(&self) -> Option<&T> {
1397 /// Provides a mutable reference to the front element, or `None` if the
1403 /// use std::collections::VecDeque;
1405 /// let mut d = VecDeque::new();
1406 /// assert_eq!(d.front_mut(), None);
1410 /// match d.front_mut() {
1411 /// Some(x) => *x = 9,
1414 /// assert_eq!(d.front(), Some(&9));
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 pub fn front_mut(&mut self) -> Option<&mut T> {
1421 /// Provides a reference to the back element, or `None` if the deque is
1427 /// use std::collections::VecDeque;
1429 /// let mut d = VecDeque::new();
1430 /// assert_eq!(d.back(), None);
1434 /// assert_eq!(d.back(), Some(&2));
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 pub fn back(&self) -> Option<&T> {
1438 self.get(self.len().wrapping_sub(1))
1441 /// Provides a mutable reference to the back element, or `None` if the
1447 /// use std::collections::VecDeque;
1449 /// let mut d = VecDeque::new();
1450 /// assert_eq!(d.back(), None);
1454 /// match d.back_mut() {
1455 /// Some(x) => *x = 9,
1458 /// assert_eq!(d.back(), Some(&9));
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 pub fn back_mut(&mut self) -> Option<&mut T> {
1462 self.get_mut(self.len().wrapping_sub(1))
1465 /// Removes the first element and returns it, or `None` if the deque is
1471 /// use std::collections::VecDeque;
1473 /// let mut d = VecDeque::new();
1477 /// assert_eq!(d.pop_front(), Some(1));
1478 /// assert_eq!(d.pop_front(), Some(2));
1479 /// assert_eq!(d.pop_front(), None);
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 pub fn pop_front(&mut self) -> Option<T> {
1483 if self.is_empty() {
1486 let tail = self.tail;
1487 self.tail = self.wrap_add(self.tail, 1);
1488 unsafe { Some(self.buffer_read(tail)) }
1492 /// Removes the last element from the deque and returns it, or `None` if
1498 /// use std::collections::VecDeque;
1500 /// let mut buf = VecDeque::new();
1501 /// assert_eq!(buf.pop_back(), None);
1502 /// buf.push_back(1);
1503 /// buf.push_back(3);
1504 /// assert_eq!(buf.pop_back(), Some(3));
1506 #[stable(feature = "rust1", since = "1.0.0")]
1507 pub fn pop_back(&mut self) -> Option<T> {
1508 if self.is_empty() {
1511 self.head = self.wrap_sub(self.head, 1);
1512 let head = self.head;
1513 unsafe { Some(self.buffer_read(head)) }
1517 /// Prepends an element to the deque.
1522 /// use std::collections::VecDeque;
1524 /// let mut d = VecDeque::new();
1525 /// d.push_front(1);
1526 /// d.push_front(2);
1527 /// assert_eq!(d.front(), Some(&2));
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 pub fn push_front(&mut self, value: T) {
1535 self.tail = self.wrap_sub(self.tail, 1);
1536 let tail = self.tail;
1538 self.buffer_write(tail, value);
1542 /// Appends an element to the back of the deque.
1547 /// use std::collections::VecDeque;
1549 /// let mut buf = VecDeque::new();
1550 /// buf.push_back(1);
1551 /// buf.push_back(3);
1552 /// assert_eq!(3, *buf.back().unwrap());
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 pub fn push_back(&mut self, value: T) {
1560 let head = self.head;
1561 self.head = self.wrap_add(self.head, 1);
1562 unsafe { self.buffer_write(head, value) }
1566 fn is_contiguous(&self) -> bool {
1567 // FIXME: Should we consider `head == 0` to mean
1568 // that `self` is contiguous?
1569 self.tail <= self.head
1572 /// Removes an element from anywhere in the deque and returns it,
1573 /// replacing it with the first element.
1575 /// This does not preserve ordering, but is *O*(1).
1577 /// Returns `None` if `index` is out of bounds.
1579 /// Element at index 0 is the front of the queue.
1584 /// use std::collections::VecDeque;
1586 /// let mut buf = VecDeque::new();
1587 /// assert_eq!(buf.swap_remove_front(0), None);
1588 /// buf.push_back(1);
1589 /// buf.push_back(2);
1590 /// buf.push_back(3);
1591 /// assert_eq!(buf, [1, 2, 3]);
1593 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1594 /// assert_eq!(buf, [2, 1]);
1596 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1597 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1598 let length = self.len();
1599 if length > 0 && index < length && index != 0 {
1600 self.swap(index, 0);
1601 } else if index >= length {
1607 /// Removes an element from anywhere in the deque and returns it,
1608 /// replacing it with the last element.
1610 /// This does not preserve ordering, but is *O*(1).
1612 /// Returns `None` if `index` is out of bounds.
1614 /// Element at index 0 is the front of the queue.
1619 /// use std::collections::VecDeque;
1621 /// let mut buf = VecDeque::new();
1622 /// assert_eq!(buf.swap_remove_back(0), None);
1623 /// buf.push_back(1);
1624 /// buf.push_back(2);
1625 /// buf.push_back(3);
1626 /// assert_eq!(buf, [1, 2, 3]);
1628 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1629 /// assert_eq!(buf, [3, 2]);
1631 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1632 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1633 let length = self.len();
1634 if length > 0 && index < length - 1 {
1635 self.swap(index, length - 1);
1636 } else if index >= length {
1642 /// Inserts an element at `index` within the deque, shifting all elements
1643 /// with indices greater than or equal to `index` towards the back.
1645 /// Element at index 0 is the front of the queue.
1649 /// Panics if `index` is greater than deque's length
1654 /// use std::collections::VecDeque;
1656 /// let mut vec_deque = VecDeque::new();
1657 /// vec_deque.push_back('a');
1658 /// vec_deque.push_back('b');
1659 /// vec_deque.push_back('c');
1660 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1662 /// vec_deque.insert(1, 'd');
1663 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1665 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1666 pub fn insert(&mut self, index: usize, value: T) {
1667 assert!(index <= self.len(), "index out of bounds");
1672 // Move the least number of elements in the ring buffer and insert
1675 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1677 // There are three main cases:
1678 // Elements are contiguous
1679 // - special case when tail is 0
1680 // Elements are discontiguous and the insert is in the tail section
1681 // Elements are discontiguous and the insert is in the head section
1683 // For each of those there are two more cases:
1684 // Insert is closer to tail
1685 // Insert is closer to head
1687 // Key: H - self.head
1689 // o - Valid element
1690 // I - Insertion element
1691 // A - The element that should be after the insertion point
1692 // M - Indicates element was moved
1694 let idx = self.wrap_add(self.tail, index);
1696 let distance_to_tail = index;
1697 let distance_to_head = self.len() - index;
1699 let contiguous = self.is_contiguous();
1701 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1702 (true, true, _) if index == 0 => {
1707 // [A o o o o o o . . . . . . . . .]
1710 // [A o o o o o o o . . . . . I]
1713 self.tail = self.wrap_sub(self.tail, 1);
1715 (true, true, _) => {
1717 // contiguous, insert closer to tail:
1720 // [. . . o o A o o o o . . . . . .]
1723 // [. . o o I A o o o o . . . . . .]
1726 // contiguous, insert closer to tail and tail is 0:
1730 // [o o A o o o o . . . . . . . . .]
1733 // [o I A o o o o o . . . . . . . o]
1736 let new_tail = self.wrap_sub(self.tail, 1);
1738 self.copy(new_tail, self.tail, 1);
1739 // Already moved the tail, so we only copy `index - 1` elements.
1740 self.copy(self.tail, self.tail + 1, index - 1);
1742 self.tail = new_tail;
1745 (true, false, _) => {
1747 // contiguous, insert closer to head:
1750 // [. . . o o o o A o o . . . . . .]
1753 // [. . . o o o o I A o o . . . . .]
1756 self.copy(idx + 1, idx, self.head - idx);
1757 self.head = self.wrap_add(self.head, 1);
1760 (false, true, true) => {
1762 // discontiguous, insert closer to tail, tail section:
1765 // [o o o o o o . . . . . o o A o o]
1768 // [o o o o o o . . . . o o I A o o]
1771 self.copy(self.tail - 1, self.tail, index);
1775 (false, false, true) => {
1777 // discontiguous, insert closer to head, tail section:
1780 // [o o . . . . . . . o o o o o A o]
1783 // [o o o . . . . . . o o o o o I A]
1786 // copy elements up to new head
1787 self.copy(1, 0, self.head);
1789 // copy last element into empty spot at bottom of buffer
1790 self.copy(0, self.cap() - 1, 1);
1792 // move elements from idx to end forward not including ^ element
1793 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1798 (false, true, false) if idx == 0 => {
1800 // discontiguous, insert is closer to tail, head section,
1801 // and is at index zero in the internal buffer:
1804 // [A o o o o o o o o o . . . o o o]
1807 // [A o o o o o o o o o . . o o o I]
1810 // copy elements up to new tail
1811 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1813 // copy last element into empty spot at bottom of buffer
1814 self.copy(self.cap() - 1, 0, 1);
1819 (false, true, false) => {
1821 // discontiguous, insert closer to tail, head section:
1824 // [o o o A o o o o o o . . . o o o]
1827 // [o o I A o o o o o o . . o o o o]
1830 // copy elements up to new tail
1831 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1833 // copy last element into empty spot at bottom of buffer
1834 self.copy(self.cap() - 1, 0, 1);
1836 // move elements from idx-1 to end forward not including ^ element
1837 self.copy(0, 1, idx - 1);
1842 (false, false, false) => {
1844 // discontiguous, insert closer to head, head section:
1847 // [o o o o A o o . . . . . . o o o]
1850 // [o o o o I A o o . . . . . o o o]
1853 self.copy(idx + 1, idx, self.head - idx);
1859 // tail might've been changed so we need to recalculate
1860 let new_idx = self.wrap_add(self.tail, index);
1862 self.buffer_write(new_idx, value);
1866 /// Removes and returns the element at `index` from the deque.
1867 /// Whichever end is closer to the removal point will be moved to make
1868 /// room, and all the affected elements will be moved to new positions.
1869 /// Returns `None` if `index` is out of bounds.
1871 /// Element at index 0 is the front of the queue.
1876 /// use std::collections::VecDeque;
1878 /// let mut buf = VecDeque::new();
1879 /// buf.push_back(1);
1880 /// buf.push_back(2);
1881 /// buf.push_back(3);
1882 /// assert_eq!(buf, [1, 2, 3]);
1884 /// assert_eq!(buf.remove(1), Some(2));
1885 /// assert_eq!(buf, [1, 3]);
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 pub fn remove(&mut self, index: usize) -> Option<T> {
1889 if self.is_empty() || self.len() <= index {
1893 // There are three main cases:
1894 // Elements are contiguous
1895 // Elements are discontiguous and the removal is in the tail section
1896 // Elements are discontiguous and the removal is in the head section
1897 // - special case when elements are technically contiguous,
1898 // but self.head = 0
1900 // For each of those there are two more cases:
1901 // Insert is closer to tail
1902 // Insert is closer to head
1904 // Key: H - self.head
1906 // o - Valid element
1907 // x - Element marked for removal
1908 // R - Indicates element that is being removed
1909 // M - Indicates element was moved
1911 let idx = self.wrap_add(self.tail, index);
1913 let elem = unsafe { Some(self.buffer_read(idx)) };
1915 let distance_to_tail = index;
1916 let distance_to_head = self.len() - index;
1918 let contiguous = self.is_contiguous();
1920 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1921 (true, true, _) => {
1923 // contiguous, remove closer to tail:
1926 // [. . . o o x o o o o . . . . . .]
1929 // [. . . . o o o o o o . . . . . .]
1932 self.copy(self.tail + 1, self.tail, index);
1936 (true, false, _) => {
1938 // contiguous, remove closer to head:
1941 // [. . . o o o o x o o . . . . . .]
1944 // [. . . o o o o o o . . . . . . .]
1947 self.copy(idx, idx + 1, self.head - idx - 1);
1951 (false, true, true) => {
1953 // discontiguous, remove closer to tail, tail section:
1956 // [o o o o o o . . . . . o o x o o]
1959 // [o o o o o o . . . . . . o o o o]
1962 self.copy(self.tail + 1, self.tail, index);
1963 self.tail = self.wrap_add(self.tail, 1);
1966 (false, false, false) => {
1968 // discontiguous, remove closer to head, head section:
1971 // [o o o o x o o . . . . . . o o o]
1974 // [o o o o o o . . . . . . . o o o]
1977 self.copy(idx, idx + 1, self.head - idx - 1);
1981 (false, false, true) => {
1983 // discontiguous, remove closer to head, tail section:
1986 // [o o o . . . . . . o o o o o x o]
1989 // [o o . . . . . . . o o o o o o o]
1992 // or quasi-discontiguous, remove next to head, tail section:
1995 // [. . . . . . . . . o o o o o x o]
1998 // [. . . . . . . . . o o o o o o .]
2001 // draw in elements in the tail section
2002 self.copy(idx, idx + 1, self.cap() - idx - 1);
2004 // Prevents underflow.
2006 // copy first element into empty spot
2007 self.copy(self.cap() - 1, 0, 1);
2009 // move elements in the head section backwards
2010 self.copy(0, 1, self.head - 1);
2013 self.head = self.wrap_sub(self.head, 1);
2016 (false, true, false) => {
2018 // discontiguous, remove closer to tail, head section:
2021 // [o o x o o o o o o o . . . o o o]
2024 // [o o o o o o o o o o . . . . o o]
2027 // draw in elements up to idx
2028 self.copy(1, 0, idx);
2030 // copy last element into empty spot
2031 self.copy(0, self.cap() - 1, 1);
2033 // move elements from tail to end forward, excluding the last one
2034 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
2036 self.tail = self.wrap_add(self.tail, 1);
2044 /// Splits the deque into two at the given index.
2046 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2047 /// and the returned deque contains elements `[at, len)`.
2049 /// Note that the capacity of `self` does not change.
2051 /// Element at index 0 is the front of the queue.
2055 /// Panics if `at > len`.
2060 /// use std::collections::VecDeque;
2062 /// let mut buf: VecDeque<_> = [1, 2, 3].into();
2063 /// let buf2 = buf.split_off(1);
2064 /// assert_eq!(buf, [1]);
2065 /// assert_eq!(buf2, [2, 3]);
2068 #[must_use = "use `.truncate()` if you don't need the other half"]
2069 #[stable(feature = "split_off", since = "1.4.0")]
2070 pub fn split_off(&mut self, at: usize) -> Self
2074 let len = self.len();
2075 assert!(at <= len, "`at` out of bounds");
2077 let other_len = len - at;
2078 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2081 let (first_half, second_half) = self.as_slices();
2083 let first_len = first_half.len();
2084 let second_len = second_half.len();
2086 // `at` lies in the first half.
2087 let amount_in_first = first_len - at;
2089 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2091 // just take all of the second half.
2092 ptr::copy_nonoverlapping(
2093 second_half.as_ptr(),
2094 other.ptr().add(amount_in_first),
2098 // `at` lies in the second half, need to factor in the elements we skipped
2099 // in the first half.
2100 let offset = at - first_len;
2101 let amount_in_second = second_len - offset;
2102 ptr::copy_nonoverlapping(
2103 second_half.as_ptr().add(offset),
2110 // Cleanup where the ends of the buffers are
2111 self.head = self.wrap_sub(self.head, other_len);
2112 other.head = other.wrap_index(other_len);
2117 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2121 /// Panics if the new number of elements in self overflows a `usize`.
2126 /// use std::collections::VecDeque;
2128 /// let mut buf: VecDeque<_> = [1, 2].into();
2129 /// let mut buf2: VecDeque<_> = [3, 4].into();
2130 /// buf.append(&mut buf2);
2131 /// assert_eq!(buf, [1, 2, 3, 4]);
2132 /// assert_eq!(buf2, []);
2135 #[stable(feature = "append", since = "1.4.0")]
2136 pub fn append(&mut self, other: &mut Self) {
2137 self.reserve(other.len());
2139 let (left, right) = other.as_slices();
2140 self.copy_slice(self.head, left);
2141 self.copy_slice(self.wrap_add(self.head, left.len()), right);
2143 // SAFETY: Update pointers after copying to avoid leaving doppelganger
2144 // in case of panics.
2145 self.head = self.wrap_add(self.head, other.len());
2146 // Silently drop values in `other`.
2147 other.tail = other.head;
2150 /// Retains only the elements specified by the predicate.
2152 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2153 /// This method operates in place, visiting each element exactly once in the
2154 /// original order, and preserves the order of the retained elements.
2159 /// use std::collections::VecDeque;
2161 /// let mut buf = VecDeque::new();
2162 /// buf.extend(1..5);
2163 /// buf.retain(|&x| x % 2 == 0);
2164 /// assert_eq!(buf, [2, 4]);
2167 /// Because the elements are visited exactly once in the original order,
2168 /// external state may be used to decide which elements to keep.
2171 /// use std::collections::VecDeque;
2173 /// let mut buf = VecDeque::new();
2174 /// buf.extend(1..6);
2176 /// let keep = [false, true, true, false, true];
2177 /// let mut iter = keep.iter();
2178 /// buf.retain(|_| *iter.next().unwrap());
2179 /// assert_eq!(buf, [2, 3, 5]);
2181 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2182 pub fn retain<F>(&mut self, mut f: F)
2184 F: FnMut(&T) -> bool,
2186 self.retain_mut(|elem| f(elem));
2189 /// Retains only the elements specified by the predicate.
2191 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2192 /// This method operates in place, visiting each element exactly once in the
2193 /// original order, and preserves the order of the retained elements.
2198 /// use std::collections::VecDeque;
2200 /// let mut buf = VecDeque::new();
2201 /// buf.extend(1..5);
2202 /// buf.retain_mut(|x| if *x % 2 == 0 {
2208 /// assert_eq!(buf, [3, 5]);
2210 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2211 pub fn retain_mut<F>(&mut self, mut f: F)
2213 F: FnMut(&mut T) -> bool,
2215 let len = self.len();
2219 // Stage 1: All values are retained.
2221 if !f(&mut self[cur]) {
2228 // Stage 2: Swap retained value into current idx.
2230 if !f(&mut self[cur]) {
2235 self.swap(idx, cur);
2239 // Stage 3: Truncate all values after idx.
2245 // Double the buffer size. This method is inline(never), so we expect it to only
2246 // be called in cold paths.
2247 // This may panic or abort
2249 fn grow(&mut self) {
2250 // Extend or possibly remove this assertion when valid use-cases for growing the
2251 // buffer without it being full emerge
2252 debug_assert!(self.is_full());
2253 let old_cap = self.cap();
2254 self.buf.reserve_exact(old_cap, old_cap);
2255 assert!(self.cap() == old_cap * 2);
2257 self.handle_capacity_increase(old_cap);
2259 debug_assert!(!self.is_full());
2262 /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2263 /// either by removing excess elements from the back or by appending
2264 /// elements generated by calling `generator` to the back.
2269 /// use std::collections::VecDeque;
2271 /// let mut buf = VecDeque::new();
2272 /// buf.push_back(5);
2273 /// buf.push_back(10);
2274 /// buf.push_back(15);
2275 /// assert_eq!(buf, [5, 10, 15]);
2277 /// buf.resize_with(5, Default::default);
2278 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2280 /// buf.resize_with(2, || unreachable!());
2281 /// assert_eq!(buf, [5, 10]);
2283 /// let mut state = 100;
2284 /// buf.resize_with(5, || { state += 1; state });
2285 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2287 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2288 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2289 let len = self.len();
2292 self.extend(repeat_with(generator).take(new_len - len))
2294 self.truncate(new_len);
2298 /// Rearranges the internal storage of this deque so it is one contiguous
2299 /// slice, which is then returned.
2301 /// This method does not allocate and does not change the order of the
2302 /// inserted elements. As it returns a mutable slice, this can be used to
2305 /// Once the internal storage is contiguous, the [`as_slices`] and
2306 /// [`as_mut_slices`] methods will return the entire contents of the
2307 /// deque in a single slice.
2309 /// [`as_slices`]: VecDeque::as_slices
2310 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2314 /// Sorting the content of a deque.
2317 /// use std::collections::VecDeque;
2319 /// let mut buf = VecDeque::with_capacity(15);
2321 /// buf.push_back(2);
2322 /// buf.push_back(1);
2323 /// buf.push_front(3);
2325 /// // sorting the deque
2326 /// buf.make_contiguous().sort();
2327 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2329 /// // sorting it in reverse order
2330 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2331 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2334 /// Getting immutable access to the contiguous slice.
2337 /// use std::collections::VecDeque;
2339 /// let mut buf = VecDeque::new();
2341 /// buf.push_back(2);
2342 /// buf.push_back(1);
2343 /// buf.push_front(3);
2345 /// buf.make_contiguous();
2346 /// if let (slice, &[]) = buf.as_slices() {
2347 /// // we can now be sure that `slice` contains all elements of the deque,
2348 /// // while still having immutable access to `buf`.
2349 /// assert_eq!(buf.len(), slice.len());
2350 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2353 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2354 pub fn make_contiguous(&mut self) -> &mut [T] {
2355 if self.is_contiguous() {
2356 let tail = self.tail;
2357 let head = self.head;
2359 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2360 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2362 MaybeUninit::slice_assume_init_mut(
2363 RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2368 let buf = self.buf.ptr();
2369 let cap = self.cap();
2370 let len = self.len();
2372 let free = self.tail - self.head;
2373 let tail_len = cap - self.tail;
2375 if free >= tail_len {
2376 // there is enough free space to copy the tail in one go,
2377 // this means that we first shift the head backwards, and then
2378 // copy the tail to the correct position.
2380 // from: DEFGH....ABC
2383 ptr::copy(buf, buf.add(tail_len), self.head);
2385 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2391 } else if free > self.head {
2392 // FIXME: We currently do not consider ....ABCDEFGH
2393 // to be contiguous because `head` would be `0` in this
2394 // case. While we probably want to change this it
2395 // isn't trivial as a few places expect `is_contiguous`
2396 // to mean that we can just slice using `buf[tail..head]`.
2398 // there is enough free space to copy the head in one go,
2399 // this means that we first shift the tail forwards, and then
2400 // copy the head to the correct position.
2402 // from: FGH....ABCDE
2405 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2407 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2410 self.tail = self.head;
2411 self.head = self.wrap_add(self.tail, len);
2414 // free is smaller than both head and tail,
2415 // this means we have to slowly "swap" the tail and the head.
2417 // from: EFGHI...ABCD or HIJK.ABCDEFG
2418 // to: ABCDEFGHI... or ABCDEFGHIJK.
2419 let mut left_edge: usize = 0;
2420 let mut right_edge: usize = self.tail;
2422 // The general problem looks like this
2423 // GHIJKLM...ABCDEF - before any swaps
2424 // ABCDEFM...GHIJKL - after 1 pass of swaps
2425 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2426 // - then restart the algorithm with a new (smaller) store
2427 // Sometimes the temp store is reached when the right edge is at the end
2428 // of the buffer - this means we've hit the right order with fewer swaps!
2431 // ABCDEF.. - after four only swaps we've finished
2432 while left_edge < len && right_edge != cap {
2433 let mut right_offset = 0;
2434 for i in left_edge..right_edge {
2435 right_offset = (i - left_edge) % (cap - right_edge);
2436 let src: isize = (right_edge + right_offset) as isize;
2437 ptr::swap(buf.add(i), buf.offset(src));
2439 let n_ops = right_edge - left_edge;
2441 right_edge += right_offset + 1;
2449 let tail = self.tail;
2450 let head = self.head;
2452 // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2453 // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2455 MaybeUninit::slice_assume_init_mut(
2456 RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2461 /// Rotates the double-ended queue `mid` places to the left.
2464 /// - Rotates item `mid` into the first position.
2465 /// - Pops the first `mid` items and pushes them to the end.
2466 /// - Rotates `len() - mid` places to the right.
2470 /// If `mid` is greater than `len()`. Note that `mid == len()`
2471 /// does _not_ panic and is a no-op rotation.
2475 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2480 /// use std::collections::VecDeque;
2482 /// let mut buf: VecDeque<_> = (0..10).collect();
2484 /// buf.rotate_left(3);
2485 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2487 /// for i in 1..10 {
2488 /// assert_eq!(i * 3 % 10, buf[0]);
2489 /// buf.rotate_left(3);
2491 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2493 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2494 pub fn rotate_left(&mut self, mid: usize) {
2495 assert!(mid <= self.len());
2496 let k = self.len() - mid;
2498 unsafe { self.rotate_left_inner(mid) }
2500 unsafe { self.rotate_right_inner(k) }
2504 /// Rotates the double-ended queue `k` places to the right.
2507 /// - Rotates the first item into position `k`.
2508 /// - Pops the last `k` items and pushes them to the front.
2509 /// - Rotates `len() - k` places to the left.
2513 /// If `k` is greater than `len()`. Note that `k == len()`
2514 /// does _not_ panic and is a no-op rotation.
2518 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2523 /// use std::collections::VecDeque;
2525 /// let mut buf: VecDeque<_> = (0..10).collect();
2527 /// buf.rotate_right(3);
2528 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2530 /// for i in 1..10 {
2531 /// assert_eq!(0, buf[i * 3 % 10]);
2532 /// buf.rotate_right(3);
2534 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2536 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2537 pub fn rotate_right(&mut self, k: usize) {
2538 assert!(k <= self.len());
2539 let mid = self.len() - k;
2541 unsafe { self.rotate_right_inner(k) }
2543 unsafe { self.rotate_left_inner(mid) }
2547 // SAFETY: the following two methods require that the rotation amount
2548 // be less than half the length of the deque.
2550 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2551 // but than `min` is never more than half the capacity, regardless of x,
2552 // so it's sound to call here because we're calling with something
2553 // less than half the length, which is never above half the capacity.
2555 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2556 debug_assert!(mid * 2 <= self.len());
2558 self.wrap_copy(self.head, self.tail, mid);
2560 self.head = self.wrap_add(self.head, mid);
2561 self.tail = self.wrap_add(self.tail, mid);
2564 unsafe fn rotate_right_inner(&mut self, k: usize) {
2565 debug_assert!(k * 2 <= self.len());
2566 self.head = self.wrap_sub(self.head, k);
2567 self.tail = self.wrap_sub(self.tail, k);
2569 self.wrap_copy(self.tail, self.head, k);
2573 /// Binary searches this `VecDeque` for a given element.
2574 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2576 /// If the value is found then [`Result::Ok`] is returned, containing the
2577 /// index of the matching element. If there are multiple matches, then any
2578 /// one of the matches could be returned. If the value is not found then
2579 /// [`Result::Err`] is returned, containing the index where a matching
2580 /// element could be inserted while maintaining sorted order.
2582 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2584 /// [`contains`]: VecDeque::contains
2585 /// [`binary_search_by`]: VecDeque::binary_search_by
2586 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2587 /// [`partition_point`]: VecDeque::partition_point
2591 /// Looks up a series of four elements. The first is found, with a
2592 /// uniquely determined position; the second and third are not
2593 /// found; the fourth could match any position in `[1, 4]`.
2596 /// use std::collections::VecDeque;
2598 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2600 /// assert_eq!(deque.binary_search(&13), Ok(9));
2601 /// assert_eq!(deque.binary_search(&4), Err(7));
2602 /// assert_eq!(deque.binary_search(&100), Err(13));
2603 /// let r = deque.binary_search(&1);
2604 /// assert!(matches!(r, Ok(1..=4)));
2607 /// If you want to insert an item to a sorted deque, while maintaining
2608 /// sort order, consider using [`partition_point`]:
2611 /// use std::collections::VecDeque;
2613 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2615 /// let idx = deque.partition_point(|&x| x < num);
2616 /// // The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
2617 /// deque.insert(idx, num);
2618 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2620 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2622 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2626 self.binary_search_by(|e| e.cmp(x))
2629 /// Binary searches this `VecDeque` with a comparator function.
2630 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2632 /// The comparator function should implement an order consistent
2633 /// with the sort order of the deque, returning an order code that
2634 /// indicates whether its argument is `Less`, `Equal` or `Greater`
2635 /// than the desired target.
2637 /// If the value is found then [`Result::Ok`] is returned, containing the
2638 /// index of the matching element. If there are multiple matches, then any
2639 /// one of the matches could be returned. If the value is not found then
2640 /// [`Result::Err`] is returned, containing the index where a matching
2641 /// element could be inserted while maintaining sorted order.
2643 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2645 /// [`contains`]: VecDeque::contains
2646 /// [`binary_search`]: VecDeque::binary_search
2647 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2648 /// [`partition_point`]: VecDeque::partition_point
2652 /// Looks up a series of four elements. The first is found, with a
2653 /// uniquely determined position; the second and third are not
2654 /// found; the fourth could match any position in `[1, 4]`.
2657 /// use std::collections::VecDeque;
2659 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2661 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2662 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2663 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2664 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2665 /// assert!(matches!(r, Ok(1..=4)));
2667 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2668 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2670 F: FnMut(&'a T) -> Ordering,
2672 let (front, back) = self.as_slices();
2673 let cmp_back = back.first().map(|elem| f(elem));
2675 if let Some(Ordering::Equal) = cmp_back {
2677 } else if let Some(Ordering::Less) = cmp_back {
2678 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2680 front.binary_search_by(f)
2684 /// Binary searches this `VecDeque` with a key extraction function.
2685 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2687 /// Assumes that the deque is sorted by the key, for instance with
2688 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2690 /// If the value is found then [`Result::Ok`] is returned, containing the
2691 /// index of the matching element. If there are multiple matches, then any
2692 /// one of the matches could be returned. If the value is not found then
2693 /// [`Result::Err`] is returned, containing the index where a matching
2694 /// element could be inserted while maintaining sorted order.
2696 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2698 /// [`contains`]: VecDeque::contains
2699 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2700 /// [`binary_search`]: VecDeque::binary_search
2701 /// [`binary_search_by`]: VecDeque::binary_search_by
2702 /// [`partition_point`]: VecDeque::partition_point
2706 /// Looks up a series of four elements in a slice of pairs sorted by
2707 /// their second elements. The first is found, with a uniquely
2708 /// determined position; the second and third are not found; the
2709 /// fourth could match any position in `[1, 4]`.
2712 /// use std::collections::VecDeque;
2714 /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
2715 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2716 /// (1, 21), (2, 34), (4, 55)].into();
2718 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2719 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2720 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2721 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2722 /// assert!(matches!(r, Ok(1..=4)));
2724 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2726 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2728 F: FnMut(&'a T) -> B,
2731 self.binary_search_by(|k| f(k).cmp(b))
2734 /// Returns the index of the partition point according to the given predicate
2735 /// (the index of the first element of the second partition).
2737 /// The deque is assumed to be partitioned according to the given predicate.
2738 /// This means that all elements for which the predicate returns true are at the start of the deque
2739 /// and all elements for which the predicate returns false are at the end.
2740 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2741 /// (all odd numbers are at the start, all even at the end).
2743 /// If the deque is not partitioned, the returned result is unspecified and meaningless,
2744 /// as this method performs a kind of binary search.
2746 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2748 /// [`binary_search`]: VecDeque::binary_search
2749 /// [`binary_search_by`]: VecDeque::binary_search_by
2750 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2755 /// use std::collections::VecDeque;
2757 /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
2758 /// let i = deque.partition_point(|&x| x < 5);
2760 /// assert_eq!(i, 4);
2761 /// assert!(deque.iter().take(i).all(|&x| x < 5));
2762 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2765 /// If you want to insert an item to a sorted deque, while maintaining
2769 /// use std::collections::VecDeque;
2771 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2773 /// let idx = deque.partition_point(|&x| x < num);
2774 /// deque.insert(idx, num);
2775 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2777 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2778 pub fn partition_point<P>(&self, mut pred: P) -> usize
2780 P: FnMut(&T) -> bool,
2782 let (front, back) = self.as_slices();
2784 if let Some(true) = back.first().map(|v| pred(v)) {
2785 back.partition_point(pred) + front.len()
2787 front.partition_point(pred)
2792 impl<T: Clone, A: Allocator> VecDeque<T, A> {
2793 /// Modifies the deque in-place so that `len()` is equal to new_len,
2794 /// either by removing excess elements from the back or by appending clones of `value`
2800 /// use std::collections::VecDeque;
2802 /// let mut buf = VecDeque::new();
2803 /// buf.push_back(5);
2804 /// buf.push_back(10);
2805 /// buf.push_back(15);
2806 /// assert_eq!(buf, [5, 10, 15]);
2808 /// buf.resize(2, 0);
2809 /// assert_eq!(buf, [5, 10]);
2811 /// buf.resize(5, 20);
2812 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2814 #[stable(feature = "deque_extras", since = "1.16.0")]
2815 pub fn resize(&mut self, new_len: usize, value: T) {
2816 self.resize_with(new_len, || value.clone());
2820 /// Returns the index in the underlying buffer for a given logical element index.
2822 fn wrap_index(index: usize, size: usize) -> usize {
2823 // size is always a power of 2
2824 debug_assert!(size.is_power_of_two());
2828 /// Calculate the number of elements left to be read in the buffer
2830 fn count(tail: usize, head: usize, size: usize) -> usize {
2831 // size is always a power of 2
2832 (head.wrapping_sub(tail)) & (size - 1)
2835 #[stable(feature = "rust1", since = "1.0.0")]
2836 impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
2837 fn eq(&self, other: &Self) -> bool {
2838 if self.len() != other.len() {
2841 let (sa, sb) = self.as_slices();
2842 let (oa, ob) = other.as_slices();
2843 if sa.len() == oa.len() {
2844 sa == oa && sb == ob
2845 } else if sa.len() < oa.len() {
2846 // Always divisible in three sections, for example:
2847 // self: [a b c|d e f]
2848 // other: [0 1 2 3|4 5]
2849 // front = 3, mid = 1,
2850 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2851 let front = sa.len();
2852 let mid = oa.len() - front;
2854 let (oa_front, oa_mid) = oa.split_at(front);
2855 let (sb_mid, sb_back) = sb.split_at(mid);
2856 debug_assert_eq!(sa.len(), oa_front.len());
2857 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2858 debug_assert_eq!(sb_back.len(), ob.len());
2859 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2861 let front = oa.len();
2862 let mid = sa.len() - front;
2864 let (sa_front, sa_mid) = sa.split_at(front);
2865 let (ob_mid, ob_back) = ob.split_at(mid);
2866 debug_assert_eq!(sa_front.len(), oa.len());
2867 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2868 debug_assert_eq!(sb.len(), ob_back.len());
2869 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2874 #[stable(feature = "rust1", since = "1.0.0")]
2875 impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
2877 __impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2878 __impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2879 __impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2880 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2881 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2882 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2884 #[stable(feature = "rust1", since = "1.0.0")]
2885 impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
2886 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2887 self.iter().partial_cmp(other.iter())
2891 #[stable(feature = "rust1", since = "1.0.0")]
2892 impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
2894 fn cmp(&self, other: &Self) -> Ordering {
2895 self.iter().cmp(other.iter())
2899 #[stable(feature = "rust1", since = "1.0.0")]
2900 impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
2901 fn hash<H: Hasher>(&self, state: &mut H) {
2902 self.len().hash(state);
2903 // It's not possible to use Hash::hash_slice on slices
2904 // returned by as_slices method as their length can vary
2905 // in otherwise identical deques.
2907 // Hasher only guarantees equivalence for the exact same
2908 // set of calls to its methods.
2909 self.iter().for_each(|elem| elem.hash(state));
2913 #[stable(feature = "rust1", since = "1.0.0")]
2914 impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
2918 fn index(&self, index: usize) -> &T {
2919 self.get(index).expect("Out of bounds access")
2923 #[stable(feature = "rust1", since = "1.0.0")]
2924 impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
2926 fn index_mut(&mut self, index: usize) -> &mut T {
2927 self.get_mut(index).expect("Out of bounds access")
2931 #[stable(feature = "rust1", since = "1.0.0")]
2932 impl<T> FromIterator<T> for VecDeque<T> {
2933 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
2934 let iterator = iter.into_iter();
2935 let (lower, _) = iterator.size_hint();
2936 let mut deq = VecDeque::with_capacity(lower);
2937 deq.extend(iterator);
2942 #[stable(feature = "rust1", since = "1.0.0")]
2943 impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
2945 type IntoIter = IntoIter<T, A>;
2947 /// Consumes the deque into a front-to-back iterator yielding elements by
2949 fn into_iter(self) -> IntoIter<T, A> {
2954 #[stable(feature = "rust1", since = "1.0.0")]
2955 impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
2957 type IntoIter = Iter<'a, T>;
2959 fn into_iter(self) -> Iter<'a, T> {
2964 #[stable(feature = "rust1", since = "1.0.0")]
2965 impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
2966 type Item = &'a mut T;
2967 type IntoIter = IterMut<'a, T>;
2969 fn into_iter(self) -> IterMut<'a, T> {
2974 #[stable(feature = "rust1", since = "1.0.0")]
2975 impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
2976 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2977 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter());
2981 fn extend_one(&mut self, elem: T) {
2982 self.push_back(elem);
2986 fn extend_reserve(&mut self, additional: usize) {
2987 self.reserve(additional);
2991 #[stable(feature = "extend_ref", since = "1.2.0")]
2992 impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
2993 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2994 self.spec_extend(iter.into_iter());
2998 fn extend_one(&mut self, &elem: &T) {
2999 self.push_back(elem);
3003 fn extend_reserve(&mut self, additional: usize) {
3004 self.reserve(additional);
3008 #[stable(feature = "rust1", since = "1.0.0")]
3009 impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
3010 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3011 f.debug_list().entries(self).finish()
3015 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3016 impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
3017 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3019 /// [`Vec<T>`]: crate::vec::Vec
3020 /// [`VecDeque<T>`]: crate::collections::VecDeque
3022 /// This avoids reallocating where possible, but the conditions for that are
3023 /// strict, and subject to change, and so shouldn't be relied upon unless the
3024 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
3025 fn from(mut other: Vec<T, A>) -> Self {
3026 let len = other.len();
3027 if mem::size_of::<T>() == 0 {
3028 // There's no actual allocation for ZSTs to worry about capacity,
3029 // but `VecDeque` can't handle as much length as `Vec`.
3030 assert!(len < MAXIMUM_ZST_CAPACITY, "capacity overflow");
3032 // We need to resize if the capacity is not a power of two, too small or
3033 // doesn't have at least one free space. We do this while it's still in
3034 // the `Vec` so the items will drop on panic.
3035 let min_cap = cmp::max(MINIMUM_CAPACITY, len) + 1;
3036 let cap = cmp::max(min_cap, other.capacity()).next_power_of_two();
3037 if other.capacity() != cap {
3038 other.reserve_exact(cap - len);
3043 let (other_buf, len, capacity, alloc) = other.into_raw_parts_with_alloc();
3044 let buf = RawVec::from_raw_parts_in(other_buf, capacity, alloc);
3045 VecDeque { tail: 0, head: len, buf }
3050 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3051 impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
3052 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
3054 /// [`Vec<T>`]: crate::vec::Vec
3055 /// [`VecDeque<T>`]: crate::collections::VecDeque
3057 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
3058 /// the circular buffer doesn't happen to be at the beginning of the allocation.
3063 /// use std::collections::VecDeque;
3065 /// // This one is *O*(1).
3066 /// let deque: VecDeque<_> = (1..5).collect();
3067 /// let ptr = deque.as_slices().0.as_ptr();
3068 /// let vec = Vec::from(deque);
3069 /// assert_eq!(vec, [1, 2, 3, 4]);
3070 /// assert_eq!(vec.as_ptr(), ptr);
3072 /// // This one needs data rearranging.
3073 /// let mut deque: VecDeque<_> = (1..5).collect();
3074 /// deque.push_front(9);
3075 /// deque.push_front(8);
3076 /// let ptr = deque.as_slices().1.as_ptr();
3077 /// let vec = Vec::from(deque);
3078 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
3079 /// assert_eq!(vec.as_ptr(), ptr);
3081 fn from(mut other: VecDeque<T, A>) -> Self {
3082 other.make_contiguous();
3085 let other = ManuallyDrop::new(other);
3086 let buf = other.buf.ptr();
3087 let len = other.len();
3088 let cap = other.cap();
3089 let alloc = ptr::read(other.allocator());
3091 if other.tail != 0 {
3092 ptr::copy(buf.add(other.tail), buf, len);
3094 Vec::from_raw_parts_in(buf, len, cap, alloc)
3099 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
3100 impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
3101 /// Converts a `[T; N]` into a `VecDeque<T>`.
3104 /// use std::collections::VecDeque;
3106 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
3107 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
3108 /// assert_eq!(deq1, deq2);
3110 fn from(arr: [T; N]) -> Self {
3111 let mut deq = VecDeque::with_capacity(N);
3112 let arr = ManuallyDrop::new(arr);
3113 if mem::size_of::<T>() != 0 {
3114 // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
3116 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);