1 //! A double-ended queue 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};
16 use core::ops::{Index, IndexMut, Range, RangeBounds};
17 use core::ptr::{self, NonNull};
20 use crate::alloc::{Allocator, Global};
21 use crate::collections::TryReserveError;
22 use crate::collections::TryReserveErrorKind;
23 use crate::raw_vec::RawVec;
29 #[stable(feature = "drain", since = "1.6.0")]
30 pub use self::drain::Drain;
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use self::iter_mut::IterMut;
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub use self::into_iter::IntoIter;
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub use self::iter::Iter;
49 use self::pair_slices::PairSlices;
53 use self::ring_slices::RingSlices;
60 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
61 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
63 const MAXIMUM_ZST_CAPACITY: usize = 1 << (usize::BITS - 1); // Largest possible power of two
65 /// A double-ended queue implemented with a growable ring buffer.
67 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
68 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
69 /// push onto the back in this manner, and iterating over `VecDeque` goes front
72 /// A `VecDeque` with a known list of items can be initialized from an array:
75 /// use std::collections::VecDeque;
77 /// let deq = VecDeque::from([-1, 0, 1]);
80 /// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
81 /// in memory. If you want to access the elements as a single slice, such as for
82 /// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
83 /// so that its elements do not wrap, and returns a mutable slice to the
84 /// now-contiguous element sequence.
86 /// [`push_back`]: VecDeque::push_back
87 /// [`pop_front`]: VecDeque::pop_front
88 /// [`extend`]: VecDeque::extend
89 /// [`append`]: VecDeque::append
90 /// [`make_contiguous`]: VecDeque::make_contiguous
91 #[cfg_attr(not(test), rustc_diagnostic_item = "VecDeque")]
92 #[stable(feature = "rust1", since = "1.0.0")]
93 #[rustc_insignificant_dtor]
96 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
98 // tail and head are pointers into the buffer. Tail always points
99 // to the first element that could be read, Head always points
100 // to where data should be written.
101 // If tail == head the buffer is empty. The length of the ringbuffer
102 // is defined as the distance between the two.
108 #[stable(feature = "rust1", since = "1.0.0")]
109 impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A> {
110 fn clone(&self) -> Self {
111 let mut deq = Self::with_capacity_in(self.len(), self.allocator().clone());
112 deq.extend(self.iter().cloned());
116 fn clone_from(&mut self, other: &Self) {
117 self.truncate(other.len());
119 let mut iter = PairSlices::from(self, other);
120 while let Some((dst, src)) = iter.next() {
121 dst.clone_from_slice(&src);
124 if iter.has_remainder() {
125 for remainder in iter.remainder() {
126 self.extend(remainder.iter().cloned());
132 #[stable(feature = "rust1", since = "1.0.0")]
133 unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
135 /// Runs the destructor for all items in the slice when it gets dropped (normally or
136 /// during unwinding).
137 struct Dropper<'a, T>(&'a mut [T]);
139 impl<'a, T> Drop for Dropper<'a, T> {
142 ptr::drop_in_place(self.0);
147 let (front, back) = self.as_mut_slices();
149 let _back_dropper = Dropper(back);
151 ptr::drop_in_place(front);
153 // RawVec handles deallocation
157 #[stable(feature = "rust1", since = "1.0.0")]
158 impl<T> Default for VecDeque<T> {
159 /// Creates an empty `VecDeque<T>`.
161 fn default() -> VecDeque<T> {
166 impl<T, A: Allocator> VecDeque<T, A> {
167 /// Marginally more convenient
169 fn ptr(&self) -> *mut T {
173 /// Marginally more convenient
175 fn cap(&self) -> usize {
176 if mem::size_of::<T>() == 0 {
177 // For zero sized types, we are always at maximum capacity
184 /// Turn ptr into a slice
186 unsafe fn buffer_as_slice(&self) -> &[T] {
187 unsafe { slice::from_raw_parts(self.ptr(), self.cap()) }
190 /// Turn ptr into a mut slice
192 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
193 unsafe { slice::from_raw_parts_mut(self.ptr(), self.cap()) }
196 /// Moves an element out of the buffer
198 unsafe fn buffer_read(&mut self, off: usize) -> T {
199 unsafe { ptr::read(self.ptr().add(off)) }
202 /// Writes an element into the buffer, moving it.
204 unsafe fn buffer_write(&mut self, off: usize, value: T) {
206 ptr::write(self.ptr().add(off), value);
210 /// Returns `true` if the buffer is at full capacity.
212 fn is_full(&self) -> bool {
213 self.cap() - self.len() == 1
216 /// Returns the index in the underlying buffer for a given logical element
219 fn wrap_index(&self, idx: usize) -> usize {
220 wrap_index(idx, self.cap())
223 /// Returns the index in the underlying buffer for a given logical element
226 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
227 wrap_index(idx.wrapping_add(addend), self.cap())
230 /// Returns the index in the underlying buffer for a given logical element
231 /// index - subtrahend.
233 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
234 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
237 /// Copies a contiguous block of memory len long from src to dst
239 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
241 dst + len <= self.cap(),
242 "cpy dst={} src={} len={} cap={}",
249 src + len <= self.cap(),
250 "cpy dst={} src={} len={} cap={}",
257 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
261 /// Copies a contiguous block of memory len long from src to dst
263 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
265 dst + len <= self.cap(),
266 "cno dst={} src={} len={} cap={}",
273 src + len <= self.cap(),
274 "cno dst={} src={} len={} cap={}",
281 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
285 /// Copies a potentially wrapping block of memory len long from src to dest.
286 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
287 /// most one continuous overlapping region between src and dest).
288 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
290 fn diff(a: usize, b: usize) -> usize {
291 if a <= b { b - a } else { a - b }
294 cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
295 "wrc dst={} src={} len={} cap={}",
302 if src == dst || len == 0 {
306 let dst_after_src = self.wrap_sub(dst, src) < len;
308 let src_pre_wrap_len = self.cap() - src;
309 let dst_pre_wrap_len = self.cap() - dst;
310 let src_wraps = src_pre_wrap_len < len;
311 let dst_wraps = dst_pre_wrap_len < len;
313 match (dst_after_src, src_wraps, dst_wraps) {
314 (_, false, false) => {
315 // src doesn't wrap, dst doesn't wrap
318 // 1 [_ _ A A B B C C _]
319 // 2 [_ _ A A A A B B _]
323 self.copy(dst, src, len);
326 (false, false, true) => {
327 // dst before src, src doesn't wrap, dst wraps
330 // 1 [A A B B _ _ _ C C]
331 // 2 [A A B B _ _ _ A A]
332 // 3 [B B B B _ _ _ A A]
336 self.copy(dst, src, dst_pre_wrap_len);
337 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
340 (true, false, true) => {
341 // src before dst, src doesn't wrap, dst wraps
344 // 1 [C C _ _ _ A A B B]
345 // 2 [B B _ _ _ A A B B]
346 // 3 [B B _ _ _ A A A A]
350 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
351 self.copy(dst, src, dst_pre_wrap_len);
354 (false, true, false) => {
355 // dst before src, src wraps, dst doesn't wrap
358 // 1 [C C _ _ _ A A B B]
359 // 2 [C C _ _ _ B B B B]
360 // 3 [C C _ _ _ B B C C]
364 self.copy(dst, src, src_pre_wrap_len);
365 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
368 (true, true, false) => {
369 // src before dst, src wraps, dst doesn't wrap
372 // 1 [A A B B _ _ _ C C]
373 // 2 [A A A A _ _ _ C C]
374 // 3 [C C A A _ _ _ C C]
378 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
379 self.copy(dst, src, src_pre_wrap_len);
382 (false, true, true) => {
383 // dst before src, src wraps, dst wraps
386 // 1 [A B C D _ E F G H]
387 // 2 [A B C D _ E G H H]
388 // 3 [A B C D _ E G H A]
389 // 4 [B C C D _ E G H A]
392 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
393 let delta = dst_pre_wrap_len - src_pre_wrap_len;
395 self.copy(dst, src, src_pre_wrap_len);
396 self.copy(dst + src_pre_wrap_len, 0, delta);
397 self.copy(0, delta, len - dst_pre_wrap_len);
400 (true, true, true) => {
401 // src before dst, src wraps, dst wraps
404 // 1 [A B C D _ E F G H]
405 // 2 [A A B D _ E F G H]
406 // 3 [H A B D _ E F G H]
407 // 4 [H A B D _ E F F G]
410 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
411 let delta = src_pre_wrap_len - dst_pre_wrap_len;
413 self.copy(delta, 0, len - src_pre_wrap_len);
414 self.copy(0, self.cap() - delta, delta);
415 self.copy(dst, src, dst_pre_wrap_len);
421 /// Copies all values from `src` to `dst`, wrapping around if needed.
422 /// Assumes capacity is sufficient.
424 unsafe fn copy_slice(&mut self, dst: usize, src: &[T]) {
425 debug_assert!(src.len() <= self.cap());
426 let head_room = self.cap() - dst;
427 if src.len() <= head_room {
429 ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst), src.len());
432 let (left, right) = src.split_at(head_room);
434 ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst), left.len());
435 ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
440 /// Frobs the head and tail sections around to handle the fact that we
441 /// just reallocated. Unsafe because it trusts old_capacity.
443 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
444 let new_capacity = self.cap();
446 // Move the shortest contiguous section of the ring buffer
448 // [o o o o o o o . ]
450 // A [o o o o o o o . . . . . . . . . ]
452 // [o o . o o o o o ]
454 // B [. . . o o o o o o o . . . . . . ]
456 // [o o o o o . o o ]
458 // C [o o o o o . . . . . . . . . o o ]
460 if self.tail <= self.head {
463 } else if self.head < old_capacity - self.tail {
466 self.copy_nonoverlapping(old_capacity, 0, self.head);
468 self.head += old_capacity;
469 debug_assert!(self.head > self.tail);
472 let new_tail = new_capacity - (old_capacity - self.tail);
474 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
476 self.tail = new_tail;
477 debug_assert!(self.head < self.tail);
479 debug_assert!(self.head < self.cap());
480 debug_assert!(self.tail < self.cap());
481 debug_assert!(self.cap().count_ones() == 1);
485 impl<T> VecDeque<T> {
486 /// Creates an empty `VecDeque`.
491 /// use std::collections::VecDeque;
493 /// let vector: VecDeque<u32> = VecDeque::new();
496 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn new() -> VecDeque<T> {
499 VecDeque::new_in(Global)
502 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
507 /// use std::collections::VecDeque;
509 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
512 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
515 Self::with_capacity_in(capacity, Global)
519 impl<T, A: Allocator> VecDeque<T, A> {
520 /// Creates an empty `VecDeque`.
525 /// use std::collections::VecDeque;
527 /// let vector: VecDeque<u32> = VecDeque::new();
530 #[unstable(feature = "allocator_api", issue = "32838")]
531 pub fn new_in(alloc: A) -> VecDeque<T, A> {
532 VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc)
535 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
540 /// use std::collections::VecDeque;
542 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
544 #[unstable(feature = "allocator_api", issue = "32838")]
545 pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
546 assert!(capacity < 1_usize << usize::BITS - 1, "capacity overflow");
547 // +1 since the ringbuffer always leaves one space empty
548 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
550 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) }
553 /// Provides a reference to the element at the given index.
555 /// Element at index 0 is the front of the queue.
560 /// use std::collections::VecDeque;
562 /// let mut buf = VecDeque::new();
563 /// buf.push_back(3);
564 /// buf.push_back(4);
565 /// buf.push_back(5);
566 /// assert_eq!(buf.get(1), Some(&4));
568 #[stable(feature = "rust1", since = "1.0.0")]
569 pub fn get(&self, index: usize) -> Option<&T> {
570 if index < self.len() {
571 let idx = self.wrap_add(self.tail, index);
572 unsafe { Some(&*self.ptr().add(idx)) }
578 /// Provides a mutable reference to the element at the given index.
580 /// Element at index 0 is the front of the queue.
585 /// use std::collections::VecDeque;
587 /// let mut buf = VecDeque::new();
588 /// buf.push_back(3);
589 /// buf.push_back(4);
590 /// buf.push_back(5);
591 /// if let Some(elem) = buf.get_mut(1) {
595 /// assert_eq!(buf[1], 7);
597 #[stable(feature = "rust1", since = "1.0.0")]
598 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
599 if index < self.len() {
600 let idx = self.wrap_add(self.tail, index);
601 unsafe { Some(&mut *self.ptr().add(idx)) }
607 /// Swaps elements at indices `i` and `j`.
609 /// `i` and `j` may be equal.
611 /// Element at index 0 is the front of the queue.
615 /// Panics if either index is out of bounds.
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 /// assert_eq!(buf, [3, 4, 5]);
628 /// assert_eq!(buf, [5, 4, 3]);
630 #[stable(feature = "rust1", since = "1.0.0")]
631 pub fn swap(&mut self, i: usize, j: usize) {
632 assert!(i < self.len());
633 assert!(j < self.len());
634 let ri = self.wrap_add(self.tail, i);
635 let rj = self.wrap_add(self.tail, j);
636 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
639 /// Returns the number of elements the `VecDeque` can hold without
645 /// use std::collections::VecDeque;
647 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
648 /// assert!(buf.capacity() >= 10);
651 #[stable(feature = "rust1", since = "1.0.0")]
652 pub fn capacity(&self) -> usize {
656 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
657 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
659 /// Note that the allocator may give the collection more space than it requests. Therefore
660 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
661 /// insertions are expected.
665 /// Panics if the new capacity overflows `usize`.
670 /// use std::collections::VecDeque;
672 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
673 /// buf.reserve_exact(10);
674 /// assert!(buf.capacity() >= 11);
677 /// [`reserve`]: VecDeque::reserve
678 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn reserve_exact(&mut self, additional: usize) {
680 self.reserve(additional);
683 /// Reserves capacity for at least `additional` more elements to be inserted in the given
684 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
688 /// Panics if the new capacity overflows `usize`.
693 /// use std::collections::VecDeque;
695 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
697 /// assert!(buf.capacity() >= 11);
699 #[stable(feature = "rust1", since = "1.0.0")]
700 pub fn reserve(&mut self, additional: usize) {
701 let old_cap = self.cap();
702 let used_cap = self.len() + 1;
703 let new_cap = used_cap
704 .checked_add(additional)
705 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
706 .expect("capacity overflow");
708 if new_cap > old_cap {
709 self.buf.reserve_exact(used_cap, new_cap - used_cap);
711 self.handle_capacity_increase(old_cap);
716 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
717 /// be inserted in the given `VecDeque<T>`. After calling `try_reserve_exact`,
718 /// capacity will be greater than or equal to `self.len() + additional`.
719 /// Does nothing if the capacity is already sufficient.
721 /// Note that the allocator may give the collection more space than it
722 /// requests. Therefore, capacity can not be relied upon to be precisely
723 /// minimal. Prefer [`reserve`] if future insertions are expected.
725 /// [`reserve`]: VecDeque::reserve
729 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
735 /// use std::collections::TryReserveError;
736 /// use std::collections::VecDeque;
738 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
739 /// let mut output = VecDeque::new();
741 /// // Pre-reserve the memory, exiting if we can't
742 /// output.try_reserve_exact(data.len())?;
744 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
745 /// output.extend(data.iter().map(|&val| {
746 /// val * 2 + 5 // very complicated
751 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
753 #[stable(feature = "try_reserve", since = "1.57.0")]
754 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
755 self.try_reserve(additional)
758 /// Tries to reserve capacity for at least `additional` more elements to be inserted
759 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
760 /// frequent reallocations. After calling `try_reserve`, capacity will be
761 /// greater than or equal to `self.len() + additional`. Does nothing if
762 /// capacity is already sufficient.
766 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
772 /// use std::collections::TryReserveError;
773 /// use std::collections::VecDeque;
775 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
776 /// let mut output = VecDeque::new();
778 /// // Pre-reserve the memory, exiting if we can't
779 /// output.try_reserve(data.len())?;
781 /// // Now we know this can't OOM in the middle of our complex work
782 /// output.extend(data.iter().map(|&val| {
783 /// val * 2 + 5 // very complicated
788 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
790 #[stable(feature = "try_reserve", since = "1.57.0")]
791 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
792 let old_cap = self.cap();
793 let used_cap = self.len() + 1;
794 let new_cap = used_cap
795 .checked_add(additional)
796 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
797 .ok_or(TryReserveErrorKind::CapacityOverflow)?;
799 if new_cap > old_cap {
800 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
802 self.handle_capacity_increase(old_cap);
808 /// Shrinks the capacity of the `VecDeque` as much as possible.
810 /// It will drop down as close as possible to the length but the allocator may still inform the
811 /// `VecDeque` that there is space for a few more elements.
816 /// use std::collections::VecDeque;
818 /// let mut buf = VecDeque::with_capacity(15);
819 /// buf.extend(0..4);
820 /// assert_eq!(buf.capacity(), 15);
821 /// buf.shrink_to_fit();
822 /// assert!(buf.capacity() >= 4);
824 #[stable(feature = "deque_extras_15", since = "1.5.0")]
825 pub fn shrink_to_fit(&mut self) {
829 /// Shrinks the capacity of the `VecDeque` with a lower bound.
831 /// The capacity will remain at least as large as both the length
832 /// and the supplied value.
834 /// If the current capacity is less than the lower limit, this is a no-op.
839 /// use std::collections::VecDeque;
841 /// let mut buf = VecDeque::with_capacity(15);
842 /// buf.extend(0..4);
843 /// assert_eq!(buf.capacity(), 15);
844 /// buf.shrink_to(6);
845 /// assert!(buf.capacity() >= 6);
846 /// buf.shrink_to(0);
847 /// assert!(buf.capacity() >= 4);
849 #[stable(feature = "shrink_to", since = "1.56.0")]
850 pub fn shrink_to(&mut self, min_capacity: usize) {
851 let min_capacity = cmp::min(min_capacity, self.capacity());
852 // We don't have to worry about an overflow as neither `self.len()` nor `self.capacity()`
853 // can ever be `usize::MAX`. +1 as the ringbuffer always leaves one space empty.
854 let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
855 .next_power_of_two();
857 if target_cap < self.cap() {
858 // There are three cases of interest:
859 // All elements are out of desired bounds
860 // Elements are contiguous, and head is out of desired bounds
861 // Elements are discontiguous, and tail is out of desired bounds
863 // At all other times, element positions are unaffected.
865 // Indicates that elements at the head should be moved.
866 let head_outside = self.head == 0 || self.head >= target_cap;
867 // Move elements from out of desired bounds (positions after target_cap)
868 if self.tail >= target_cap && head_outside {
870 // [. . . . . . . . o o o o o o o . ]
872 // [o o o o o o o . ]
874 self.copy_nonoverlapping(0, self.tail, self.len());
876 self.head = self.len();
878 } else if self.tail != 0 && self.tail < target_cap && head_outside {
880 // [. . . o o o o o o o . . . . . . ]
882 // [o o . o o o o o ]
883 let len = self.wrap_sub(self.head, target_cap);
885 self.copy_nonoverlapping(0, target_cap, len);
888 debug_assert!(self.head < self.tail);
889 } else if self.tail >= target_cap {
891 // [o o o o o . . . . . . . . . o o ]
893 // [o o o o o . o o ]
894 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
895 let len = self.cap() - self.tail;
896 let new_tail = target_cap - len;
898 self.copy_nonoverlapping(new_tail, self.tail, len);
900 self.tail = new_tail;
901 debug_assert!(self.head < self.tail);
904 self.buf.shrink_to_fit(target_cap);
906 debug_assert!(self.head < self.cap());
907 debug_assert!(self.tail < self.cap());
908 debug_assert!(self.cap().count_ones() == 1);
912 /// Shortens the `VecDeque`, keeping the first `len` elements and dropping
915 /// If `len` is greater than the `VecDeque`'s current length, this has no
921 /// use std::collections::VecDeque;
923 /// let mut buf = VecDeque::new();
924 /// buf.push_back(5);
925 /// buf.push_back(10);
926 /// buf.push_back(15);
927 /// assert_eq!(buf, [5, 10, 15]);
929 /// assert_eq!(buf, [5]);
931 #[stable(feature = "deque_extras", since = "1.16.0")]
932 pub fn truncate(&mut self, len: usize) {
933 /// Runs the destructor for all items in the slice when it gets dropped (normally or
934 /// during unwinding).
935 struct Dropper<'a, T>(&'a mut [T]);
937 impl<'a, T> Drop for Dropper<'a, T> {
940 ptr::drop_in_place(self.0);
947 // * Any slice passed to `drop_in_place` is valid; the second case has
948 // `len <= front.len()` and returning on `len > self.len()` ensures
949 // `begin <= back.len()` in the first case
950 // * The head of the VecDeque is moved before calling `drop_in_place`,
951 // so no value is dropped twice if `drop_in_place` panics
953 if len > self.len() {
956 let num_dropped = self.len() - len;
957 let (front, back) = self.as_mut_slices();
958 if len > front.len() {
959 let begin = len - front.len();
960 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
961 self.head = self.wrap_sub(self.head, num_dropped);
962 ptr::drop_in_place(drop_back);
964 let drop_back = back as *mut _;
965 let drop_front = front.get_unchecked_mut(len..) as *mut _;
966 self.head = self.wrap_sub(self.head, num_dropped);
968 // Make sure the second half is dropped even when a destructor
969 // in the first one panics.
970 let _back_dropper = Dropper(&mut *drop_back);
971 ptr::drop_in_place(drop_front);
976 /// Returns a reference to the underlying allocator.
977 #[unstable(feature = "allocator_api", issue = "32838")]
979 pub fn allocator(&self) -> &A {
983 /// Returns a front-to-back iterator.
988 /// use std::collections::VecDeque;
990 /// let mut buf = VecDeque::new();
991 /// buf.push_back(5);
992 /// buf.push_back(3);
993 /// buf.push_back(4);
994 /// let b: &[_] = &[&5, &3, &4];
995 /// let c: Vec<&i32> = buf.iter().collect();
996 /// assert_eq!(&c[..], b);
998 #[stable(feature = "rust1", since = "1.0.0")]
999 pub fn iter(&self) -> Iter<'_, T> {
1000 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } }
1003 /// Returns a front-to-back iterator that returns mutable references.
1008 /// use std::collections::VecDeque;
1010 /// let mut buf = VecDeque::new();
1011 /// buf.push_back(5);
1012 /// buf.push_back(3);
1013 /// buf.push_back(4);
1014 /// for num in buf.iter_mut() {
1015 /// *num = *num - 2;
1017 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1018 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1022 // SAFETY: The internal `IterMut` safety invariant is established because the
1023 // `ring` we create is a dereferencable slice for lifetime '_.
1024 let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1026 unsafe { IterMut::new(ring, self.tail, self.head, PhantomData) }
1029 /// Returns a pair of slices which contain, in order, the contents of the
1032 /// If [`make_contiguous`] was previously called, all elements of the
1033 /// `VecDeque` will be in the first slice and the second slice will be empty.
1035 /// [`make_contiguous`]: VecDeque::make_contiguous
1040 /// use std::collections::VecDeque;
1042 /// let mut vector = VecDeque::new();
1044 /// vector.push_back(0);
1045 /// vector.push_back(1);
1046 /// vector.push_back(2);
1048 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
1050 /// vector.push_front(10);
1051 /// vector.push_front(9);
1053 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1056 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1057 pub fn as_slices(&self) -> (&[T], &[T]) {
1059 let buf = self.buffer_as_slice();
1060 RingSlices::ring_slices(buf, self.head, self.tail)
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 /// `VecDeque` 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 vector = VecDeque::new();
1079 /// vector.push_back(0);
1080 /// vector.push_back(1);
1082 /// vector.push_front(10);
1083 /// vector.push_front(9);
1085 /// vector.as_mut_slices().0[0] = 42;
1086 /// vector.as_mut_slices().1[0] = 24;
1087 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
1090 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1091 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1093 let head = self.head;
1094 let tail = self.tail;
1095 let buf = self.buffer_as_mut_slice();
1096 RingSlices::ring_slices(buf, head, tail)
1100 /// Returns the number of elements in the `VecDeque`.
1105 /// use std::collections::VecDeque;
1107 /// let mut v = VecDeque::new();
1108 /// assert_eq!(v.len(), 0);
1110 /// assert_eq!(v.len(), 1);
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn len(&self) -> usize {
1114 count(self.tail, self.head, self.cap())
1117 /// Returns `true` if the `VecDeque` is empty.
1122 /// use std::collections::VecDeque;
1124 /// let mut v = VecDeque::new();
1125 /// assert!(v.is_empty());
1126 /// v.push_front(1);
1127 /// assert!(!v.is_empty());
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 pub fn is_empty(&self) -> bool {
1131 self.tail == self.head
1134 fn range_tail_head<R>(&self, range: R) -> (usize, usize)
1136 R: RangeBounds<usize>,
1138 let Range { start, end } = slice::range(range, ..self.len());
1139 let tail = self.wrap_add(self.tail, start);
1140 let head = self.wrap_add(self.tail, end);
1144 /// Creates an iterator that covers the specified range in the `VecDeque`.
1148 /// Panics if the starting point is greater than the end point or if
1149 /// the end point is greater than the length of the vector.
1154 /// use std::collections::VecDeque;
1156 /// let v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1157 /// let range = v.range(2..).copied().collect::<VecDeque<_>>();
1158 /// assert_eq!(range, [3]);
1160 /// // A full range covers all contents
1161 /// let all = v.range(..);
1162 /// assert_eq!(all.len(), 3);
1165 #[stable(feature = "deque_range", since = "1.51.0")]
1166 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1168 R: RangeBounds<usize>,
1170 let (tail, head) = self.range_tail_head(range);
1174 // The shared reference we have in &self is maintained in the '_ of Iter.
1175 ring: unsafe { self.buffer_as_slice() },
1179 /// Creates an iterator that covers the specified mutable range in the `VecDeque`.
1183 /// Panics if the starting point is greater than the end point or if
1184 /// the end point is greater than the length of the vector.
1189 /// use std::collections::VecDeque;
1191 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1192 /// for v in v.range_mut(2..) {
1195 /// assert_eq!(v, vec![1, 2, 6]);
1197 /// // A full range covers all contents
1198 /// for v in v.range_mut(..) {
1201 /// assert_eq!(v, vec![2, 4, 12]);
1204 #[stable(feature = "deque_range", since = "1.51.0")]
1205 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1207 R: RangeBounds<usize>,
1209 let (tail, head) = self.range_tail_head(range);
1211 // SAFETY: The internal `IterMut` safety invariant is established because the
1212 // `ring` we create is a dereferencable slice for lifetime '_.
1213 let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1215 unsafe { IterMut::new(ring, tail, head, PhantomData) }
1218 /// Creates a draining iterator that removes the specified range in the
1219 /// `VecDeque` and yields the removed items.
1221 /// Note 1: The element range is removed even if the iterator is not
1222 /// consumed until the end.
1224 /// Note 2: It is unspecified how many elements are removed from the deque,
1225 /// if the `Drain` value is not dropped, but the borrow it holds expires
1226 /// (e.g., due to `mem::forget`).
1230 /// Panics if the starting point is greater than the end point or if
1231 /// the end point is greater than the length of the vector.
1236 /// use std::collections::VecDeque;
1238 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1239 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
1240 /// assert_eq!(drained, [3]);
1241 /// assert_eq!(v, [1, 2]);
1243 /// // A full range clears all contents
1245 /// assert!(v.is_empty());
1248 #[stable(feature = "drain", since = "1.6.0")]
1249 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1251 R: RangeBounds<usize>,
1255 // When the Drain is first created, the source deque is shortened to
1256 // make sure no uninitialized or moved-from elements are accessible at
1257 // all if the Drain's destructor never gets to run.
1259 // Drain will ptr::read out the values to remove.
1260 // When finished, the remaining data will be copied back to cover the hole,
1261 // and the head/tail values will be restored correctly.
1263 let (drain_tail, drain_head) = self.range_tail_head(range);
1265 // The deque's elements are parted into three segments:
1266 // * self.tail -> drain_tail
1267 // * drain_tail -> drain_head
1268 // * drain_head -> self.head
1270 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1272 // We store drain_tail as self.head, and drain_head and self.head as
1273 // after_tail and after_head respectively on the Drain. This also
1274 // truncates the effective array such that if the Drain is leaked, we
1275 // have forgotten about the potentially moved values after the start of
1279 // [. . . o o x x o o . . .]
1281 let head = self.head;
1283 // "forget" about the values after the start of the drain until after
1284 // the drain is complete and the Drain destructor is run.
1285 self.head = drain_tail;
1287 let deque = NonNull::from(&mut *self);
1291 // Crucially, we only create shared references from `self` here and read from
1292 // it. We do not write to `self` nor reborrow to a mutable reference.
1293 // Hence the raw pointer we created above, for `deque`, remains valid.
1294 ring: unsafe { self.buffer_as_slice() },
1297 unsafe { Drain::new(drain_head, head, iter, deque) }
1300 /// Clears the `VecDeque`, removing all values.
1305 /// use std::collections::VecDeque;
1307 /// let mut v = VecDeque::new();
1310 /// assert!(v.is_empty());
1312 #[stable(feature = "rust1", since = "1.0.0")]
1314 pub fn clear(&mut self) {
1318 /// Returns `true` if the `VecDeque` contains an element equal to the
1324 /// use std::collections::VecDeque;
1326 /// let mut vector: VecDeque<u32> = VecDeque::new();
1328 /// vector.push_back(0);
1329 /// vector.push_back(1);
1331 /// assert_eq!(vector.contains(&1), true);
1332 /// assert_eq!(vector.contains(&10), false);
1334 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1335 pub fn contains(&self, x: &T) -> bool
1339 let (a, b) = self.as_slices();
1340 a.contains(x) || b.contains(x)
1343 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1349 /// use std::collections::VecDeque;
1351 /// let mut d = VecDeque::new();
1352 /// assert_eq!(d.front(), None);
1356 /// assert_eq!(d.front(), Some(&1));
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 pub fn front(&self) -> Option<&T> {
1363 /// Provides a mutable reference to the front element, or `None` if the
1364 /// `VecDeque` is empty.
1369 /// use std::collections::VecDeque;
1371 /// let mut d = VecDeque::new();
1372 /// assert_eq!(d.front_mut(), None);
1376 /// match d.front_mut() {
1377 /// Some(x) => *x = 9,
1380 /// assert_eq!(d.front(), Some(&9));
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 pub fn front_mut(&mut self) -> Option<&mut T> {
1387 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1393 /// use std::collections::VecDeque;
1395 /// let mut d = VecDeque::new();
1396 /// assert_eq!(d.back(), None);
1400 /// assert_eq!(d.back(), Some(&2));
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 pub fn back(&self) -> Option<&T> {
1404 self.get(self.len().wrapping_sub(1))
1407 /// Provides a mutable reference to the back element, or `None` if the
1408 /// `VecDeque` is empty.
1413 /// use std::collections::VecDeque;
1415 /// let mut d = VecDeque::new();
1416 /// assert_eq!(d.back(), None);
1420 /// match d.back_mut() {
1421 /// Some(x) => *x = 9,
1424 /// assert_eq!(d.back(), Some(&9));
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 pub fn back_mut(&mut self) -> Option<&mut T> {
1428 self.get_mut(self.len().wrapping_sub(1))
1431 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1437 /// use std::collections::VecDeque;
1439 /// let mut d = VecDeque::new();
1443 /// assert_eq!(d.pop_front(), Some(1));
1444 /// assert_eq!(d.pop_front(), Some(2));
1445 /// assert_eq!(d.pop_front(), None);
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 pub fn pop_front(&mut self) -> Option<T> {
1449 if self.is_empty() {
1452 let tail = self.tail;
1453 self.tail = self.wrap_add(self.tail, 1);
1454 unsafe { Some(self.buffer_read(tail)) }
1458 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1464 /// use std::collections::VecDeque;
1466 /// let mut buf = VecDeque::new();
1467 /// assert_eq!(buf.pop_back(), None);
1468 /// buf.push_back(1);
1469 /// buf.push_back(3);
1470 /// assert_eq!(buf.pop_back(), Some(3));
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub fn pop_back(&mut self) -> Option<T> {
1474 if self.is_empty() {
1477 self.head = self.wrap_sub(self.head, 1);
1478 let head = self.head;
1479 unsafe { Some(self.buffer_read(head)) }
1483 /// Prepends an element to the `VecDeque`.
1488 /// use std::collections::VecDeque;
1490 /// let mut d = VecDeque::new();
1491 /// d.push_front(1);
1492 /// d.push_front(2);
1493 /// assert_eq!(d.front(), Some(&2));
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 pub fn push_front(&mut self, value: T) {
1501 self.tail = self.wrap_sub(self.tail, 1);
1502 let tail = self.tail;
1504 self.buffer_write(tail, value);
1508 /// Appends an element to the back of the `VecDeque`.
1513 /// use std::collections::VecDeque;
1515 /// let mut buf = VecDeque::new();
1516 /// buf.push_back(1);
1517 /// buf.push_back(3);
1518 /// assert_eq!(3, *buf.back().unwrap());
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 pub fn push_back(&mut self, value: T) {
1526 let head = self.head;
1527 self.head = self.wrap_add(self.head, 1);
1528 unsafe { self.buffer_write(head, value) }
1532 fn is_contiguous(&self) -> bool {
1533 // FIXME: Should we consider `head == 0` to mean
1534 // that `self` is contiguous?
1535 self.tail <= self.head
1538 /// Removes an element from anywhere in the `VecDeque` and returns it,
1539 /// replacing it with the first element.
1541 /// This does not preserve ordering, but is *O*(1).
1543 /// Returns `None` if `index` is out of bounds.
1545 /// Element at index 0 is the front of the queue.
1550 /// use std::collections::VecDeque;
1552 /// let mut buf = VecDeque::new();
1553 /// assert_eq!(buf.swap_remove_front(0), None);
1554 /// buf.push_back(1);
1555 /// buf.push_back(2);
1556 /// buf.push_back(3);
1557 /// assert_eq!(buf, [1, 2, 3]);
1559 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1560 /// assert_eq!(buf, [2, 1]);
1562 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1563 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1564 let length = self.len();
1565 if length > 0 && index < length && index != 0 {
1566 self.swap(index, 0);
1567 } else if index >= length {
1573 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1576 /// This does not preserve ordering, but is *O*(1).
1578 /// Returns `None` if `index` is out of bounds.
1580 /// Element at index 0 is the front of the queue.
1585 /// use std::collections::VecDeque;
1587 /// let mut buf = VecDeque::new();
1588 /// assert_eq!(buf.swap_remove_back(0), None);
1589 /// buf.push_back(1);
1590 /// buf.push_back(2);
1591 /// buf.push_back(3);
1592 /// assert_eq!(buf, [1, 2, 3]);
1594 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1595 /// assert_eq!(buf, [3, 2]);
1597 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1598 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1599 let length = self.len();
1600 if length > 0 && index < length - 1 {
1601 self.swap(index, length - 1);
1602 } else if index >= length {
1608 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1609 /// greater than or equal to `index` towards the back.
1611 /// Element at index 0 is the front of the queue.
1615 /// Panics if `index` is greater than `VecDeque`'s length
1620 /// use std::collections::VecDeque;
1622 /// let mut vec_deque = VecDeque::new();
1623 /// vec_deque.push_back('a');
1624 /// vec_deque.push_back('b');
1625 /// vec_deque.push_back('c');
1626 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1628 /// vec_deque.insert(1, 'd');
1629 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1631 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1632 pub fn insert(&mut self, index: usize, value: T) {
1633 assert!(index <= self.len(), "index out of bounds");
1638 // Move the least number of elements in the ring buffer and insert
1641 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1643 // There are three main cases:
1644 // Elements are contiguous
1645 // - special case when tail is 0
1646 // Elements are discontiguous and the insert is in the tail section
1647 // Elements are discontiguous and the insert is in the head section
1649 // For each of those there are two more cases:
1650 // Insert is closer to tail
1651 // Insert is closer to head
1653 // Key: H - self.head
1655 // o - Valid element
1656 // I - Insertion element
1657 // A - The element that should be after the insertion point
1658 // M - Indicates element was moved
1660 let idx = self.wrap_add(self.tail, index);
1662 let distance_to_tail = index;
1663 let distance_to_head = self.len() - index;
1665 let contiguous = self.is_contiguous();
1667 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1668 (true, true, _) if index == 0 => {
1673 // [A o o o o o o . . . . . . . . .]
1676 // [A o o o o o o o . . . . . I]
1679 self.tail = self.wrap_sub(self.tail, 1);
1681 (true, true, _) => {
1683 // contiguous, insert closer to tail:
1686 // [. . . o o A o o o o . . . . . .]
1689 // [. . o o I A o o o o . . . . . .]
1692 // contiguous, insert closer to tail and tail is 0:
1696 // [o o A o o o o . . . . . . . . .]
1699 // [o I A o o o o o . . . . . . . o]
1702 let new_tail = self.wrap_sub(self.tail, 1);
1704 self.copy(new_tail, self.tail, 1);
1705 // Already moved the tail, so we only copy `index - 1` elements.
1706 self.copy(self.tail, self.tail + 1, index - 1);
1708 self.tail = new_tail;
1711 (true, false, _) => {
1713 // contiguous, insert closer to head:
1716 // [. . . o o o o A o o . . . . . .]
1719 // [. . . o o o o I A o o . . . . .]
1722 self.copy(idx + 1, idx, self.head - idx);
1723 self.head = self.wrap_add(self.head, 1);
1726 (false, true, true) => {
1728 // discontiguous, insert closer to tail, tail section:
1731 // [o o o o o o . . . . . o o A o o]
1734 // [o o o o o o . . . . o o I A o o]
1737 self.copy(self.tail - 1, self.tail, index);
1741 (false, false, true) => {
1743 // discontiguous, insert closer to head, tail section:
1746 // [o o . . . . . . . o o o o o A o]
1749 // [o o o . . . . . . o o o o o I A]
1752 // copy elements up to new head
1753 self.copy(1, 0, self.head);
1755 // copy last element into empty spot at bottom of buffer
1756 self.copy(0, self.cap() - 1, 1);
1758 // move elements from idx to end forward not including ^ element
1759 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1764 (false, true, false) if idx == 0 => {
1766 // discontiguous, insert is closer to tail, head section,
1767 // and is at index zero in the internal buffer:
1770 // [A o o o o o o o o o . . . o o o]
1773 // [A o o o o o o o o o . . o o o I]
1776 // copy elements up to new tail
1777 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1779 // copy last element into empty spot at bottom of buffer
1780 self.copy(self.cap() - 1, 0, 1);
1785 (false, true, false) => {
1787 // discontiguous, insert closer to tail, head section:
1790 // [o o o A o o o o o o . . . o o o]
1793 // [o o I A o o o o o o . . o o o o]
1796 // copy elements up to new tail
1797 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1799 // copy last element into empty spot at bottom of buffer
1800 self.copy(self.cap() - 1, 0, 1);
1802 // move elements from idx-1 to end forward not including ^ element
1803 self.copy(0, 1, idx - 1);
1808 (false, false, false) => {
1810 // discontiguous, insert closer to head, head section:
1813 // [o o o o A o o . . . . . . o o o]
1816 // [o o o o I A o o . . . . . o o o]
1819 self.copy(idx + 1, idx, self.head - idx);
1825 // tail might've been changed so we need to recalculate
1826 let new_idx = self.wrap_add(self.tail, index);
1828 self.buffer_write(new_idx, value);
1832 /// Removes and returns the element at `index` from the `VecDeque`.
1833 /// Whichever end is closer to the removal point will be moved to make
1834 /// room, and all the affected elements will be moved to new positions.
1835 /// Returns `None` if `index` is out of bounds.
1837 /// Element at index 0 is the front of the queue.
1842 /// use std::collections::VecDeque;
1844 /// let mut buf = VecDeque::new();
1845 /// buf.push_back(1);
1846 /// buf.push_back(2);
1847 /// buf.push_back(3);
1848 /// assert_eq!(buf, [1, 2, 3]);
1850 /// assert_eq!(buf.remove(1), Some(2));
1851 /// assert_eq!(buf, [1, 3]);
1853 #[stable(feature = "rust1", since = "1.0.0")]
1854 pub fn remove(&mut self, index: usize) -> Option<T> {
1855 if self.is_empty() || self.len() <= index {
1859 // There are three main cases:
1860 // Elements are contiguous
1861 // Elements are discontiguous and the removal is in the tail section
1862 // Elements are discontiguous and the removal is in the head section
1863 // - special case when elements are technically contiguous,
1864 // but self.head = 0
1866 // For each of those there are two more cases:
1867 // Insert is closer to tail
1868 // Insert is closer to head
1870 // Key: H - self.head
1872 // o - Valid element
1873 // x - Element marked for removal
1874 // R - Indicates element that is being removed
1875 // M - Indicates element was moved
1877 let idx = self.wrap_add(self.tail, index);
1879 let elem = unsafe { Some(self.buffer_read(idx)) };
1881 let distance_to_tail = index;
1882 let distance_to_head = self.len() - index;
1884 let contiguous = self.is_contiguous();
1886 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1887 (true, true, _) => {
1889 // contiguous, remove closer to tail:
1892 // [. . . o o x o o o o . . . . . .]
1895 // [. . . . o o o o o o . . . . . .]
1898 self.copy(self.tail + 1, self.tail, index);
1902 (true, false, _) => {
1904 // contiguous, remove closer to head:
1907 // [. . . o o o o x o o . . . . . .]
1910 // [. . . o o o o o o . . . . . . .]
1913 self.copy(idx, idx + 1, self.head - idx - 1);
1917 (false, true, true) => {
1919 // discontiguous, remove closer to tail, tail section:
1922 // [o o o o o o . . . . . o o x o o]
1925 // [o o o o o o . . . . . . o o o o]
1928 self.copy(self.tail + 1, self.tail, index);
1929 self.tail = self.wrap_add(self.tail, 1);
1932 (false, false, false) => {
1934 // discontiguous, remove closer to head, head section:
1937 // [o o o o x o o . . . . . . o o o]
1940 // [o o o o o o . . . . . . . o o o]
1943 self.copy(idx, idx + 1, self.head - idx - 1);
1947 (false, false, true) => {
1949 // discontiguous, remove closer to head, tail section:
1952 // [o o o . . . . . . o o o o o x o]
1955 // [o o . . . . . . . o o o o o o o]
1958 // or quasi-discontiguous, remove next to head, tail section:
1961 // [. . . . . . . . . o o o o o x o]
1964 // [. . . . . . . . . o o o o o o .]
1967 // draw in elements in the tail section
1968 self.copy(idx, idx + 1, self.cap() - idx - 1);
1970 // Prevents underflow.
1972 // copy first element into empty spot
1973 self.copy(self.cap() - 1, 0, 1);
1975 // move elements in the head section backwards
1976 self.copy(0, 1, self.head - 1);
1979 self.head = self.wrap_sub(self.head, 1);
1982 (false, true, false) => {
1984 // discontiguous, remove closer to tail, head section:
1987 // [o o x o o o o o o o . . . o o o]
1990 // [o o o o o o o o o o . . . . o o]
1993 // draw in elements up to idx
1994 self.copy(1, 0, idx);
1996 // copy last element into empty spot
1997 self.copy(0, self.cap() - 1, 1);
1999 // move elements from tail to end forward, excluding the last one
2000 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
2002 self.tail = self.wrap_add(self.tail, 1);
2010 /// Splits the `VecDeque` into two at the given index.
2012 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2013 /// and the returned `VecDeque` contains elements `[at, len)`.
2015 /// Note that the capacity of `self` does not change.
2017 /// Element at index 0 is the front of the queue.
2021 /// Panics if `at > len`.
2026 /// use std::collections::VecDeque;
2028 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
2029 /// let buf2 = buf.split_off(1);
2030 /// assert_eq!(buf, [1]);
2031 /// assert_eq!(buf2, [2, 3]);
2034 #[must_use = "use `.truncate()` if you don't need the other half"]
2035 #[stable(feature = "split_off", since = "1.4.0")]
2036 pub fn split_off(&mut self, at: usize) -> Self
2040 let len = self.len();
2041 assert!(at <= len, "`at` out of bounds");
2043 let other_len = len - at;
2044 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2047 let (first_half, second_half) = self.as_slices();
2049 let first_len = first_half.len();
2050 let second_len = second_half.len();
2052 // `at` lies in the first half.
2053 let amount_in_first = first_len - at;
2055 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2057 // just take all of the second half.
2058 ptr::copy_nonoverlapping(
2059 second_half.as_ptr(),
2060 other.ptr().add(amount_in_first),
2064 // `at` lies in the second half, need to factor in the elements we skipped
2065 // in the first half.
2066 let offset = at - first_len;
2067 let amount_in_second = second_len - offset;
2068 ptr::copy_nonoverlapping(
2069 second_half.as_ptr().add(offset),
2076 // Cleanup where the ends of the buffers are
2077 self.head = self.wrap_sub(self.head, other_len);
2078 other.head = other.wrap_index(other_len);
2083 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2087 /// Panics if the new number of elements in self overflows a `usize`.
2092 /// use std::collections::VecDeque;
2094 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
2095 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
2096 /// buf.append(&mut buf2);
2097 /// assert_eq!(buf, [1, 2, 3, 4]);
2098 /// assert_eq!(buf2, []);
2101 #[stable(feature = "append", since = "1.4.0")]
2102 pub fn append(&mut self, other: &mut Self) {
2103 self.reserve(other.len());
2105 let (left, right) = other.as_slices();
2106 self.copy_slice(self.head, left);
2107 self.copy_slice(self.wrap_add(self.head, left.len()), right);
2109 // SAFETY: Update pointers after copying to avoid leaving doppelganger
2110 // in case of panics.
2111 self.head = self.wrap_add(self.head, other.len());
2112 // Silently drop values in `other`.
2113 other.tail = other.head;
2116 /// Retains only the elements specified by the predicate.
2118 /// In other words, remove all elements `e` such that `f(&e)` returns false.
2119 /// This method operates in place, visiting each element exactly once in the
2120 /// original order, and preserves the order of the retained elements.
2125 /// use std::collections::VecDeque;
2127 /// let mut buf = VecDeque::new();
2128 /// buf.extend(1..5);
2129 /// buf.retain(|&x| x % 2 == 0);
2130 /// assert_eq!(buf, [2, 4]);
2133 /// Because the elements are visited exactly once in the original order,
2134 /// external state may be used to decide which elements to keep.
2137 /// use std::collections::VecDeque;
2139 /// let mut buf = VecDeque::new();
2140 /// buf.extend(1..6);
2142 /// let keep = [false, true, true, false, true];
2143 /// let mut iter = keep.iter();
2144 /// buf.retain(|_| *iter.next().unwrap());
2145 /// assert_eq!(buf, [2, 3, 5]);
2147 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2148 pub fn retain<F>(&mut self, mut f: F)
2150 F: FnMut(&T) -> bool,
2152 let len = self.len();
2156 // Stage 1: All values are retained.
2165 // Stage 2: Swap retained value into current idx.
2172 self.swap(idx, cur);
2176 // Stage 3: Trancate all values after idx.
2182 // Double the buffer size. This method is inline(never), so we expect it to only
2183 // be called in cold paths.
2184 // This may panic or abort
2186 fn grow(&mut self) {
2187 // Extend or possibly remove this assertion when valid use-cases for growing the
2188 // buffer without it being full emerge
2189 debug_assert!(self.is_full());
2190 let old_cap = self.cap();
2191 self.buf.reserve_exact(old_cap, old_cap);
2192 assert!(self.cap() == old_cap * 2);
2194 self.handle_capacity_increase(old_cap);
2196 debug_assert!(!self.is_full());
2199 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
2200 /// either by removing excess elements from the back or by appending
2201 /// elements generated by calling `generator` to the back.
2206 /// use std::collections::VecDeque;
2208 /// let mut buf = VecDeque::new();
2209 /// buf.push_back(5);
2210 /// buf.push_back(10);
2211 /// buf.push_back(15);
2212 /// assert_eq!(buf, [5, 10, 15]);
2214 /// buf.resize_with(5, Default::default);
2215 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2217 /// buf.resize_with(2, || unreachable!());
2218 /// assert_eq!(buf, [5, 10]);
2220 /// let mut state = 100;
2221 /// buf.resize_with(5, || { state += 1; state });
2222 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2224 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2225 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2226 let len = self.len();
2229 self.extend(repeat_with(generator).take(new_len - len))
2231 self.truncate(new_len);
2235 /// Rearranges the internal storage of this deque so it is one contiguous
2236 /// slice, which is then returned.
2238 /// This method does not allocate and does not change the order of the
2239 /// inserted elements. As it returns a mutable slice, this can be used to
2242 /// Once the internal storage is contiguous, the [`as_slices`] and
2243 /// [`as_mut_slices`] methods will return the entire contents of the
2244 /// `VecDeque` in a single slice.
2246 /// [`as_slices`]: VecDeque::as_slices
2247 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2251 /// Sorting the content of a deque.
2254 /// use std::collections::VecDeque;
2256 /// let mut buf = VecDeque::with_capacity(15);
2258 /// buf.push_back(2);
2259 /// buf.push_back(1);
2260 /// buf.push_front(3);
2262 /// // sorting the deque
2263 /// buf.make_contiguous().sort();
2264 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2266 /// // sorting it in reverse order
2267 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2268 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2271 /// Getting immutable access to the contiguous slice.
2274 /// use std::collections::VecDeque;
2276 /// let mut buf = VecDeque::new();
2278 /// buf.push_back(2);
2279 /// buf.push_back(1);
2280 /// buf.push_front(3);
2282 /// buf.make_contiguous();
2283 /// if let (slice, &[]) = buf.as_slices() {
2284 /// // we can now be sure that `slice` contains all elements of the deque,
2285 /// // while still having immutable access to `buf`.
2286 /// assert_eq!(buf.len(), slice.len());
2287 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2290 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2291 pub fn make_contiguous(&mut self) -> &mut [T] {
2292 if self.is_contiguous() {
2293 let tail = self.tail;
2294 let head = self.head;
2295 return unsafe { RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0 };
2298 let buf = self.buf.ptr();
2299 let cap = self.cap();
2300 let len = self.len();
2302 let free = self.tail - self.head;
2303 let tail_len = cap - self.tail;
2305 if free >= tail_len {
2306 // there is enough free space to copy the tail in one go,
2307 // this means that we first shift the head backwards, and then
2308 // copy the tail to the correct position.
2310 // from: DEFGH....ABC
2313 ptr::copy(buf, buf.add(tail_len), self.head);
2315 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2321 } else if free > self.head {
2322 // FIXME: We currently do not consider ....ABCDEFGH
2323 // to be contiguous because `head` would be `0` in this
2324 // case. While we probably want to change this it
2325 // isn't trivial as a few places expect `is_contiguous`
2326 // to mean that we can just slice using `buf[tail..head]`.
2328 // there is enough free space to copy the head in one go,
2329 // this means that we first shift the tail forwards, and then
2330 // copy the head to the correct position.
2332 // from: FGH....ABCDE
2335 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2337 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2340 self.tail = self.head;
2341 self.head = self.wrap_add(self.tail, len);
2344 // free is smaller than both head and tail,
2345 // this means we have to slowly "swap" the tail and the head.
2347 // from: EFGHI...ABCD or HIJK.ABCDEFG
2348 // to: ABCDEFGHI... or ABCDEFGHIJK.
2349 let mut left_edge: usize = 0;
2350 let mut right_edge: usize = self.tail;
2352 // The general problem looks like this
2353 // GHIJKLM...ABCDEF - before any swaps
2354 // ABCDEFM...GHIJKL - after 1 pass of swaps
2355 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2356 // - then restart the algorithm with a new (smaller) store
2357 // Sometimes the temp store is reached when the right edge is at the end
2358 // of the buffer - this means we've hit the right order with fewer swaps!
2361 // ABCDEF.. - after four only swaps we've finished
2362 while left_edge < len && right_edge != cap {
2363 let mut right_offset = 0;
2364 for i in left_edge..right_edge {
2365 right_offset = (i - left_edge) % (cap - right_edge);
2366 let src: isize = (right_edge + right_offset) as isize;
2367 ptr::swap(buf.add(i), buf.offset(src));
2369 let n_ops = right_edge - left_edge;
2371 right_edge += right_offset + 1;
2379 let tail = self.tail;
2380 let head = self.head;
2381 unsafe { RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0 }
2384 /// Rotates the double-ended queue `mid` places to the left.
2387 /// - Rotates item `mid` into the first position.
2388 /// - Pops the first `mid` items and pushes them to the end.
2389 /// - Rotates `len() - mid` places to the right.
2393 /// If `mid` is greater than `len()`. Note that `mid == len()`
2394 /// does _not_ panic and is a no-op rotation.
2398 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2403 /// use std::collections::VecDeque;
2405 /// let mut buf: VecDeque<_> = (0..10).collect();
2407 /// buf.rotate_left(3);
2408 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2410 /// for i in 1..10 {
2411 /// assert_eq!(i * 3 % 10, buf[0]);
2412 /// buf.rotate_left(3);
2414 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2416 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2417 pub fn rotate_left(&mut self, mid: usize) {
2418 assert!(mid <= self.len());
2419 let k = self.len() - mid;
2421 unsafe { self.rotate_left_inner(mid) }
2423 unsafe { self.rotate_right_inner(k) }
2427 /// Rotates the double-ended queue `k` places to the right.
2430 /// - Rotates the first item into position `k`.
2431 /// - Pops the last `k` items and pushes them to the front.
2432 /// - Rotates `len() - k` places to the left.
2436 /// If `k` is greater than `len()`. Note that `k == len()`
2437 /// does _not_ panic and is a no-op rotation.
2441 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2446 /// use std::collections::VecDeque;
2448 /// let mut buf: VecDeque<_> = (0..10).collect();
2450 /// buf.rotate_right(3);
2451 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2453 /// for i in 1..10 {
2454 /// assert_eq!(0, buf[i * 3 % 10]);
2455 /// buf.rotate_right(3);
2457 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2459 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2460 pub fn rotate_right(&mut self, k: usize) {
2461 assert!(k <= self.len());
2462 let mid = self.len() - k;
2464 unsafe { self.rotate_right_inner(k) }
2466 unsafe { self.rotate_left_inner(mid) }
2470 // SAFETY: the following two methods require that the rotation amount
2471 // be less than half the length of the deque.
2473 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2474 // but than `min` is never more than half the capacity, regardless of x,
2475 // so it's sound to call here because we're calling with something
2476 // less than half the length, which is never above half the capacity.
2478 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2479 debug_assert!(mid * 2 <= self.len());
2481 self.wrap_copy(self.head, self.tail, mid);
2483 self.head = self.wrap_add(self.head, mid);
2484 self.tail = self.wrap_add(self.tail, mid);
2487 unsafe fn rotate_right_inner(&mut self, k: usize) {
2488 debug_assert!(k * 2 <= self.len());
2489 self.head = self.wrap_sub(self.head, k);
2490 self.tail = self.wrap_sub(self.tail, k);
2492 self.wrap_copy(self.tail, self.head, k);
2496 /// Binary searches this sorted `VecDeque` for a given element.
2498 /// If the value is found then [`Result::Ok`] is returned, containing the
2499 /// index of the matching element. If there are multiple matches, then any
2500 /// one of the matches could be returned. If the value is not found then
2501 /// [`Result::Err`] is returned, containing the index where a matching
2502 /// element could be inserted while maintaining sorted order.
2504 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2506 /// [`binary_search_by`]: VecDeque::binary_search_by
2507 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2508 /// [`partition_point`]: VecDeque::partition_point
2512 /// Looks up a series of four elements. The first is found, with a
2513 /// uniquely determined position; the second and third are not
2514 /// found; the fourth could match any position in `[1, 4]`.
2517 /// use std::collections::VecDeque;
2519 /// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2521 /// assert_eq!(deque.binary_search(&13), Ok(9));
2522 /// assert_eq!(deque.binary_search(&4), Err(7));
2523 /// assert_eq!(deque.binary_search(&100), Err(13));
2524 /// let r = deque.binary_search(&1);
2525 /// assert!(matches!(r, Ok(1..=4)));
2528 /// If you want to insert an item to a sorted `VecDeque`, while maintaining
2532 /// use std::collections::VecDeque;
2534 /// let mut deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2536 /// let idx = deque.binary_search(&num).unwrap_or_else(|x| x);
2537 /// deque.insert(idx, num);
2538 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2540 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2542 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2546 self.binary_search_by(|e| e.cmp(x))
2549 /// Binary searches this sorted `VecDeque` with a comparator function.
2551 /// The comparator function should implement an order consistent
2552 /// with the sort order of the underlying `VecDeque`, returning an
2553 /// order code that indicates whether its argument is `Less`,
2554 /// `Equal` or `Greater` than the desired target.
2556 /// If the value is found then [`Result::Ok`] is returned, containing the
2557 /// index of the matching element. If there are multiple matches, then any
2558 /// one of the matches could be returned. If the value is not found then
2559 /// [`Result::Err`] is returned, containing the index where a matching
2560 /// element could be inserted while maintaining sorted order.
2562 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2564 /// [`binary_search`]: VecDeque::binary_search
2565 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2566 /// [`partition_point`]: VecDeque::partition_point
2570 /// Looks up a series of four elements. The first is found, with a
2571 /// uniquely determined position; the second and third are not
2572 /// found; the fourth could match any position in `[1, 4]`.
2575 /// use std::collections::VecDeque;
2577 /// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2579 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2580 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2581 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2582 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2583 /// assert!(matches!(r, Ok(1..=4)));
2585 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2586 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2588 F: FnMut(&'a T) -> Ordering,
2590 let (front, back) = self.as_slices();
2591 let cmp_back = back.first().map(|elem| f(elem));
2593 if let Some(Ordering::Equal) = cmp_back {
2595 } else if let Some(Ordering::Less) = cmp_back {
2596 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2598 front.binary_search_by(f)
2602 /// Binary searches this sorted `VecDeque` with a key extraction function.
2604 /// Assumes that the `VecDeque` is sorted by the key, for instance with
2605 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2607 /// If the value is found then [`Result::Ok`] is returned, containing the
2608 /// index of the matching element. If there are multiple matches, then any
2609 /// one of the matches could be returned. If the value is not found then
2610 /// [`Result::Err`] is returned, containing the index where a matching
2611 /// element could be inserted while maintaining sorted order.
2613 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2615 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2616 /// [`binary_search`]: VecDeque::binary_search
2617 /// [`binary_search_by`]: VecDeque::binary_search_by
2618 /// [`partition_point`]: VecDeque::partition_point
2622 /// Looks up a series of four elements in a slice of pairs sorted by
2623 /// their second elements. The first is found, with a uniquely
2624 /// determined position; the second and third are not found; the
2625 /// fourth could match any position in `[1, 4]`.
2628 /// use std::collections::VecDeque;
2630 /// let deque: VecDeque<_> = vec![(0, 0), (2, 1), (4, 1), (5, 1),
2631 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2632 /// (1, 21), (2, 34), (4, 55)].into();
2634 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2635 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2636 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2637 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2638 /// assert!(matches!(r, Ok(1..=4)));
2640 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2642 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2644 F: FnMut(&'a T) -> B,
2647 self.binary_search_by(|k| f(k).cmp(b))
2650 /// Returns the index of the partition point according to the given predicate
2651 /// (the index of the first element of the second partition).
2653 /// The deque is assumed to be partitioned according to the given predicate.
2654 /// This means that all elements for which the predicate returns true are at the start of the deque
2655 /// and all elements for which the predicate returns false are at the end.
2656 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2657 /// (all odd numbers are at the start, all even at the end).
2659 /// If this deque is not partitioned, the returned result is unspecified and meaningless,
2660 /// as this method performs a kind of binary search.
2662 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2664 /// [`binary_search`]: VecDeque::binary_search
2665 /// [`binary_search_by`]: VecDeque::binary_search_by
2666 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2671 /// use std::collections::VecDeque;
2673 /// let deque: VecDeque<_> = vec![1, 2, 3, 3, 5, 6, 7].into();
2674 /// let i = deque.partition_point(|&x| x < 5);
2676 /// assert_eq!(i, 4);
2677 /// assert!(deque.iter().take(i).all(|&x| x < 5));
2678 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2680 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2681 pub fn partition_point<P>(&self, mut pred: P) -> usize
2683 P: FnMut(&T) -> bool,
2685 let (front, back) = self.as_slices();
2687 if let Some(true) = back.first().map(|v| pred(v)) {
2688 back.partition_point(pred) + front.len()
2690 front.partition_point(pred)
2695 impl<T: Clone, A: Allocator> VecDeque<T, A> {
2696 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2697 /// either by removing excess elements from the back or by appending clones of `value`
2703 /// use std::collections::VecDeque;
2705 /// let mut buf = VecDeque::new();
2706 /// buf.push_back(5);
2707 /// buf.push_back(10);
2708 /// buf.push_back(15);
2709 /// assert_eq!(buf, [5, 10, 15]);
2711 /// buf.resize(2, 0);
2712 /// assert_eq!(buf, [5, 10]);
2714 /// buf.resize(5, 20);
2715 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2717 #[stable(feature = "deque_extras", since = "1.16.0")]
2718 pub fn resize(&mut self, new_len: usize, value: T) {
2719 self.resize_with(new_len, || value.clone());
2723 /// Returns the index in the underlying buffer for a given logical element index.
2725 fn wrap_index(index: usize, size: usize) -> usize {
2726 // size is always a power of 2
2727 debug_assert!(size.is_power_of_two());
2731 /// Calculate the number of elements left to be read in the buffer
2733 fn count(tail: usize, head: usize, size: usize) -> usize {
2734 // size is always a power of 2
2735 (head.wrapping_sub(tail)) & (size - 1)
2738 #[stable(feature = "rust1", since = "1.0.0")]
2739 impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
2740 fn eq(&self, other: &Self) -> bool {
2741 if self.len() != other.len() {
2744 let (sa, sb) = self.as_slices();
2745 let (oa, ob) = other.as_slices();
2746 if sa.len() == oa.len() {
2747 sa == oa && sb == ob
2748 } else if sa.len() < oa.len() {
2749 // Always divisible in three sections, for example:
2750 // self: [a b c|d e f]
2751 // other: [0 1 2 3|4 5]
2752 // front = 3, mid = 1,
2753 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2754 let front = sa.len();
2755 let mid = oa.len() - front;
2757 let (oa_front, oa_mid) = oa.split_at(front);
2758 let (sb_mid, sb_back) = sb.split_at(mid);
2759 debug_assert_eq!(sa.len(), oa_front.len());
2760 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2761 debug_assert_eq!(sb_back.len(), ob.len());
2762 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2764 let front = oa.len();
2765 let mid = sa.len() - front;
2767 let (sa_front, sa_mid) = sa.split_at(front);
2768 let (ob_mid, ob_back) = ob.split_at(mid);
2769 debug_assert_eq!(sa_front.len(), oa.len());
2770 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2771 debug_assert_eq!(sb.len(), ob_back.len());
2772 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2777 #[stable(feature = "rust1", since = "1.0.0")]
2778 impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
2780 __impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2781 __impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2782 __impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2783 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2784 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2785 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2787 #[stable(feature = "rust1", since = "1.0.0")]
2788 impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
2789 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2790 self.iter().partial_cmp(other.iter())
2794 #[stable(feature = "rust1", since = "1.0.0")]
2795 impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
2797 fn cmp(&self, other: &Self) -> Ordering {
2798 self.iter().cmp(other.iter())
2802 #[stable(feature = "rust1", since = "1.0.0")]
2803 impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
2804 fn hash<H: Hasher>(&self, state: &mut H) {
2805 self.len().hash(state);
2806 // It's not possible to use Hash::hash_slice on slices
2807 // returned by as_slices method as their length can vary
2808 // in otherwise identical deques.
2810 // Hasher only guarantees equivalence for the exact same
2811 // set of calls to its methods.
2812 self.iter().for_each(|elem| elem.hash(state));
2816 #[stable(feature = "rust1", since = "1.0.0")]
2817 impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
2821 fn index(&self, index: usize) -> &T {
2822 self.get(index).expect("Out of bounds access")
2826 #[stable(feature = "rust1", since = "1.0.0")]
2827 impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
2829 fn index_mut(&mut self, index: usize) -> &mut T {
2830 self.get_mut(index).expect("Out of bounds access")
2834 #[stable(feature = "rust1", since = "1.0.0")]
2835 impl<T> FromIterator<T> for VecDeque<T> {
2836 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
2837 let iterator = iter.into_iter();
2838 let (lower, _) = iterator.size_hint();
2839 let mut deq = VecDeque::with_capacity(lower);
2840 deq.extend(iterator);
2845 #[stable(feature = "rust1", since = "1.0.0")]
2846 impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
2848 type IntoIter = IntoIter<T, A>;
2850 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2852 fn into_iter(self) -> IntoIter<T, A> {
2857 #[stable(feature = "rust1", since = "1.0.0")]
2858 impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
2860 type IntoIter = Iter<'a, T>;
2862 fn into_iter(self) -> Iter<'a, T> {
2867 #[stable(feature = "rust1", since = "1.0.0")]
2868 impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
2869 type Item = &'a mut T;
2870 type IntoIter = IterMut<'a, T>;
2872 fn into_iter(self) -> IterMut<'a, T> {
2877 #[stable(feature = "rust1", since = "1.0.0")]
2878 impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
2879 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2880 // This function should be the moral equivalent of:
2882 // for item in iter.into_iter() {
2883 // self.push_back(item);
2885 let mut iter = iter.into_iter();
2886 while let Some(element) = iter.next() {
2887 if self.len() == self.capacity() {
2888 let (lower, _) = iter.size_hint();
2889 self.reserve(lower.saturating_add(1));
2892 let head = self.head;
2893 self.head = self.wrap_add(self.head, 1);
2895 self.buffer_write(head, element);
2901 fn extend_one(&mut self, elem: T) {
2902 self.push_back(elem);
2906 fn extend_reserve(&mut self, additional: usize) {
2907 self.reserve(additional);
2911 #[stable(feature = "extend_ref", since = "1.2.0")]
2912 impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
2913 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2914 self.extend(iter.into_iter().cloned());
2918 fn extend_one(&mut self, &elem: &T) {
2919 self.push_back(elem);
2923 fn extend_reserve(&mut self, additional: usize) {
2924 self.reserve(additional);
2928 #[stable(feature = "rust1", since = "1.0.0")]
2929 impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
2930 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2931 f.debug_list().entries(self).finish()
2935 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2936 impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
2937 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2939 /// [`Vec<T>`]: crate::vec::Vec
2940 /// [`VecDeque<T>`]: crate::collections::VecDeque
2942 /// This avoids reallocating where possible, but the conditions for that are
2943 /// strict, and subject to change, and so shouldn't be relied upon unless the
2944 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
2945 fn from(mut other: Vec<T, A>) -> Self {
2946 let len = other.len();
2947 if mem::size_of::<T>() == 0 {
2948 // There's no actual allocation for ZSTs to worry about capacity,
2949 // but `VecDeque` can't handle as much length as `Vec`.
2950 assert!(len < MAXIMUM_ZST_CAPACITY, "capacity overflow");
2952 // We need to resize if the capacity is not a power of two, too small or
2953 // doesn't have at least one free space. We do this while it's still in
2954 // the `Vec` so the items will drop on panic.
2955 let min_cap = cmp::max(MINIMUM_CAPACITY, len) + 1;
2956 let cap = cmp::max(min_cap, other.capacity()).next_power_of_two();
2957 if other.capacity() != cap {
2958 other.reserve_exact(cap - len);
2963 let (other_buf, len, capacity, alloc) = other.into_raw_parts_with_alloc();
2964 let buf = RawVec::from_raw_parts_in(other_buf, capacity, alloc);
2965 VecDeque { tail: 0, head: len, buf }
2970 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2971 impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
2972 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2974 /// [`Vec<T>`]: crate::vec::Vec
2975 /// [`VecDeque<T>`]: crate::collections::VecDeque
2977 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
2978 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2983 /// use std::collections::VecDeque;
2985 /// // This one is *O*(1).
2986 /// let deque: VecDeque<_> = (1..5).collect();
2987 /// let ptr = deque.as_slices().0.as_ptr();
2988 /// let vec = Vec::from(deque);
2989 /// assert_eq!(vec, [1, 2, 3, 4]);
2990 /// assert_eq!(vec.as_ptr(), ptr);
2992 /// // This one needs data rearranging.
2993 /// let mut deque: VecDeque<_> = (1..5).collect();
2994 /// deque.push_front(9);
2995 /// deque.push_front(8);
2996 /// let ptr = deque.as_slices().1.as_ptr();
2997 /// let vec = Vec::from(deque);
2998 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2999 /// assert_eq!(vec.as_ptr(), ptr);
3001 fn from(mut other: VecDeque<T, A>) -> Self {
3002 other.make_contiguous();
3005 let other = ManuallyDrop::new(other);
3006 let buf = other.buf.ptr();
3007 let len = other.len();
3008 let cap = other.cap();
3009 let alloc = ptr::read(other.allocator());
3011 if other.tail != 0 {
3012 ptr::copy(buf.add(other.tail), buf, len);
3014 Vec::from_raw_parts_in(buf, len, cap, alloc)
3019 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
3020 impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
3022 /// use std::collections::VecDeque;
3024 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
3025 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
3026 /// assert_eq!(deq1, deq2);
3028 fn from(arr: [T; N]) -> Self {
3029 let mut deq = VecDeque::with_capacity(N);
3030 let arr = ManuallyDrop::new(arr);
3031 if mem::size_of::<T>() != 0 {
3032 // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
3034 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);