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_n, repeat_with, ByRefSized, FromIterator};
14 use core::mem::{ManuallyDrop, SizedTypeProperties};
15 use core::ops::{Index, IndexMut, Range, RangeBounds};
19 // This is used in a bunch of intra-doc links.
20 // FIXME: For some reason, `#[cfg(doc)]` wasn't sufficient, resulting in
21 // failures in linkchecker even though rustdoc built the docs just fine.
22 #[allow(unused_imports)]
25 use crate::alloc::{Allocator, Global};
26 use crate::collections::TryReserveError;
27 use crate::collections::TryReserveErrorKind;
28 use crate::raw_vec::RawVec;
34 #[stable(feature = "drain", since = "1.6.0")]
35 pub use self::drain::Drain;
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub use self::iter_mut::IterMut;
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub use self::into_iter::IntoIter;
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub use self::iter::Iter;
54 use self::spec_extend::SpecExtend;
58 use self::spec_from_iter::SpecFromIter;
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 // `self[0]`, if it exists, is `buf[head]`.
99 // `head < buf.capacity()`, unless `buf.capacity() == 0` when `head == 0`.
101 // the number of initialized elements, starting from the one at `head` and potentially wrapping around.
102 // if `len == 0`, the exact value of `head` is unimportant.
103 // if `T` is zero-Sized, then `self.len <= usize::MAX`, otherwise `self.len <= isize::MAX as usize`.
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) {
118 self.extend(other.iter().cloned());
122 #[stable(feature = "rust1", since = "1.0.0")]
123 unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
125 /// Runs the destructor for all items in the slice when it gets dropped (normally or
126 /// during unwinding).
127 struct Dropper<'a, T>(&'a mut [T]);
129 impl<'a, T> Drop for Dropper<'a, T> {
132 ptr::drop_in_place(self.0);
137 let (front, back) = self.as_mut_slices();
139 let _back_dropper = Dropper(back);
141 ptr::drop_in_place(front);
143 // RawVec handles deallocation
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl<T> Default for VecDeque<T> {
149 /// Creates an empty deque.
151 fn default() -> VecDeque<T> {
156 impl<T, A: Allocator> VecDeque<T, A> {
157 /// Marginally more convenient
159 fn ptr(&self) -> *mut T {
163 /// Moves an element out of the buffer
165 unsafe fn buffer_read(&mut self, off: usize) -> T {
166 unsafe { ptr::read(self.ptr().add(off)) }
169 /// Writes an element into the buffer, moving it.
171 unsafe fn buffer_write(&mut self, off: usize, value: T) {
173 ptr::write(self.ptr().add(off), value);
177 /// Returns a slice pointer into the buffer.
178 /// `range` must lie inside `0..self.capacity()`.
180 unsafe fn buffer_range(&self, range: Range<usize>) -> *mut [T] {
182 ptr::slice_from_raw_parts_mut(self.ptr().add(range.start), range.end - range.start)
186 /// Returns `true` if the buffer is at full capacity.
188 fn is_full(&self) -> bool {
189 self.len == self.capacity()
192 /// Returns the index in the underlying buffer for a given logical element
195 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
196 wrap_index(idx.wrapping_add(addend), self.capacity())
200 fn to_physical_idx(&self, idx: usize) -> usize {
201 self.wrap_add(self.head, idx)
204 /// Returns the index in the underlying buffer for a given logical element
205 /// index - subtrahend.
207 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
208 wrap_index(idx.wrapping_sub(subtrahend).wrapping_add(self.capacity()), self.capacity())
211 /// Copies a contiguous block of memory len long from src to dst
213 unsafe fn copy(&mut self, src: usize, dst: usize, len: usize) {
215 dst + len <= self.capacity(),
216 "cpy dst={} src={} len={} cap={}",
223 src + len <= self.capacity(),
224 "cpy dst={} src={} len={} cap={}",
231 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
235 /// Copies a contiguous block of memory len long from src to dst
237 unsafe fn copy_nonoverlapping(&mut self, src: usize, dst: usize, len: usize) {
239 dst + len <= self.capacity(),
240 "cno dst={} src={} len={} cap={}",
247 src + len <= self.capacity(),
248 "cno dst={} src={} len={} cap={}",
255 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
259 /// Copies a potentially wrapping block of memory len long from src to dest.
260 /// (abs(dst - src) + len) must be no larger than capacity() (There must be at
261 /// most one continuous overlapping region between src and dest).
262 unsafe fn wrap_copy(&mut self, src: usize, dst: usize, len: usize) {
264 cmp::min(src.abs_diff(dst), self.capacity() - src.abs_diff(dst)) + len
266 "wrc dst={} src={} len={} cap={}",
273 // If T is a ZST, don't do any copying.
274 if T::IS_ZST || src == dst || len == 0 {
278 let dst_after_src = self.wrap_sub(dst, src) < len;
280 let src_pre_wrap_len = self.capacity() - src;
281 let dst_pre_wrap_len = self.capacity() - dst;
282 let src_wraps = src_pre_wrap_len < len;
283 let dst_wraps = dst_pre_wrap_len < len;
285 match (dst_after_src, src_wraps, dst_wraps) {
286 (_, false, false) => {
287 // src doesn't wrap, dst doesn't wrap
290 // 1 [_ _ A A B B C C _]
291 // 2 [_ _ A A A A B B _]
295 self.copy(src, dst, len);
298 (false, false, true) => {
299 // dst before src, src doesn't wrap, dst wraps
302 // 1 [A A B B _ _ _ C C]
303 // 2 [A A B B _ _ _ A A]
304 // 3 [B B B B _ _ _ A A]
308 self.copy(src, dst, dst_pre_wrap_len);
309 self.copy(src + dst_pre_wrap_len, 0, len - dst_pre_wrap_len);
312 (true, false, true) => {
313 // src before dst, src doesn't wrap, dst wraps
316 // 1 [C C _ _ _ A A B B]
317 // 2 [B B _ _ _ A A B B]
318 // 3 [B B _ _ _ A A A A]
322 self.copy(src + dst_pre_wrap_len, 0, len - dst_pre_wrap_len);
323 self.copy(src, dst, dst_pre_wrap_len);
326 (false, true, false) => {
327 // dst before src, src wraps, dst doesn't wrap
330 // 1 [C C _ _ _ A A B B]
331 // 2 [C C _ _ _ B B B B]
332 // 3 [C C _ _ _ B B C C]
336 self.copy(src, dst, src_pre_wrap_len);
337 self.copy(0, dst + src_pre_wrap_len, len - src_pre_wrap_len);
340 (true, true, false) => {
341 // src before dst, src wraps, dst doesn't wrap
344 // 1 [A A B B _ _ _ C C]
345 // 2 [A A A A _ _ _ C C]
346 // 3 [C C A A _ _ _ C C]
350 self.copy(0, dst + src_pre_wrap_len, len - src_pre_wrap_len);
351 self.copy(src, dst, src_pre_wrap_len);
354 (false, true, true) => {
355 // dst before src, src wraps, dst wraps
358 // 1 [A B C D _ E F G H]
359 // 2 [A B C D _ E G H H]
360 // 3 [A B C D _ E G H A]
361 // 4 [B C C D _ E G H A]
364 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
365 let delta = dst_pre_wrap_len - src_pre_wrap_len;
367 self.copy(src, dst, src_pre_wrap_len);
368 self.copy(0, dst + src_pre_wrap_len, delta);
369 self.copy(delta, 0, len - dst_pre_wrap_len);
372 (true, true, true) => {
373 // src before dst, src wraps, dst wraps
376 // 1 [A B C D _ E F G H]
377 // 2 [A A B D _ E F G H]
378 // 3 [H A B D _ E F G H]
379 // 4 [H A B D _ E F F G]
382 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
383 let delta = src_pre_wrap_len - dst_pre_wrap_len;
385 self.copy(0, delta, len - src_pre_wrap_len);
386 self.copy(self.capacity() - delta, 0, delta);
387 self.copy(src, dst, dst_pre_wrap_len);
393 /// Copies all values from `src` to `dst`, wrapping around if needed.
394 /// Assumes capacity is sufficient.
396 unsafe fn copy_slice(&mut self, dst: usize, src: &[T]) {
397 debug_assert!(src.len() <= self.capacity());
398 let head_room = self.capacity() - dst;
399 if src.len() <= head_room {
401 ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst), src.len());
404 let (left, right) = src.split_at(head_room);
406 ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst), left.len());
407 ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
412 /// Writes all values from `iter` to `dst`.
416 /// Assumes no wrapping around happens.
417 /// Assumes capacity is sufficient.
419 unsafe fn write_iter(
422 iter: impl Iterator<Item = T>,
425 iter.enumerate().for_each(|(i, element)| unsafe {
426 self.buffer_write(dst + i, element);
431 /// Writes all values from `iter` to `dst`, wrapping
432 /// at the end of the buffer and returns the number
433 /// of written values.
437 /// Assumes that `iter` yields at most `len` items.
438 /// Assumes capacity is sufficient.
439 unsafe fn write_iter_wrapping(
442 mut iter: impl Iterator<Item = T>,
445 struct Guard<'a, T, A: Allocator> {
446 deque: &'a mut VecDeque<T, A>,
450 impl<'a, T, A: Allocator> Drop for Guard<'a, T, A> {
452 self.deque.len += self.written;
456 let head_room = self.capacity() - dst;
458 let mut guard = Guard { deque: self, written: 0 };
460 if head_room >= len {
461 unsafe { guard.deque.write_iter(dst, iter, &mut guard.written) };
464 guard.deque.write_iter(
466 ByRefSized(&mut iter).take(head_room),
469 guard.deque.write_iter(0, iter, &mut guard.written)
476 /// Frobs the head and tail sections around to handle the fact that we
477 /// just reallocated. Unsafe because it trusts old_capacity.
479 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
480 let new_capacity = self.capacity();
481 debug_assert!(new_capacity >= old_capacity);
483 // Move the shortest contiguous section of the ring buffer
486 // L := last element (`self.to_physical_idx(self.len - 1)`)
489 // [o o o o o o o . ]
491 // A [o o o o o o o . . . . . . . . . ]
493 // [o o o o o o o o ]
495 // B [. . . o o o o o o o . . . . . . ]
497 // [o o o o o o o o ]
499 // C [o o o o o . . . . . . . . . o o ]
501 // can't use is_contiguous() because the capacity is already updated.
502 if self.head <= old_capacity - self.len {
506 let head_len = old_capacity - self.head;
507 let tail_len = self.len - head_len;
508 if head_len > tail_len && new_capacity - old_capacity >= tail_len {
511 self.copy_nonoverlapping(0, old_capacity, tail_len);
515 let new_head = new_capacity - head_len;
517 // can't use copy_nonoverlapping here, because if e.g. head_len = 2
518 // and new_capacity = old_capacity + 1, then the heads overlap.
519 self.copy(self.head, new_head, head_len);
521 self.head = new_head;
524 debug_assert!(self.head < self.capacity() || self.capacity() == 0);
528 impl<T> VecDeque<T> {
529 /// Creates an empty deque.
534 /// use std::collections::VecDeque;
536 /// let deque: VecDeque<u32> = VecDeque::new();
538 // FIXME: This should probably be const
540 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn new() -> VecDeque<T> {
543 VecDeque::new_in(Global)
546 /// Creates an empty deque with space for at least `capacity` elements.
551 /// use std::collections::VecDeque;
553 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
556 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
559 Self::with_capacity_in(capacity, Global)
563 impl<T, A: Allocator> VecDeque<T, A> {
564 /// Creates an empty deque.
569 /// use std::collections::VecDeque;
571 /// let deque: VecDeque<u32> = VecDeque::new();
574 #[unstable(feature = "allocator_api", issue = "32838")]
575 pub const fn new_in(alloc: A) -> VecDeque<T, A> {
576 VecDeque { head: 0, len: 0, buf: RawVec::new_in(alloc) }
579 /// Creates an empty deque with space for at least `capacity` elements.
584 /// use std::collections::VecDeque;
586 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
588 #[unstable(feature = "allocator_api", issue = "32838")]
589 pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
590 VecDeque { head: 0, len: 0, buf: RawVec::with_capacity_in(capacity, alloc) }
593 /// Creates a `VecDeque` from a raw allocation, when the initialized
594 /// part of that allocation forms a *contiguous* subslice thereof.
596 /// For use by `vec::IntoIter::into_vecdeque`
600 /// All the usual requirements on the allocated memory like in
601 /// `Vec::from_raw_parts_in`, but takes a *range* of elements that are
602 /// initialized rather than only supporting `0..len`. Requires that
603 /// `initialized.start` ≤ `initialized.end` ≤ `capacity`.
605 pub(crate) unsafe fn from_contiguous_raw_parts_in(
607 initialized: Range<usize>,
611 debug_assert!(initialized.start <= initialized.end);
612 debug_assert!(initialized.end <= capacity);
614 // SAFETY: Our safety precondition guarantees the range length won't wrap,
615 // and that the allocation is valid for use in `RawVec`.
618 head: initialized.start,
619 len: initialized.end.unchecked_sub(initialized.start),
620 buf: RawVec::from_raw_parts_in(ptr, capacity, alloc),
625 /// Provides a reference to the element at the given index.
627 /// Element at index 0 is the front of the queue.
632 /// use std::collections::VecDeque;
634 /// let mut buf = VecDeque::new();
635 /// buf.push_back(3);
636 /// buf.push_back(4);
637 /// buf.push_back(5);
638 /// assert_eq!(buf.get(1), Some(&4));
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn get(&self, index: usize) -> Option<&T> {
642 if index < self.len {
643 let idx = self.to_physical_idx(index);
644 unsafe { Some(&*self.ptr().add(idx)) }
650 /// Provides a mutable reference to the element at the given index.
652 /// Element at index 0 is the front of the queue.
657 /// use std::collections::VecDeque;
659 /// let mut buf = VecDeque::new();
660 /// buf.push_back(3);
661 /// buf.push_back(4);
662 /// buf.push_back(5);
663 /// if let Some(elem) = buf.get_mut(1) {
667 /// assert_eq!(buf[1], 7);
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
671 if index < self.len {
672 let idx = self.to_physical_idx(index);
673 unsafe { Some(&mut *self.ptr().add(idx)) }
679 /// Swaps elements at indices `i` and `j`.
681 /// `i` and `j` may be equal.
683 /// Element at index 0 is the front of the queue.
687 /// Panics if either index is out of bounds.
692 /// use std::collections::VecDeque;
694 /// let mut buf = VecDeque::new();
695 /// buf.push_back(3);
696 /// buf.push_back(4);
697 /// buf.push_back(5);
698 /// assert_eq!(buf, [3, 4, 5]);
700 /// assert_eq!(buf, [5, 4, 3]);
702 #[stable(feature = "rust1", since = "1.0.0")]
703 pub fn swap(&mut self, i: usize, j: usize) {
704 assert!(i < self.len());
705 assert!(j < self.len());
706 let ri = self.to_physical_idx(i);
707 let rj = self.to_physical_idx(j);
708 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
711 /// Returns the number of elements the deque can hold without
717 /// use std::collections::VecDeque;
719 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
720 /// assert!(buf.capacity() >= 10);
723 #[stable(feature = "rust1", since = "1.0.0")]
724 pub fn capacity(&self) -> usize {
725 if T::IS_ZST { usize::MAX } else { self.buf.capacity() }
728 /// Reserves the minimum capacity for at least `additional` more elements to be inserted in the
729 /// given deque. Does nothing if the capacity is already sufficient.
731 /// Note that the allocator may give the collection more space than it requests. Therefore
732 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
733 /// insertions are expected.
737 /// Panics if the new capacity overflows `usize`.
742 /// use std::collections::VecDeque;
744 /// let mut buf: VecDeque<i32> = [1].into();
745 /// buf.reserve_exact(10);
746 /// assert!(buf.capacity() >= 11);
749 /// [`reserve`]: VecDeque::reserve
750 #[stable(feature = "rust1", since = "1.0.0")]
751 pub fn reserve_exact(&mut self, additional: usize) {
752 let new_cap = self.len.checked_add(additional).expect("capacity overflow");
753 let old_cap = self.capacity();
755 if new_cap > old_cap {
756 self.buf.reserve_exact(self.len, additional);
758 self.handle_capacity_increase(old_cap);
763 /// Reserves capacity for at least `additional` more elements to be inserted in the given
764 /// deque. The collection may reserve more space to speculatively avoid frequent reallocations.
768 /// Panics if the new capacity overflows `usize`.
773 /// use std::collections::VecDeque;
775 /// let mut buf: VecDeque<i32> = [1].into();
777 /// assert!(buf.capacity() >= 11);
779 #[stable(feature = "rust1", since = "1.0.0")]
780 pub fn reserve(&mut self, additional: usize) {
781 let new_cap = self.len.checked_add(additional).expect("capacity overflow");
782 let old_cap = self.capacity();
784 if new_cap > old_cap {
785 // we don't need to reserve_exact(), as the size doesn't have
786 // to be a power of 2.
787 self.buf.reserve(self.len, additional);
789 self.handle_capacity_increase(old_cap);
794 /// Tries to reserve the minimum capacity for at least `additional` more elements to
795 /// be inserted in the given deque. After calling `try_reserve_exact`,
796 /// capacity will be greater than or equal to `self.len() + additional` if
797 /// it returns `Ok(())`. Does nothing if the capacity is already sufficient.
799 /// Note that the allocator may give the collection more space than it
800 /// requests. Therefore, capacity can not be relied upon to be precisely
801 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
803 /// [`try_reserve`]: VecDeque::try_reserve
807 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
813 /// use std::collections::TryReserveError;
814 /// use std::collections::VecDeque;
816 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
817 /// let mut output = VecDeque::new();
819 /// // Pre-reserve the memory, exiting if we can't
820 /// output.try_reserve_exact(data.len())?;
822 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
823 /// output.extend(data.iter().map(|&val| {
824 /// val * 2 + 5 // very complicated
829 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
831 #[stable(feature = "try_reserve", since = "1.57.0")]
832 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
834 self.len.checked_add(additional).ok_or(TryReserveErrorKind::CapacityOverflow)?;
835 let old_cap = self.capacity();
837 if new_cap > old_cap {
838 self.buf.try_reserve_exact(self.len, additional)?;
840 self.handle_capacity_increase(old_cap);
846 /// Tries to reserve capacity for at least `additional` more elements to be inserted
847 /// in the given deque. The collection may reserve more space to speculatively avoid
848 /// frequent reallocations. After calling `try_reserve`, capacity will be
849 /// greater than or equal to `self.len() + additional` if it returns
850 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
851 /// preserves the contents even if an error occurs.
855 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
861 /// use std::collections::TryReserveError;
862 /// use std::collections::VecDeque;
864 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
865 /// let mut output = VecDeque::new();
867 /// // Pre-reserve the memory, exiting if we can't
868 /// output.try_reserve(data.len())?;
870 /// // Now we know this can't OOM in the middle of our complex work
871 /// output.extend(data.iter().map(|&val| {
872 /// val * 2 + 5 // very complicated
877 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
879 #[stable(feature = "try_reserve", since = "1.57.0")]
880 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
882 self.len.checked_add(additional).ok_or(TryReserveErrorKind::CapacityOverflow)?;
883 let old_cap = self.capacity();
885 if new_cap > old_cap {
886 self.buf.try_reserve(self.len, additional)?;
888 self.handle_capacity_increase(old_cap);
894 /// Shrinks the capacity of the deque as much as possible.
896 /// It will drop down as close as possible to the length but the allocator may still inform the
897 /// deque that there is space for a few more elements.
902 /// use std::collections::VecDeque;
904 /// let mut buf = VecDeque::with_capacity(15);
905 /// buf.extend(0..4);
906 /// assert_eq!(buf.capacity(), 15);
907 /// buf.shrink_to_fit();
908 /// assert!(buf.capacity() >= 4);
910 #[stable(feature = "deque_extras_15", since = "1.5.0")]
911 pub fn shrink_to_fit(&mut self) {
915 /// Shrinks the capacity of the deque with a lower bound.
917 /// The capacity will remain at least as large as both the length
918 /// and the supplied value.
920 /// If the current capacity is less than the lower limit, this is a no-op.
925 /// use std::collections::VecDeque;
927 /// let mut buf = VecDeque::with_capacity(15);
928 /// buf.extend(0..4);
929 /// assert_eq!(buf.capacity(), 15);
930 /// buf.shrink_to(6);
931 /// assert!(buf.capacity() >= 6);
932 /// buf.shrink_to(0);
933 /// assert!(buf.capacity() >= 4);
935 #[stable(feature = "shrink_to", since = "1.56.0")]
936 pub fn shrink_to(&mut self, min_capacity: usize) {
937 let target_cap = min_capacity.max(self.len);
940 if T::IS_ZST || self.capacity() <= target_cap {
944 if target_cap < self.capacity() {
945 // There are three cases of interest:
946 // All elements are out of desired bounds
947 // Elements are contiguous, and head is out of desired bounds
948 // Elements are discontiguous, and tail is out of desired bounds
950 // At all other times, element positions are unaffected.
952 // Indicates that elements at the head should be moved.
954 let tail_outside = (target_cap + 1..=self.capacity()).contains(&(self.head + self.len));
955 // Move elements from out of desired bounds (positions after target_cap)
958 } else if self.head >= target_cap && tail_outside {
962 // [. . . . . . . . o o o o o o o . ]
964 // [o o o o o o o . ]
966 // nonoverlapping because self.head >= target_cap >= self.len
967 self.copy_nonoverlapping(self.head, 0, self.len);
970 } else if self.head < target_cap && tail_outside {
974 // [. . . o o o o o o o . . . . . . ]
976 // [o o . o o o o o ]
977 let len = self.head + self.len - target_cap;
979 self.copy_nonoverlapping(target_cap, 0, len);
981 } else if self.head >= target_cap {
985 // [o o o o o . . . . . . . . . o o ]
987 // [o o o o o . o o ]
988 let len = self.capacity() - self.head;
989 let new_head = target_cap - len;
991 // can't use copy_nonoverlapping here for the same reason
992 // as in `handle_capacity_increase()`
993 self.copy(self.head, new_head, len);
995 self.head = new_head;
998 self.buf.shrink_to_fit(target_cap);
1000 debug_assert!(self.head < self.capacity() || self.capacity() == 0);
1001 debug_assert!(self.len <= self.capacity());
1005 /// Shortens the deque, keeping the first `len` elements and dropping
1008 /// If `len` is greater than the deque's current length, this has no
1014 /// use std::collections::VecDeque;
1016 /// let mut buf = VecDeque::new();
1017 /// buf.push_back(5);
1018 /// buf.push_back(10);
1019 /// buf.push_back(15);
1020 /// assert_eq!(buf, [5, 10, 15]);
1021 /// buf.truncate(1);
1022 /// assert_eq!(buf, [5]);
1024 #[stable(feature = "deque_extras", since = "1.16.0")]
1025 pub fn truncate(&mut self, len: usize) {
1026 /// Runs the destructor for all items in the slice when it gets dropped (normally or
1027 /// during unwinding).
1028 struct Dropper<'a, T>(&'a mut [T]);
1030 impl<'a, T> Drop for Dropper<'a, T> {
1031 fn drop(&mut self) {
1033 ptr::drop_in_place(self.0);
1040 // * Any slice passed to `drop_in_place` is valid; the second case has
1041 // `len <= front.len()` and returning on `len > self.len()` ensures
1042 // `begin <= back.len()` in the first case
1043 // * The head of the VecDeque is moved before calling `drop_in_place`,
1044 // so no value is dropped twice if `drop_in_place` panics
1046 if len >= self.len {
1050 let (front, back) = self.as_mut_slices();
1051 if len > front.len() {
1052 let begin = len - front.len();
1053 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
1055 ptr::drop_in_place(drop_back);
1057 let drop_back = back as *mut _;
1058 let drop_front = front.get_unchecked_mut(len..) as *mut _;
1061 // Make sure the second half is dropped even when a destructor
1062 // in the first one panics.
1063 let _back_dropper = Dropper(&mut *drop_back);
1064 ptr::drop_in_place(drop_front);
1069 /// Returns a reference to the underlying allocator.
1070 #[unstable(feature = "allocator_api", issue = "32838")]
1072 pub fn allocator(&self) -> &A {
1073 self.buf.allocator()
1076 /// Returns a front-to-back iterator.
1081 /// use std::collections::VecDeque;
1083 /// let mut buf = VecDeque::new();
1084 /// buf.push_back(5);
1085 /// buf.push_back(3);
1086 /// buf.push_back(4);
1087 /// let b: &[_] = &[&5, &3, &4];
1088 /// let c: Vec<&i32> = buf.iter().collect();
1089 /// assert_eq!(&c[..], b);
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 pub fn iter(&self) -> Iter<'_, T> {
1093 let (a, b) = self.as_slices();
1094 Iter::new(a.iter(), b.iter())
1097 /// Returns a front-to-back iterator that returns mutable references.
1102 /// use std::collections::VecDeque;
1104 /// let mut buf = VecDeque::new();
1105 /// buf.push_back(5);
1106 /// buf.push_back(3);
1107 /// buf.push_back(4);
1108 /// for num in buf.iter_mut() {
1109 /// *num = *num - 2;
1111 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1112 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1116 let (a, b) = self.as_mut_slices();
1117 IterMut::new(a.iter_mut(), b.iter_mut())
1120 /// Returns a pair of slices which contain, in order, the contents of the
1123 /// If [`make_contiguous`] was previously called, all elements of the
1124 /// deque will be in the first slice and the second slice will be empty.
1126 /// [`make_contiguous`]: VecDeque::make_contiguous
1131 /// use std::collections::VecDeque;
1133 /// let mut deque = VecDeque::new();
1135 /// deque.push_back(0);
1136 /// deque.push_back(1);
1137 /// deque.push_back(2);
1139 /// assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..]));
1141 /// deque.push_front(10);
1142 /// deque.push_front(9);
1144 /// assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1147 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1148 pub fn as_slices(&self) -> (&[T], &[T]) {
1149 let (a_range, b_range) = self.slice_ranges(..);
1150 // SAFETY: `slice_ranges` always returns valid ranges into
1151 // the physical buffer.
1152 unsafe { (&*self.buffer_range(a_range), &*self.buffer_range(b_range)) }
1155 /// Returns a pair of slices which contain, in order, the contents of the
1158 /// If [`make_contiguous`] was previously called, all elements of the
1159 /// deque will be in the first slice and the second slice will be empty.
1161 /// [`make_contiguous`]: VecDeque::make_contiguous
1166 /// use std::collections::VecDeque;
1168 /// let mut deque = VecDeque::new();
1170 /// deque.push_back(0);
1171 /// deque.push_back(1);
1173 /// deque.push_front(10);
1174 /// deque.push_front(9);
1176 /// deque.as_mut_slices().0[0] = 42;
1177 /// deque.as_mut_slices().1[0] = 24;
1178 /// assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
1181 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1182 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1183 let (a_range, b_range) = self.slice_ranges(..);
1184 // SAFETY: `slice_ranges` always returns valid ranges into
1185 // the physical buffer.
1186 unsafe { (&mut *self.buffer_range(a_range), &mut *self.buffer_range(b_range)) }
1189 /// Returns the number of elements in the deque.
1194 /// use std::collections::VecDeque;
1196 /// let mut deque = VecDeque::new();
1197 /// assert_eq!(deque.len(), 0);
1198 /// deque.push_back(1);
1199 /// assert_eq!(deque.len(), 1);
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 pub fn len(&self) -> usize {
1206 /// Returns `true` if the deque is empty.
1211 /// use std::collections::VecDeque;
1213 /// let mut deque = VecDeque::new();
1214 /// assert!(deque.is_empty());
1215 /// deque.push_front(1);
1216 /// assert!(!deque.is_empty());
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub fn is_empty(&self) -> bool {
1223 /// Given a range into the logical buffer of the deque, this function
1224 /// return two ranges into the physical buffer that correspond to
1225 /// the given range.
1226 fn slice_ranges<R>(&self, range: R) -> (Range<usize>, Range<usize>)
1228 R: RangeBounds<usize>,
1230 let Range { start, end } = slice::range(range, ..self.len);
1231 let len = end - start;
1236 // `slice::range` guarantees that `start <= end <= self.len`.
1237 // because `len != 0`, we know that `start < end`, so `start < self.len`
1238 // and the indexing is valid.
1239 let wrapped_start = self.to_physical_idx(start);
1241 // this subtraction can never overflow because `wrapped_start` is
1242 // at most `self.capacity()` (and if `self.capacity != 0`, then `wrapped_start` is strictly less
1243 // than `self.capacity`).
1244 let head_len = self.capacity() - wrapped_start;
1246 if head_len >= len {
1247 // we know that `len + wrapped_start <= self.capacity <= usize::MAX`, so this addition can't overflow
1248 (wrapped_start..wrapped_start + len, 0..0)
1250 // can't overflow because of the if condition
1251 let tail_len = len - head_len;
1252 (wrapped_start..self.capacity(), 0..tail_len)
1257 /// Creates an iterator that covers the specified range in the deque.
1261 /// Panics if the starting point is greater than the end point or if
1262 /// the end point is greater than the length of the deque.
1267 /// use std::collections::VecDeque;
1269 /// let deque: VecDeque<_> = [1, 2, 3].into();
1270 /// let range = deque.range(2..).copied().collect::<VecDeque<_>>();
1271 /// assert_eq!(range, [3]);
1273 /// // A full range covers all contents
1274 /// let all = deque.range(..);
1275 /// assert_eq!(all.len(), 3);
1278 #[stable(feature = "deque_range", since = "1.51.0")]
1279 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1281 R: RangeBounds<usize>,
1283 let (a_range, b_range) = self.slice_ranges(range);
1284 // SAFETY: The ranges returned by `slice_ranges`
1285 // are valid ranges into the physical buffer, so
1286 // it's ok to pass them to `buffer_range` and
1287 // dereference the result.
1288 let a = unsafe { &*self.buffer_range(a_range) };
1289 let b = unsafe { &*self.buffer_range(b_range) };
1290 Iter::new(a.iter(), b.iter())
1293 /// Creates an iterator that covers the specified mutable range in the deque.
1297 /// Panics if the starting point is greater than the end point or if
1298 /// the end point is greater than the length of the deque.
1303 /// use std::collections::VecDeque;
1305 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1306 /// for v in deque.range_mut(2..) {
1309 /// assert_eq!(deque, [1, 2, 6]);
1311 /// // A full range covers all contents
1312 /// for v in deque.range_mut(..) {
1315 /// assert_eq!(deque, [2, 4, 12]);
1318 #[stable(feature = "deque_range", since = "1.51.0")]
1319 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1321 R: RangeBounds<usize>,
1323 let (a_range, b_range) = self.slice_ranges(range);
1324 // SAFETY: The ranges returned by `slice_ranges`
1325 // are valid ranges into the physical buffer, so
1326 // it's ok to pass them to `buffer_range` and
1327 // dereference the result.
1328 let a = unsafe { &mut *self.buffer_range(a_range) };
1329 let b = unsafe { &mut *self.buffer_range(b_range) };
1330 IterMut::new(a.iter_mut(), b.iter_mut())
1333 /// Removes the specified range from the deque in bulk, returning all
1334 /// removed elements as an iterator. If the iterator is dropped before
1335 /// being fully consumed, it drops the remaining removed elements.
1337 /// The returned iterator keeps a mutable borrow on the queue to optimize
1338 /// its implementation.
1343 /// Panics if the starting point is greater than the end point or if
1344 /// the end point is greater than the length of the deque.
1348 /// If the returned iterator goes out of scope without being dropped (due to
1349 /// [`mem::forget`], for example), the deque may have lost and leaked
1350 /// elements arbitrarily, including elements outside the range.
1355 /// use std::collections::VecDeque;
1357 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1358 /// let drained = deque.drain(2..).collect::<VecDeque<_>>();
1359 /// assert_eq!(drained, [3]);
1360 /// assert_eq!(deque, [1, 2]);
1362 /// // A full range clears all contents, like `clear()` does
1363 /// deque.drain(..);
1364 /// assert!(deque.is_empty());
1367 #[stable(feature = "drain", since = "1.6.0")]
1368 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1370 R: RangeBounds<usize>,
1374 // When the Drain is first created, the source deque is shortened to
1375 // make sure no uninitialized or moved-from elements are accessible at
1376 // all if the Drain's destructor never gets to run.
1378 // Drain will ptr::read out the values to remove.
1379 // When finished, the remaining data will be copied back to cover the hole,
1380 // and the head/tail values will be restored correctly.
1382 let Range { start, end } = slice::range(range, ..self.len);
1383 let drain_start = start;
1384 let drain_len = end - start;
1386 // The deque's elements are parted into three segments:
1387 // * 0 -> drain_start
1388 // * drain_start -> drain_start+drain_len
1389 // * drain_start+drain_len -> self.len
1391 // H = self.head; T = self.head+self.len; t = drain_start+drain_len; h = drain_head
1393 // We store drain_start as self.len, and drain_len and self.len as
1394 // drain_len and orig_len respectively on the Drain. This also
1395 // truncates the effective array such that if the Drain is leaked, we
1396 // have forgotten about the potentially moved values after the start of
1400 // [. . . o o x x o o . . .]
1402 // "forget" about the values after the start of the drain until after
1403 // the drain is complete and the Drain destructor is run.
1405 unsafe { Drain::new(self, drain_start, drain_len) }
1408 /// Clears the deque, removing all values.
1413 /// use std::collections::VecDeque;
1415 /// let mut deque = VecDeque::new();
1416 /// deque.push_back(1);
1418 /// assert!(deque.is_empty());
1420 #[stable(feature = "rust1", since = "1.0.0")]
1422 pub fn clear(&mut self) {
1424 // Not strictly necessary, but leaves things in a more consistent/predictable state.
1428 /// Returns `true` if the deque contains an element equal to the
1431 /// This operation is *O*(*n*).
1433 /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
1435 /// [`binary_search`]: VecDeque::binary_search
1440 /// use std::collections::VecDeque;
1442 /// let mut deque: VecDeque<u32> = VecDeque::new();
1444 /// deque.push_back(0);
1445 /// deque.push_back(1);
1447 /// assert_eq!(deque.contains(&1), true);
1448 /// assert_eq!(deque.contains(&10), false);
1450 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1451 pub fn contains(&self, x: &T) -> bool
1455 let (a, b) = self.as_slices();
1456 a.contains(x) || b.contains(x)
1459 /// Provides a reference to the front element, or `None` if the deque is
1465 /// use std::collections::VecDeque;
1467 /// let mut d = VecDeque::new();
1468 /// assert_eq!(d.front(), None);
1472 /// assert_eq!(d.front(), Some(&1));
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 pub fn front(&self) -> Option<&T> {
1479 /// Provides a mutable reference to the front element, or `None` if the
1485 /// use std::collections::VecDeque;
1487 /// let mut d = VecDeque::new();
1488 /// assert_eq!(d.front_mut(), None);
1492 /// match d.front_mut() {
1493 /// Some(x) => *x = 9,
1496 /// assert_eq!(d.front(), Some(&9));
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 pub fn front_mut(&mut self) -> Option<&mut T> {
1503 /// Provides a reference to the back element, or `None` if the deque is
1509 /// use std::collections::VecDeque;
1511 /// let mut d = VecDeque::new();
1512 /// assert_eq!(d.back(), None);
1516 /// assert_eq!(d.back(), Some(&2));
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 pub fn back(&self) -> Option<&T> {
1520 self.get(self.len.wrapping_sub(1))
1523 /// Provides a mutable reference to the back element, or `None` if the
1529 /// use std::collections::VecDeque;
1531 /// let mut d = VecDeque::new();
1532 /// assert_eq!(d.back(), None);
1536 /// match d.back_mut() {
1537 /// Some(x) => *x = 9,
1540 /// assert_eq!(d.back(), Some(&9));
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 pub fn back_mut(&mut self) -> Option<&mut T> {
1544 self.get_mut(self.len.wrapping_sub(1))
1547 /// Removes the first element and returns it, or `None` if the deque is
1553 /// use std::collections::VecDeque;
1555 /// let mut d = VecDeque::new();
1559 /// assert_eq!(d.pop_front(), Some(1));
1560 /// assert_eq!(d.pop_front(), Some(2));
1561 /// assert_eq!(d.pop_front(), None);
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 pub fn pop_front(&mut self) -> Option<T> {
1565 if self.is_empty() {
1568 let old_head = self.head;
1569 self.head = self.to_physical_idx(1);
1571 Some(unsafe { self.buffer_read(old_head) })
1575 /// Removes the last element from the deque and returns it, or `None` if
1581 /// use std::collections::VecDeque;
1583 /// let mut buf = VecDeque::new();
1584 /// assert_eq!(buf.pop_back(), None);
1585 /// buf.push_back(1);
1586 /// buf.push_back(3);
1587 /// assert_eq!(buf.pop_back(), Some(3));
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 pub fn pop_back(&mut self) -> Option<T> {
1591 if self.is_empty() {
1595 Some(unsafe { self.buffer_read(self.to_physical_idx(self.len)) })
1599 /// Prepends an element to the deque.
1604 /// use std::collections::VecDeque;
1606 /// let mut d = VecDeque::new();
1607 /// d.push_front(1);
1608 /// d.push_front(2);
1609 /// assert_eq!(d.front(), Some(&2));
1611 #[stable(feature = "rust1", since = "1.0.0")]
1612 pub fn push_front(&mut self, value: T) {
1617 self.head = self.wrap_sub(self.head, 1);
1621 self.buffer_write(self.head, value);
1625 /// Appends an element to the back of the deque.
1630 /// use std::collections::VecDeque;
1632 /// let mut buf = VecDeque::new();
1633 /// buf.push_back(1);
1634 /// buf.push_back(3);
1635 /// assert_eq!(3, *buf.back().unwrap());
1637 #[stable(feature = "rust1", since = "1.0.0")]
1638 pub fn push_back(&mut self, value: T) {
1643 unsafe { self.buffer_write(self.to_physical_idx(self.len), value) }
1648 fn is_contiguous(&self) -> bool {
1649 // Do the calculation like this to avoid overflowing if len + head > usize::MAX
1650 self.head <= self.capacity() - self.len
1653 /// Removes an element from anywhere in the deque and returns it,
1654 /// replacing it with the first element.
1656 /// This does not preserve ordering, but is *O*(1).
1658 /// Returns `None` if `index` is out of bounds.
1660 /// Element at index 0 is the front of the queue.
1665 /// use std::collections::VecDeque;
1667 /// let mut buf = VecDeque::new();
1668 /// assert_eq!(buf.swap_remove_front(0), None);
1669 /// buf.push_back(1);
1670 /// buf.push_back(2);
1671 /// buf.push_back(3);
1672 /// assert_eq!(buf, [1, 2, 3]);
1674 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1675 /// assert_eq!(buf, [2, 1]);
1677 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1678 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1679 let length = self.len;
1680 if index < length && index != 0 {
1681 self.swap(index, 0);
1682 } else if index >= length {
1688 /// Removes an element from anywhere in the deque and returns it,
1689 /// replacing it with the last element.
1691 /// This does not preserve ordering, but is *O*(1).
1693 /// Returns `None` if `index` is out of bounds.
1695 /// Element at index 0 is the front of the queue.
1700 /// use std::collections::VecDeque;
1702 /// let mut buf = VecDeque::new();
1703 /// assert_eq!(buf.swap_remove_back(0), None);
1704 /// buf.push_back(1);
1705 /// buf.push_back(2);
1706 /// buf.push_back(3);
1707 /// assert_eq!(buf, [1, 2, 3]);
1709 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1710 /// assert_eq!(buf, [3, 2]);
1712 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1713 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1714 let length = self.len;
1715 if length > 0 && index < length - 1 {
1716 self.swap(index, length - 1);
1717 } else if index >= length {
1723 /// Inserts an element at `index` within the deque, shifting all elements
1724 /// with indices greater than or equal to `index` towards the back.
1726 /// Element at index 0 is the front of the queue.
1730 /// Panics if `index` is greater than deque's length
1735 /// use std::collections::VecDeque;
1737 /// let mut vec_deque = VecDeque::new();
1738 /// vec_deque.push_back('a');
1739 /// vec_deque.push_back('b');
1740 /// vec_deque.push_back('c');
1741 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1743 /// vec_deque.insert(1, 'd');
1744 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1746 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1747 pub fn insert(&mut self, index: usize, value: T) {
1748 assert!(index <= self.len(), "index out of bounds");
1753 let k = self.len - index;
1755 // `index + 1` can't overflow, because if index was usize::MAX, then either the
1756 // assert would've failed, or the deque would've tried to grow past usize::MAX
1759 // see `remove()` for explanation why this wrap_copy() call is safe.
1760 self.wrap_copy(self.to_physical_idx(index), self.to_physical_idx(index + 1), k);
1761 self.buffer_write(self.to_physical_idx(index), value);
1765 let old_head = self.head;
1766 self.head = self.wrap_sub(self.head, 1);
1768 self.wrap_copy(old_head, self.head, index);
1769 self.buffer_write(self.to_physical_idx(index), value);
1775 /// Removes and returns the element at `index` from the deque.
1776 /// Whichever end is closer to the removal point will be moved to make
1777 /// room, and all the affected elements will be moved to new positions.
1778 /// Returns `None` if `index` is out of bounds.
1780 /// Element at index 0 is the front of the queue.
1785 /// use std::collections::VecDeque;
1787 /// let mut buf = VecDeque::new();
1788 /// buf.push_back(1);
1789 /// buf.push_back(2);
1790 /// buf.push_back(3);
1791 /// assert_eq!(buf, [1, 2, 3]);
1793 /// assert_eq!(buf.remove(1), Some(2));
1794 /// assert_eq!(buf, [1, 3]);
1796 #[stable(feature = "rust1", since = "1.0.0")]
1797 pub fn remove(&mut self, index: usize) -> Option<T> {
1798 if self.len <= index {
1802 let wrapped_idx = self.to_physical_idx(index);
1804 let elem = unsafe { Some(self.buffer_read(wrapped_idx)) };
1806 let k = self.len - index - 1;
1807 // safety: due to the nature of the if-condition, whichever wrap_copy gets called,
1808 // its length argument will be at most `self.len / 2`, so there can't be more than
1809 // one overlapping area.
1811 unsafe { self.wrap_copy(self.wrap_add(wrapped_idx, 1), wrapped_idx, k) };
1814 let old_head = self.head;
1815 self.head = self.to_physical_idx(1);
1816 unsafe { self.wrap_copy(old_head, self.head, index) };
1823 /// Splits the deque into two at the given index.
1825 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1826 /// and the returned deque contains elements `[at, len)`.
1828 /// Note that the capacity of `self` does not change.
1830 /// Element at index 0 is the front of the queue.
1834 /// Panics if `at > len`.
1839 /// use std::collections::VecDeque;
1841 /// let mut buf: VecDeque<_> = [1, 2, 3].into();
1842 /// let buf2 = buf.split_off(1);
1843 /// assert_eq!(buf, [1]);
1844 /// assert_eq!(buf2, [2, 3]);
1847 #[must_use = "use `.truncate()` if you don't need the other half"]
1848 #[stable(feature = "split_off", since = "1.4.0")]
1849 pub fn split_off(&mut self, at: usize) -> Self
1854 assert!(at <= len, "`at` out of bounds");
1856 let other_len = len - at;
1857 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
1860 let (first_half, second_half) = self.as_slices();
1862 let first_len = first_half.len();
1863 let second_len = second_half.len();
1865 // `at` lies in the first half.
1866 let amount_in_first = first_len - at;
1868 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
1870 // just take all of the second half.
1871 ptr::copy_nonoverlapping(
1872 second_half.as_ptr(),
1873 other.ptr().add(amount_in_first),
1877 // `at` lies in the second half, need to factor in the elements we skipped
1878 // in the first half.
1879 let offset = at - first_len;
1880 let amount_in_second = second_len - offset;
1881 ptr::copy_nonoverlapping(
1882 second_half.as_ptr().add(offset),
1889 // Cleanup where the ends of the buffers are
1891 other.len = other_len;
1896 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1900 /// Panics if the new number of elements in self overflows a `usize`.
1905 /// use std::collections::VecDeque;
1907 /// let mut buf: VecDeque<_> = [1, 2].into();
1908 /// let mut buf2: VecDeque<_> = [3, 4].into();
1909 /// buf.append(&mut buf2);
1910 /// assert_eq!(buf, [1, 2, 3, 4]);
1911 /// assert_eq!(buf2, []);
1914 #[stable(feature = "append", since = "1.4.0")]
1915 pub fn append(&mut self, other: &mut Self) {
1917 self.len += other.len;
1923 self.reserve(other.len);
1925 let (left, right) = other.as_slices();
1926 self.copy_slice(self.to_physical_idx(self.len), left);
1927 // no overflow, because self.capacity() >= old_cap + left.len() >= self.len + left.len()
1928 self.copy_slice(self.to_physical_idx(self.len + left.len()), right);
1930 // SAFETY: Update pointers after copying to avoid leaving doppelganger
1931 // in case of panics.
1932 self.len += other.len;
1933 // Now that we own its values, forget everything in `other`.
1938 /// Retains only the elements specified by the predicate.
1940 /// In other words, remove all elements `e` for which `f(&e)` returns false.
1941 /// This method operates in place, visiting each element exactly once in the
1942 /// original order, and preserves the order of the retained elements.
1947 /// use std::collections::VecDeque;
1949 /// let mut buf = VecDeque::new();
1950 /// buf.extend(1..5);
1951 /// buf.retain(|&x| x % 2 == 0);
1952 /// assert_eq!(buf, [2, 4]);
1955 /// Because the elements are visited exactly once in the original order,
1956 /// external state may be used to decide which elements to keep.
1959 /// use std::collections::VecDeque;
1961 /// let mut buf = VecDeque::new();
1962 /// buf.extend(1..6);
1964 /// let keep = [false, true, true, false, true];
1965 /// let mut iter = keep.iter();
1966 /// buf.retain(|_| *iter.next().unwrap());
1967 /// assert_eq!(buf, [2, 3, 5]);
1969 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1970 pub fn retain<F>(&mut self, mut f: F)
1972 F: FnMut(&T) -> bool,
1974 self.retain_mut(|elem| f(elem));
1977 /// Retains only the elements specified by the predicate.
1979 /// In other words, remove all elements `e` for which `f(&e)` returns false.
1980 /// This method operates in place, visiting each element exactly once in the
1981 /// original order, and preserves the order of the retained elements.
1986 /// use std::collections::VecDeque;
1988 /// let mut buf = VecDeque::new();
1989 /// buf.extend(1..5);
1990 /// buf.retain_mut(|x| if *x % 2 == 0 {
1996 /// assert_eq!(buf, [3, 5]);
1998 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
1999 pub fn retain_mut<F>(&mut self, mut f: F)
2001 F: FnMut(&mut T) -> bool,
2007 // Stage 1: All values are retained.
2009 if !f(&mut self[cur]) {
2016 // Stage 2: Swap retained value into current idx.
2018 if !f(&mut self[cur]) {
2023 self.swap(idx, cur);
2027 // Stage 3: Truncate all values after idx.
2033 // Double the buffer size. This method is inline(never), so we expect it to only
2034 // be called in cold paths.
2035 // This may panic or abort
2037 fn grow(&mut self) {
2038 // Extend or possibly remove this assertion when valid use-cases for growing the
2039 // buffer without it being full emerge
2040 debug_assert!(self.is_full());
2041 let old_cap = self.capacity();
2042 self.buf.reserve_for_push(old_cap);
2044 self.handle_capacity_increase(old_cap);
2046 debug_assert!(!self.is_full());
2049 /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2050 /// either by removing excess elements from the back or by appending
2051 /// elements generated by calling `generator` to the back.
2056 /// use std::collections::VecDeque;
2058 /// let mut buf = VecDeque::new();
2059 /// buf.push_back(5);
2060 /// buf.push_back(10);
2061 /// buf.push_back(15);
2062 /// assert_eq!(buf, [5, 10, 15]);
2064 /// buf.resize_with(5, Default::default);
2065 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2067 /// buf.resize_with(2, || unreachable!());
2068 /// assert_eq!(buf, [5, 10]);
2070 /// let mut state = 100;
2071 /// buf.resize_with(5, || { state += 1; state });
2072 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2074 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2075 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2079 self.extend(repeat_with(generator).take(new_len - len))
2081 self.truncate(new_len);
2085 /// Rearranges the internal storage of this deque so it is one contiguous
2086 /// slice, which is then returned.
2088 /// This method does not allocate and does not change the order of the
2089 /// inserted elements. As it returns a mutable slice, this can be used to
2092 /// Once the internal storage is contiguous, the [`as_slices`] and
2093 /// [`as_mut_slices`] methods will return the entire contents of the
2094 /// deque in a single slice.
2096 /// [`as_slices`]: VecDeque::as_slices
2097 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2101 /// Sorting the content of a deque.
2104 /// use std::collections::VecDeque;
2106 /// let mut buf = VecDeque::with_capacity(15);
2108 /// buf.push_back(2);
2109 /// buf.push_back(1);
2110 /// buf.push_front(3);
2112 /// // sorting the deque
2113 /// buf.make_contiguous().sort();
2114 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2116 /// // sorting it in reverse order
2117 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2118 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2121 /// Getting immutable access to the contiguous slice.
2124 /// use std::collections::VecDeque;
2126 /// let mut buf = VecDeque::new();
2128 /// buf.push_back(2);
2129 /// buf.push_back(1);
2130 /// buf.push_front(3);
2132 /// buf.make_contiguous();
2133 /// if let (slice, &[]) = buf.as_slices() {
2134 /// // we can now be sure that `slice` contains all elements of the deque,
2135 /// // while still having immutable access to `buf`.
2136 /// assert_eq!(buf.len(), slice.len());
2137 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2140 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2141 pub fn make_contiguous(&mut self) -> &mut [T] {
2146 if self.is_contiguous() {
2147 unsafe { return slice::from_raw_parts_mut(self.ptr().add(self.head), self.len) }
2150 let &mut Self { head, len, .. } = self;
2151 let ptr = self.ptr();
2152 let cap = self.capacity();
2154 let free = cap - len;
2155 let head_len = cap - head;
2156 let tail = len - head_len;
2157 let tail_len = tail;
2159 if free >= head_len {
2160 // there is enough free space to copy the head in one go,
2161 // this means that we first shift the tail backwards, and then
2162 // copy the head to the correct position.
2164 // from: DEFGH....ABC
2167 self.copy(0, head_len, tail_len);
2169 self.copy_nonoverlapping(head, 0, head_len);
2174 } else if free >= tail_len {
2175 // there is enough free space to copy the tail in one go,
2176 // this means that we first shift the head forwards, and then
2177 // copy the tail to the correct position.
2179 // from: FGH....ABCDE
2182 self.copy(head, tail, head_len);
2184 self.copy_nonoverlapping(0, tail + head_len, tail_len);
2190 // `free` is smaller than both `head_len` and `tail_len`.
2191 // the general algorithm for this first moves the slices
2192 // right next to each other and then uses `slice::rotate`
2193 // to rotate them into place:
2195 // initially: HIJK..ABCDEFG
2196 // step 1: ..HIJKABCDEFG
2197 // step 2: ..ABCDEFGHIJK
2201 // initially: FGHIJK..ABCDE
2202 // step 1: FGHIJKABCDE..
2203 // step 2: ABCDEFGHIJK..
2205 // pick the shorter of the 2 slices to reduce the amount
2206 // of memory that needs to be moved around.
2207 if head_len > tail_len {
2208 // tail is shorter, so:
2209 // 1. copy tail forwards
2210 // 2. rotate used part of the buffer
2211 // 3. update head to point to the new beginning (which is just `free`)
2214 // if there is no free space in the buffer, then the slices are already
2215 // right next to each other and we don't need to move any memory.
2217 // because we only move the tail forward as much as there's free space
2218 // behind it, we don't overwrite any elements of the head slice, and
2219 // the slices end up right next to each other.
2220 self.copy(0, free, tail_len);
2223 // We just copied the tail right next to the head slice,
2224 // so all of the elements in the range are initialized
2225 let slice = &mut *self.buffer_range(free..self.capacity());
2227 // because the deque wasn't contiguous, we know that `tail_len < self.len == slice.len()`,
2228 // so this will never panic.
2229 slice.rotate_left(tail_len);
2231 // the used part of the buffer now is `free..self.capacity()`, so set
2232 // `head` to the beginning of that range.
2236 // head is shorter so:
2237 // 1. copy head backwards
2238 // 2. rotate used part of the buffer
2239 // 3. update head to point to the new beginning (which is the beginning of the buffer)
2242 // if there is no free space in the buffer, then the slices are already
2243 // right next to each other and we don't need to move any memory.
2245 // copy the head slice to lie right behind the tail slice.
2246 self.copy(self.head, tail_len, head_len);
2249 // because we copied the head slice so that both slices lie right
2250 // next to each other, all the elements in the range are initialized.
2251 let slice = &mut *self.buffer_range(0..self.len);
2253 // because the deque wasn't contiguous, we know that `head_len < self.len == slice.len()`
2254 // so this will never panic.
2255 slice.rotate_right(head_len);
2257 // the used part of the buffer now is `0..self.len`, so set
2258 // `head` to the beginning of that range.
2264 unsafe { slice::from_raw_parts_mut(ptr.add(self.head), self.len) }
2267 /// Rotates the double-ended queue `mid` places to the left.
2270 /// - Rotates item `mid` into the first position.
2271 /// - Pops the first `mid` items and pushes them to the end.
2272 /// - Rotates `len() - mid` places to the right.
2276 /// If `mid` is greater than `len()`. Note that `mid == len()`
2277 /// does _not_ panic and is a no-op rotation.
2281 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2286 /// use std::collections::VecDeque;
2288 /// let mut buf: VecDeque<_> = (0..10).collect();
2290 /// buf.rotate_left(3);
2291 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2293 /// for i in 1..10 {
2294 /// assert_eq!(i * 3 % 10, buf[0]);
2295 /// buf.rotate_left(3);
2297 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2299 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2300 pub fn rotate_left(&mut self, mid: usize) {
2301 assert!(mid <= self.len());
2302 let k = self.len - mid;
2304 unsafe { self.rotate_left_inner(mid) }
2306 unsafe { self.rotate_right_inner(k) }
2310 /// Rotates the double-ended queue `k` places to the right.
2313 /// - Rotates the first item into position `k`.
2314 /// - Pops the last `k` items and pushes them to the front.
2315 /// - Rotates `len() - k` places to the left.
2319 /// If `k` is greater than `len()`. Note that `k == len()`
2320 /// does _not_ panic and is a no-op rotation.
2324 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2329 /// use std::collections::VecDeque;
2331 /// let mut buf: VecDeque<_> = (0..10).collect();
2333 /// buf.rotate_right(3);
2334 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2336 /// for i in 1..10 {
2337 /// assert_eq!(0, buf[i * 3 % 10]);
2338 /// buf.rotate_right(3);
2340 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2342 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2343 pub fn rotate_right(&mut self, k: usize) {
2344 assert!(k <= self.len());
2345 let mid = self.len - k;
2347 unsafe { self.rotate_right_inner(k) }
2349 unsafe { self.rotate_left_inner(mid) }
2353 // SAFETY: the following two methods require that the rotation amount
2354 // be less than half the length of the deque.
2356 // `wrap_copy` requires that `min(x, capacity() - x) + copy_len <= capacity()`,
2357 // but then `min` is never more than half the capacity, regardless of x,
2358 // so it's sound to call here because we're calling with something
2359 // less than half the length, which is never above half the capacity.
2361 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2362 debug_assert!(mid * 2 <= self.len());
2364 self.wrap_copy(self.head, self.to_physical_idx(self.len), mid);
2366 self.head = self.to_physical_idx(mid);
2369 unsafe fn rotate_right_inner(&mut self, k: usize) {
2370 debug_assert!(k * 2 <= self.len());
2371 self.head = self.wrap_sub(self.head, k);
2373 self.wrap_copy(self.to_physical_idx(self.len), self.head, k);
2377 /// Binary searches this `VecDeque` for a given element.
2378 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2380 /// If the value is found then [`Result::Ok`] is returned, containing the
2381 /// index of the matching element. If there are multiple matches, then any
2382 /// one of the matches could be returned. If the value is not found then
2383 /// [`Result::Err`] is returned, containing the index where a matching
2384 /// element could be inserted while maintaining sorted order.
2386 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2388 /// [`contains`]: VecDeque::contains
2389 /// [`binary_search_by`]: VecDeque::binary_search_by
2390 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2391 /// [`partition_point`]: VecDeque::partition_point
2395 /// Looks up a series of four elements. The first is found, with a
2396 /// uniquely determined position; the second and third are not
2397 /// found; the fourth could match any position in `[1, 4]`.
2400 /// use std::collections::VecDeque;
2402 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2404 /// assert_eq!(deque.binary_search(&13), Ok(9));
2405 /// assert_eq!(deque.binary_search(&4), Err(7));
2406 /// assert_eq!(deque.binary_search(&100), Err(13));
2407 /// let r = deque.binary_search(&1);
2408 /// assert!(matches!(r, Ok(1..=4)));
2411 /// If you want to insert an item to a sorted deque, while maintaining
2412 /// sort order, consider using [`partition_point`]:
2415 /// use std::collections::VecDeque;
2417 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2419 /// let idx = deque.partition_point(|&x| x < num);
2420 /// // The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
2421 /// deque.insert(idx, num);
2422 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2424 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2426 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2430 self.binary_search_by(|e| e.cmp(x))
2433 /// Binary searches this `VecDeque` with a comparator function.
2434 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2436 /// The comparator function should implement an order consistent
2437 /// with the sort order of the deque, returning an order code that
2438 /// indicates whether its argument is `Less`, `Equal` or `Greater`
2439 /// than the desired target.
2441 /// If the value is found then [`Result::Ok`] is returned, containing the
2442 /// index of the matching element. If there are multiple matches, then any
2443 /// one of the matches could be returned. If the value is not found then
2444 /// [`Result::Err`] is returned, containing the index where a matching
2445 /// element could be inserted while maintaining sorted order.
2447 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2449 /// [`contains`]: VecDeque::contains
2450 /// [`binary_search`]: VecDeque::binary_search
2451 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2452 /// [`partition_point`]: VecDeque::partition_point
2456 /// Looks up a series of four elements. The first is found, with a
2457 /// uniquely determined position; the second and third are not
2458 /// found; the fourth could match any position in `[1, 4]`.
2461 /// use std::collections::VecDeque;
2463 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2465 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2466 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2467 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2468 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2469 /// assert!(matches!(r, Ok(1..=4)));
2471 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2472 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2474 F: FnMut(&'a T) -> Ordering,
2476 let (front, back) = self.as_slices();
2477 let cmp_back = back.first().map(|elem| f(elem));
2479 if let Some(Ordering::Equal) = cmp_back {
2481 } else if let Some(Ordering::Less) = cmp_back {
2482 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2484 front.binary_search_by(f)
2488 /// Binary searches this `VecDeque` with a key extraction function.
2489 /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2491 /// Assumes that the deque is sorted by the key, for instance with
2492 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2494 /// If the value is found then [`Result::Ok`] is returned, containing the
2495 /// index of the matching element. If there are multiple matches, then any
2496 /// one of the matches could be returned. If the value is not found then
2497 /// [`Result::Err`] is returned, containing the index where a matching
2498 /// element could be inserted while maintaining sorted order.
2500 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2502 /// [`contains`]: VecDeque::contains
2503 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2504 /// [`binary_search`]: VecDeque::binary_search
2505 /// [`binary_search_by`]: VecDeque::binary_search_by
2506 /// [`partition_point`]: VecDeque::partition_point
2510 /// Looks up a series of four elements in a slice of pairs sorted by
2511 /// their second elements. The first is found, with a uniquely
2512 /// determined position; the second and third are not found; the
2513 /// fourth could match any position in `[1, 4]`.
2516 /// use std::collections::VecDeque;
2518 /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
2519 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2520 /// (1, 21), (2, 34), (4, 55)].into();
2522 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2523 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2524 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2525 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2526 /// assert!(matches!(r, Ok(1..=4)));
2528 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2530 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2532 F: FnMut(&'a T) -> B,
2535 self.binary_search_by(|k| f(k).cmp(b))
2538 /// Returns the index of the partition point according to the given predicate
2539 /// (the index of the first element of the second partition).
2541 /// The deque is assumed to be partitioned according to the given predicate.
2542 /// This means that all elements for which the predicate returns true are at the start of the deque
2543 /// and all elements for which the predicate returns false are at the end.
2544 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2545 /// (all odd numbers are at the start, all even at the end).
2547 /// If the deque is not partitioned, the returned result is unspecified and meaningless,
2548 /// as this method performs a kind of binary search.
2550 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2552 /// [`binary_search`]: VecDeque::binary_search
2553 /// [`binary_search_by`]: VecDeque::binary_search_by
2554 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2559 /// use std::collections::VecDeque;
2561 /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
2562 /// let i = deque.partition_point(|&x| x < 5);
2564 /// assert_eq!(i, 4);
2565 /// assert!(deque.iter().take(i).all(|&x| x < 5));
2566 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2569 /// If you want to insert an item to a sorted deque, while maintaining
2573 /// use std::collections::VecDeque;
2575 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2577 /// let idx = deque.partition_point(|&x| x < num);
2578 /// deque.insert(idx, num);
2579 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2581 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2582 pub fn partition_point<P>(&self, mut pred: P) -> usize
2584 P: FnMut(&T) -> bool,
2586 let (front, back) = self.as_slices();
2588 if let Some(true) = back.first().map(|v| pred(v)) {
2589 back.partition_point(pred) + front.len()
2591 front.partition_point(pred)
2596 impl<T: Clone, A: Allocator> VecDeque<T, A> {
2597 /// Modifies the deque in-place so that `len()` is equal to new_len,
2598 /// either by removing excess elements from the back or by appending clones of `value`
2604 /// use std::collections::VecDeque;
2606 /// let mut buf = VecDeque::new();
2607 /// buf.push_back(5);
2608 /// buf.push_back(10);
2609 /// buf.push_back(15);
2610 /// assert_eq!(buf, [5, 10, 15]);
2612 /// buf.resize(2, 0);
2613 /// assert_eq!(buf, [5, 10]);
2615 /// buf.resize(5, 20);
2616 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2618 #[stable(feature = "deque_extras", since = "1.16.0")]
2619 pub fn resize(&mut self, new_len: usize, value: T) {
2620 if new_len > self.len() {
2621 let extra = new_len - self.len();
2622 self.extend(repeat_n(value, extra))
2624 self.truncate(new_len);
2629 /// Returns the index in the underlying buffer for a given logical element index.
2631 fn wrap_index(logical_index: usize, capacity: usize) -> usize {
2633 (logical_index == 0 && capacity == 0)
2634 || logical_index < capacity
2635 || (logical_index - capacity) < capacity
2637 if logical_index >= capacity { logical_index - capacity } else { logical_index }
2640 #[stable(feature = "rust1", since = "1.0.0")]
2641 impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
2642 fn eq(&self, other: &Self) -> bool {
2643 if self.len != other.len() {
2646 let (sa, sb) = self.as_slices();
2647 let (oa, ob) = other.as_slices();
2648 if sa.len() == oa.len() {
2649 sa == oa && sb == ob
2650 } else if sa.len() < oa.len() {
2651 // Always divisible in three sections, for example:
2652 // self: [a b c|d e f]
2653 // other: [0 1 2 3|4 5]
2654 // front = 3, mid = 1,
2655 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2656 let front = sa.len();
2657 let mid = oa.len() - front;
2659 let (oa_front, oa_mid) = oa.split_at(front);
2660 let (sb_mid, sb_back) = sb.split_at(mid);
2661 debug_assert_eq!(sa.len(), oa_front.len());
2662 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2663 debug_assert_eq!(sb_back.len(), ob.len());
2664 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2666 let front = oa.len();
2667 let mid = sa.len() - front;
2669 let (sa_front, sa_mid) = sa.split_at(front);
2670 let (ob_mid, ob_back) = ob.split_at(mid);
2671 debug_assert_eq!(sa_front.len(), oa.len());
2672 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2673 debug_assert_eq!(sb.len(), ob_back.len());
2674 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2679 #[stable(feature = "rust1", since = "1.0.0")]
2680 impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
2682 __impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2683 __impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2684 __impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2685 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2686 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2687 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2689 #[stable(feature = "rust1", since = "1.0.0")]
2690 impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
2691 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2692 self.iter().partial_cmp(other.iter())
2696 #[stable(feature = "rust1", since = "1.0.0")]
2697 impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
2699 fn cmp(&self, other: &Self) -> Ordering {
2700 self.iter().cmp(other.iter())
2704 #[stable(feature = "rust1", since = "1.0.0")]
2705 impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
2706 fn hash<H: Hasher>(&self, state: &mut H) {
2707 state.write_length_prefix(self.len);
2708 // It's not possible to use Hash::hash_slice on slices
2709 // returned by as_slices method as their length can vary
2710 // in otherwise identical deques.
2712 // Hasher only guarantees equivalence for the exact same
2713 // set of calls to its methods.
2714 self.iter().for_each(|elem| elem.hash(state));
2718 #[stable(feature = "rust1", since = "1.0.0")]
2719 impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
2723 fn index(&self, index: usize) -> &T {
2724 self.get(index).expect("Out of bounds access")
2728 #[stable(feature = "rust1", since = "1.0.0")]
2729 impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
2731 fn index_mut(&mut self, index: usize) -> &mut T {
2732 self.get_mut(index).expect("Out of bounds access")
2736 #[stable(feature = "rust1", since = "1.0.0")]
2737 impl<T> FromIterator<T> for VecDeque<T> {
2738 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
2739 SpecFromIter::spec_from_iter(iter.into_iter())
2743 #[stable(feature = "rust1", since = "1.0.0")]
2744 impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
2746 type IntoIter = IntoIter<T, A>;
2748 /// Consumes the deque into a front-to-back iterator yielding elements by
2750 fn into_iter(self) -> IntoIter<T, A> {
2755 #[stable(feature = "rust1", since = "1.0.0")]
2756 impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
2758 type IntoIter = Iter<'a, T>;
2760 fn into_iter(self) -> Iter<'a, T> {
2765 #[stable(feature = "rust1", since = "1.0.0")]
2766 impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
2767 type Item = &'a mut T;
2768 type IntoIter = IterMut<'a, T>;
2770 fn into_iter(self) -> IterMut<'a, T> {
2775 #[stable(feature = "rust1", since = "1.0.0")]
2776 impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
2777 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2778 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter());
2782 fn extend_one(&mut self, elem: T) {
2783 self.push_back(elem);
2787 fn extend_reserve(&mut self, additional: usize) {
2788 self.reserve(additional);
2792 #[stable(feature = "extend_ref", since = "1.2.0")]
2793 impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
2794 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2795 self.spec_extend(iter.into_iter());
2799 fn extend_one(&mut self, &elem: &T) {
2800 self.push_back(elem);
2804 fn extend_reserve(&mut self, additional: usize) {
2805 self.reserve(additional);
2809 #[stable(feature = "rust1", since = "1.0.0")]
2810 impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
2811 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2812 f.debug_list().entries(self.iter()).finish()
2816 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2817 impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
2818 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2820 /// [`Vec<T>`]: crate::vec::Vec
2821 /// [`VecDeque<T>`]: crate::collections::VecDeque
2823 /// In its current implementation, this is a very cheap
2824 /// conversion. This isn't yet a guarantee though, and
2825 /// shouldn't be relied on.
2827 fn from(other: Vec<T, A>) -> Self {
2828 let (ptr, len, cap, alloc) = other.into_raw_parts_with_alloc();
2829 Self { head: 0, len, buf: unsafe { RawVec::from_raw_parts_in(ptr, cap, alloc) } }
2833 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2834 impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
2835 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2837 /// [`Vec<T>`]: crate::vec::Vec
2838 /// [`VecDeque<T>`]: crate::collections::VecDeque
2840 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
2841 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2846 /// use std::collections::VecDeque;
2848 /// // This one is *O*(1).
2849 /// let deque: VecDeque<_> = (1..5).collect();
2850 /// let ptr = deque.as_slices().0.as_ptr();
2851 /// let vec = Vec::from(deque);
2852 /// assert_eq!(vec, [1, 2, 3, 4]);
2853 /// assert_eq!(vec.as_ptr(), ptr);
2855 /// // This one needs data rearranging.
2856 /// let mut deque: VecDeque<_> = (1..5).collect();
2857 /// deque.push_front(9);
2858 /// deque.push_front(8);
2859 /// let ptr = deque.as_slices().1.as_ptr();
2860 /// let vec = Vec::from(deque);
2861 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2862 /// assert_eq!(vec.as_ptr(), ptr);
2864 fn from(mut other: VecDeque<T, A>) -> Self {
2865 other.make_contiguous();
2868 let other = ManuallyDrop::new(other);
2869 let buf = other.buf.ptr();
2870 let len = other.len();
2871 let cap = other.capacity();
2872 let alloc = ptr::read(other.allocator());
2874 if other.head != 0 {
2875 ptr::copy(buf.add(other.head), buf, len);
2877 Vec::from_raw_parts_in(buf, len, cap, alloc)
2882 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
2883 impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
2884 /// Converts a `[T; N]` into a `VecDeque<T>`.
2887 /// use std::collections::VecDeque;
2889 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
2890 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
2891 /// assert_eq!(deq1, deq2);
2893 fn from(arr: [T; N]) -> Self {
2894 let mut deq = VecDeque::with_capacity(N);
2895 let arr = ManuallyDrop::new(arr);
2897 // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
2899 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);