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_type")]
92 #[stable(feature = "rust1", since = "1.0.0")]
95 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
97 // tail and head are pointers into the buffer. Tail always points
98 // to the first element that could be read, Head always points
99 // to where data should be written.
100 // If tail == head the buffer is empty. The length of the ringbuffer
101 // is defined as the distance between the two.
107 #[stable(feature = "rust1", since = "1.0.0")]
108 impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A> {
109 fn clone(&self) -> Self {
110 let mut deq = Self::with_capacity_in(self.len(), self.allocator().clone());
111 deq.extend(self.iter().cloned());
115 fn clone_from(&mut self, other: &Self) {
116 self.truncate(other.len());
118 let mut iter = PairSlices::from(self, other);
119 while let Some((dst, src)) = iter.next() {
120 dst.clone_from_slice(&src);
123 if iter.has_remainder() {
124 for remainder in iter.remainder() {
125 self.extend(remainder.iter().cloned());
131 #[stable(feature = "rust1", since = "1.0.0")]
132 unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
134 /// Runs the destructor for all items in the slice when it gets dropped (normally or
135 /// during unwinding).
136 struct Dropper<'a, T>(&'a mut [T]);
138 impl<'a, T> Drop for Dropper<'a, T> {
141 ptr::drop_in_place(self.0);
146 let (front, back) = self.as_mut_slices();
148 let _back_dropper = Dropper(back);
150 ptr::drop_in_place(front);
152 // RawVec handles deallocation
156 #[stable(feature = "rust1", since = "1.0.0")]
157 impl<T> Default for VecDeque<T> {
158 /// Creates an empty `VecDeque<T>`.
160 fn default() -> VecDeque<T> {
165 impl<T, A: Allocator> VecDeque<T, A> {
166 /// Marginally more convenient
168 fn ptr(&self) -> *mut T {
172 /// Marginally more convenient
174 fn cap(&self) -> usize {
175 if mem::size_of::<T>() == 0 {
176 // For zero sized types, we are always at maximum capacity
183 /// Turn ptr into a slice
185 unsafe fn buffer_as_slice(&self) -> &[T] {
186 unsafe { slice::from_raw_parts(self.ptr(), self.cap()) }
189 /// Turn ptr into a mut slice
191 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
192 unsafe { slice::from_raw_parts_mut(self.ptr(), self.cap()) }
195 /// Moves an element out of the buffer
197 unsafe fn buffer_read(&mut self, off: usize) -> T {
198 unsafe { ptr::read(self.ptr().add(off)) }
201 /// Writes an element into the buffer, moving it.
203 unsafe fn buffer_write(&mut self, off: usize, value: T) {
205 ptr::write(self.ptr().add(off), value);
209 /// Returns `true` if the buffer is at full capacity.
211 fn is_full(&self) -> bool {
212 self.cap() - self.len() == 1
215 /// Returns the index in the underlying buffer for a given logical element
218 fn wrap_index(&self, idx: usize) -> usize {
219 wrap_index(idx, self.cap())
222 /// Returns the index in the underlying buffer for a given logical element
225 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
226 wrap_index(idx.wrapping_add(addend), self.cap())
229 /// Returns the index in the underlying buffer for a given logical element
230 /// index - subtrahend.
232 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
233 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
236 /// Copies a contiguous block of memory len long from src to dst
238 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
240 dst + len <= self.cap(),
241 "cpy dst={} src={} len={} cap={}",
248 src + len <= self.cap(),
249 "cpy dst={} src={} len={} cap={}",
256 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
260 /// Copies a contiguous block of memory len long from src to dst
262 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
264 dst + len <= self.cap(),
265 "cno dst={} src={} len={} cap={}",
272 src + len <= self.cap(),
273 "cno dst={} src={} len={} cap={}",
280 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
284 /// Copies a potentially wrapping block of memory len long from src to dest.
285 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
286 /// most one continuous overlapping region between src and dest).
287 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
289 fn diff(a: usize, b: usize) -> usize {
290 if a <= b { b - a } else { a - b }
293 cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
294 "wrc dst={} src={} len={} cap={}",
301 if src == dst || len == 0 {
305 let dst_after_src = self.wrap_sub(dst, src) < len;
307 let src_pre_wrap_len = self.cap() - src;
308 let dst_pre_wrap_len = self.cap() - dst;
309 let src_wraps = src_pre_wrap_len < len;
310 let dst_wraps = dst_pre_wrap_len < len;
312 match (dst_after_src, src_wraps, dst_wraps) {
313 (_, false, false) => {
314 // src doesn't wrap, dst doesn't wrap
317 // 1 [_ _ A A B B C C _]
318 // 2 [_ _ A A A A B B _]
322 self.copy(dst, src, len);
325 (false, false, true) => {
326 // dst before src, src doesn't wrap, dst wraps
329 // 1 [A A B B _ _ _ C C]
330 // 2 [A A B B _ _ _ A A]
331 // 3 [B B B B _ _ _ A A]
335 self.copy(dst, src, dst_pre_wrap_len);
336 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
339 (true, false, true) => {
340 // src before dst, src doesn't wrap, dst wraps
343 // 1 [C C _ _ _ A A B B]
344 // 2 [B B _ _ _ A A B B]
345 // 3 [B B _ _ _ A A A A]
349 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
350 self.copy(dst, src, dst_pre_wrap_len);
353 (false, true, false) => {
354 // dst before src, src wraps, dst doesn't wrap
357 // 1 [C C _ _ _ A A B B]
358 // 2 [C C _ _ _ B B B B]
359 // 3 [C C _ _ _ B B C C]
363 self.copy(dst, src, src_pre_wrap_len);
364 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
367 (true, true, false) => {
368 // src before dst, src wraps, dst doesn't wrap
371 // 1 [A A B B _ _ _ C C]
372 // 2 [A A A A _ _ _ C C]
373 // 3 [C C A A _ _ _ C C]
377 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
378 self.copy(dst, src, src_pre_wrap_len);
381 (false, true, true) => {
382 // dst before src, src wraps, dst wraps
385 // 1 [A B C D _ E F G H]
386 // 2 [A B C D _ E G H H]
387 // 3 [A B C D _ E G H A]
388 // 4 [B C C D _ E G H A]
391 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
392 let delta = dst_pre_wrap_len - src_pre_wrap_len;
394 self.copy(dst, src, src_pre_wrap_len);
395 self.copy(dst + src_pre_wrap_len, 0, delta);
396 self.copy(0, delta, len - dst_pre_wrap_len);
399 (true, true, true) => {
400 // src before dst, src wraps, dst wraps
403 // 1 [A B C D _ E F G H]
404 // 2 [A A B D _ E F G H]
405 // 3 [H A B D _ E F G H]
406 // 4 [H A B D _ E F F G]
409 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
410 let delta = src_pre_wrap_len - dst_pre_wrap_len;
412 self.copy(delta, 0, len - src_pre_wrap_len);
413 self.copy(0, self.cap() - delta, delta);
414 self.copy(dst, src, dst_pre_wrap_len);
420 /// Frobs the head and tail sections around to handle the fact that we
421 /// just reallocated. Unsafe because it trusts old_capacity.
423 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
424 let new_capacity = self.cap();
426 // Move the shortest contiguous section of the ring buffer
428 // [o o o o o o o . ]
430 // A [o o o o o o o . . . . . . . . . ]
432 // [o o . o o o o o ]
434 // B [. . . o o o o o o o . . . . . . ]
436 // [o o o o o . o o ]
438 // C [o o o o o . . . . . . . . . o o ]
440 if self.tail <= self.head {
443 } else if self.head < old_capacity - self.tail {
446 self.copy_nonoverlapping(old_capacity, 0, self.head);
448 self.head += old_capacity;
449 debug_assert!(self.head > self.tail);
452 let new_tail = new_capacity - (old_capacity - self.tail);
454 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
456 self.tail = new_tail;
457 debug_assert!(self.head < self.tail);
459 debug_assert!(self.head < self.cap());
460 debug_assert!(self.tail < self.cap());
461 debug_assert!(self.cap().count_ones() == 1);
465 impl<T> VecDeque<T> {
466 /// Creates an empty `VecDeque`.
471 /// use std::collections::VecDeque;
473 /// let vector: VecDeque<u32> = VecDeque::new();
476 #[stable(feature = "rust1", since = "1.0.0")]
477 pub fn new() -> VecDeque<T> {
478 VecDeque::new_in(Global)
481 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
486 /// use std::collections::VecDeque;
488 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
493 Self::with_capacity_in(capacity, Global)
497 impl<T, A: Allocator> VecDeque<T, A> {
498 /// Creates an empty `VecDeque`.
503 /// use std::collections::VecDeque;
505 /// let vector: VecDeque<u32> = VecDeque::new();
508 #[unstable(feature = "allocator_api", issue = "32838")]
509 pub fn new_in(alloc: A) -> VecDeque<T, A> {
510 VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc)
513 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
518 /// use std::collections::VecDeque;
520 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
522 #[unstable(feature = "allocator_api", issue = "32838")]
523 pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
524 // +1 since the ringbuffer always leaves one space empty
525 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
526 assert!(cap > capacity, "capacity overflow");
528 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) }
531 /// Provides a reference to the element at the given index.
533 /// Element at index 0 is the front of the queue.
538 /// use std::collections::VecDeque;
540 /// let mut buf = VecDeque::new();
541 /// buf.push_back(3);
542 /// buf.push_back(4);
543 /// buf.push_back(5);
544 /// assert_eq!(buf.get(1), Some(&4));
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn get(&self, index: usize) -> Option<&T> {
548 if index < self.len() {
549 let idx = self.wrap_add(self.tail, index);
550 unsafe { Some(&*self.ptr().add(idx)) }
556 /// Provides a mutable reference to the element at the given index.
558 /// Element at index 0 is the front of the queue.
563 /// use std::collections::VecDeque;
565 /// let mut buf = VecDeque::new();
566 /// buf.push_back(3);
567 /// buf.push_back(4);
568 /// buf.push_back(5);
569 /// if let Some(elem) = buf.get_mut(1) {
573 /// assert_eq!(buf[1], 7);
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
577 if index < self.len() {
578 let idx = self.wrap_add(self.tail, index);
579 unsafe { Some(&mut *self.ptr().add(idx)) }
585 /// Swaps elements at indices `i` and `j`.
587 /// `i` and `j` may be equal.
589 /// Element at index 0 is the front of the queue.
593 /// Panics if either index is out of bounds.
598 /// use std::collections::VecDeque;
600 /// let mut buf = VecDeque::new();
601 /// buf.push_back(3);
602 /// buf.push_back(4);
603 /// buf.push_back(5);
604 /// assert_eq!(buf, [3, 4, 5]);
606 /// assert_eq!(buf, [5, 4, 3]);
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub fn swap(&mut self, i: usize, j: usize) {
610 assert!(i < self.len());
611 assert!(j < self.len());
612 let ri = self.wrap_add(self.tail, i);
613 let rj = self.wrap_add(self.tail, j);
614 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
617 /// Returns the number of elements the `VecDeque` can hold without
623 /// use std::collections::VecDeque;
625 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
626 /// assert!(buf.capacity() >= 10);
629 #[stable(feature = "rust1", since = "1.0.0")]
630 pub fn capacity(&self) -> usize {
634 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
635 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
637 /// Note that the allocator may give the collection more space than it requests. Therefore
638 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
639 /// insertions are expected.
643 /// Panics if the new capacity overflows `usize`.
648 /// use std::collections::VecDeque;
650 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
651 /// buf.reserve_exact(10);
652 /// assert!(buf.capacity() >= 11);
655 /// [`reserve`]: VecDeque::reserve
656 #[stable(feature = "rust1", since = "1.0.0")]
657 pub fn reserve_exact(&mut self, additional: usize) {
658 self.reserve(additional);
661 /// Reserves capacity for at least `additional` more elements to be inserted in the given
662 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
666 /// Panics if the new capacity overflows `usize`.
671 /// use std::collections::VecDeque;
673 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
675 /// assert!(buf.capacity() >= 11);
677 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn reserve(&mut self, additional: usize) {
679 let old_cap = self.cap();
680 let used_cap = self.len() + 1;
681 let new_cap = used_cap
682 .checked_add(additional)
683 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
684 .expect("capacity overflow");
686 if new_cap > old_cap {
687 self.buf.reserve_exact(used_cap, new_cap - used_cap);
689 self.handle_capacity_increase(old_cap);
694 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
695 /// be inserted in the given `VecDeque<T>`. After calling `try_reserve_exact`,
696 /// capacity will be greater than or equal to `self.len() + additional`.
697 /// Does nothing if the capacity is already sufficient.
699 /// Note that the allocator may give the collection more space than it
700 /// requests. Therefore, capacity can not be relied upon to be precisely
701 /// minimal. Prefer [`reserve`] if future insertions are expected.
703 /// [`reserve`]: VecDeque::reserve
707 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
713 /// #![feature(try_reserve)]
714 /// use std::collections::TryReserveError;
715 /// use std::collections::VecDeque;
717 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
718 /// let mut output = VecDeque::new();
720 /// // Pre-reserve the memory, exiting if we can't
721 /// output.try_reserve_exact(data.len())?;
723 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
724 /// output.extend(data.iter().map(|&val| {
725 /// val * 2 + 5 // very complicated
730 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
732 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
733 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
734 self.try_reserve(additional)
737 /// Tries to reserve capacity for at least `additional` more elements to be inserted
738 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
739 /// frequent reallocations. After calling `try_reserve`, capacity will be
740 /// greater than or equal to `self.len() + additional`. Does nothing if
741 /// capacity is already sufficient.
745 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
751 /// #![feature(try_reserve)]
752 /// use std::collections::TryReserveError;
753 /// use std::collections::VecDeque;
755 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
756 /// let mut output = VecDeque::new();
758 /// // Pre-reserve the memory, exiting if we can't
759 /// output.try_reserve(data.len())?;
761 /// // Now we know this can't OOM in the middle of our complex work
762 /// output.extend(data.iter().map(|&val| {
763 /// val * 2 + 5 // very complicated
768 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
770 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
771 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
772 let old_cap = self.cap();
773 let used_cap = self.len() + 1;
774 let new_cap = used_cap
775 .checked_add(additional)
776 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
777 .ok_or(TryReserveErrorKind::CapacityOverflow)?;
779 if new_cap > old_cap {
780 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
782 self.handle_capacity_increase(old_cap);
788 /// Shrinks the capacity of the `VecDeque` as much as possible.
790 /// It will drop down as close as possible to the length but the allocator may still inform the
791 /// `VecDeque` that there is space for a few more elements.
796 /// use std::collections::VecDeque;
798 /// let mut buf = VecDeque::with_capacity(15);
799 /// buf.extend(0..4);
800 /// assert_eq!(buf.capacity(), 15);
801 /// buf.shrink_to_fit();
802 /// assert!(buf.capacity() >= 4);
804 #[stable(feature = "deque_extras_15", since = "1.5.0")]
805 pub fn shrink_to_fit(&mut self) {
809 /// Shrinks the capacity of the `VecDeque` with a lower bound.
811 /// The capacity will remain at least as large as both the length
812 /// and the supplied value.
814 /// If the current capacity is less than the lower limit, this is a no-op.
819 /// use std::collections::VecDeque;
821 /// let mut buf = VecDeque::with_capacity(15);
822 /// buf.extend(0..4);
823 /// assert_eq!(buf.capacity(), 15);
824 /// buf.shrink_to(6);
825 /// assert!(buf.capacity() >= 6);
826 /// buf.shrink_to(0);
827 /// assert!(buf.capacity() >= 4);
829 #[stable(feature = "shrink_to", since = "1.56.0")]
830 pub fn shrink_to(&mut self, min_capacity: usize) {
831 let min_capacity = cmp::min(min_capacity, self.capacity());
832 // We don't have to worry about an overflow as neither `self.len()` nor `self.capacity()`
833 // can ever be `usize::MAX`. +1 as the ringbuffer always leaves one space empty.
834 let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
835 .next_power_of_two();
837 if target_cap < self.cap() {
838 // There are three cases of interest:
839 // All elements are out of desired bounds
840 // Elements are contiguous, and head is out of desired bounds
841 // Elements are discontiguous, and tail is out of desired bounds
843 // At all other times, element positions are unaffected.
845 // Indicates that elements at the head should be moved.
846 let head_outside = self.head == 0 || self.head >= target_cap;
847 // Move elements from out of desired bounds (positions after target_cap)
848 if self.tail >= target_cap && head_outside {
850 // [. . . . . . . . o o o o o o o . ]
852 // [o o o o o o o . ]
854 self.copy_nonoverlapping(0, self.tail, self.len());
856 self.head = self.len();
858 } else if self.tail != 0 && self.tail < target_cap && head_outside {
860 // [. . . o o o o o o o . . . . . . ]
862 // [o o . o o o o o ]
863 let len = self.wrap_sub(self.head, target_cap);
865 self.copy_nonoverlapping(0, target_cap, len);
868 debug_assert!(self.head < self.tail);
869 } else if self.tail >= target_cap {
871 // [o o o o o . . . . . . . . . o o ]
873 // [o o o o o . o o ]
874 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
875 let len = self.cap() - self.tail;
876 let new_tail = target_cap - len;
878 self.copy_nonoverlapping(new_tail, self.tail, len);
880 self.tail = new_tail;
881 debug_assert!(self.head < self.tail);
884 self.buf.shrink_to_fit(target_cap);
886 debug_assert!(self.head < self.cap());
887 debug_assert!(self.tail < self.cap());
888 debug_assert!(self.cap().count_ones() == 1);
892 /// Shortens the `VecDeque`, keeping the first `len` elements and dropping
895 /// If `len` is greater than the `VecDeque`'s current length, this has no
901 /// use std::collections::VecDeque;
903 /// let mut buf = VecDeque::new();
904 /// buf.push_back(5);
905 /// buf.push_back(10);
906 /// buf.push_back(15);
907 /// assert_eq!(buf, [5, 10, 15]);
909 /// assert_eq!(buf, [5]);
911 #[stable(feature = "deque_extras", since = "1.16.0")]
912 pub fn truncate(&mut self, len: usize) {
913 /// Runs the destructor for all items in the slice when it gets dropped (normally or
914 /// during unwinding).
915 struct Dropper<'a, T>(&'a mut [T]);
917 impl<'a, T> Drop for Dropper<'a, T> {
920 ptr::drop_in_place(self.0);
927 // * Any slice passed to `drop_in_place` is valid; the second case has
928 // `len <= front.len()` and returning on `len > self.len()` ensures
929 // `begin <= back.len()` in the first case
930 // * The head of the VecDeque is moved before calling `drop_in_place`,
931 // so no value is dropped twice if `drop_in_place` panics
933 if len > self.len() {
936 let num_dropped = self.len() - len;
937 let (front, back) = self.as_mut_slices();
938 if len > front.len() {
939 let begin = len - front.len();
940 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
941 self.head = self.wrap_sub(self.head, num_dropped);
942 ptr::drop_in_place(drop_back);
944 let drop_back = back as *mut _;
945 let drop_front = front.get_unchecked_mut(len..) as *mut _;
946 self.head = self.wrap_sub(self.head, num_dropped);
948 // Make sure the second half is dropped even when a destructor
949 // in the first one panics.
950 let _back_dropper = Dropper(&mut *drop_back);
951 ptr::drop_in_place(drop_front);
956 /// Returns a reference to the underlying allocator.
957 #[unstable(feature = "allocator_api", issue = "32838")]
959 pub fn allocator(&self) -> &A {
963 /// Returns a front-to-back iterator.
968 /// use std::collections::VecDeque;
970 /// let mut buf = VecDeque::new();
971 /// buf.push_back(5);
972 /// buf.push_back(3);
973 /// buf.push_back(4);
974 /// let b: &[_] = &[&5, &3, &4];
975 /// let c: Vec<&i32> = buf.iter().collect();
976 /// assert_eq!(&c[..], b);
978 #[stable(feature = "rust1", since = "1.0.0")]
979 pub fn iter(&self) -> Iter<'_, T> {
980 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } }
983 /// Returns a front-to-back iterator that returns mutable references.
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 /// for num in buf.iter_mut() {
997 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
998 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1002 // SAFETY: The internal `IterMut` safety invariant is established because the
1003 // `ring` we create is a dereferencable slice for lifetime '_.
1007 ring: ptr::slice_from_raw_parts_mut(self.ptr(), self.cap()),
1008 phantom: PhantomData,
1012 /// Returns a pair of slices which contain, in order, the contents of the
1015 /// If [`make_contiguous`] was previously called, all elements of the
1016 /// `VecDeque` will be in the first slice and the second slice will be empty.
1018 /// [`make_contiguous`]: VecDeque::make_contiguous
1023 /// use std::collections::VecDeque;
1025 /// let mut vector = VecDeque::new();
1027 /// vector.push_back(0);
1028 /// vector.push_back(1);
1029 /// vector.push_back(2);
1031 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
1033 /// vector.push_front(10);
1034 /// vector.push_front(9);
1036 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1039 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1040 pub fn as_slices(&self) -> (&[T], &[T]) {
1042 let buf = self.buffer_as_slice();
1043 RingSlices::ring_slices(buf, self.head, self.tail)
1047 /// Returns a pair of slices which contain, in order, the contents of the
1050 /// If [`make_contiguous`] was previously called, all elements of the
1051 /// `VecDeque` will be in the first slice and the second slice will be empty.
1053 /// [`make_contiguous`]: VecDeque::make_contiguous
1058 /// use std::collections::VecDeque;
1060 /// let mut vector = VecDeque::new();
1062 /// vector.push_back(0);
1063 /// vector.push_back(1);
1065 /// vector.push_front(10);
1066 /// vector.push_front(9);
1068 /// vector.as_mut_slices().0[0] = 42;
1069 /// vector.as_mut_slices().1[0] = 24;
1070 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
1073 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1074 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1076 let head = self.head;
1077 let tail = self.tail;
1078 let buf = self.buffer_as_mut_slice();
1079 RingSlices::ring_slices(buf, head, tail)
1083 /// Returns the number of elements in the `VecDeque`.
1088 /// use std::collections::VecDeque;
1090 /// let mut v = VecDeque::new();
1091 /// assert_eq!(v.len(), 0);
1093 /// assert_eq!(v.len(), 1);
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub fn len(&self) -> usize {
1097 count(self.tail, self.head, self.cap())
1100 /// Returns `true` if the `VecDeque` is empty.
1105 /// use std::collections::VecDeque;
1107 /// let mut v = VecDeque::new();
1108 /// assert!(v.is_empty());
1109 /// v.push_front(1);
1110 /// assert!(!v.is_empty());
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn is_empty(&self) -> bool {
1114 self.tail == self.head
1117 fn range_tail_head<R>(&self, range: R) -> (usize, usize)
1119 R: RangeBounds<usize>,
1121 let Range { start, end } = slice::range(range, ..self.len());
1122 let tail = self.wrap_add(self.tail, start);
1123 let head = self.wrap_add(self.tail, end);
1127 /// Creates an iterator that covers the specified range in the `VecDeque`.
1131 /// Panics if the starting point is greater than the end point or if
1132 /// the end point is greater than the length of the vector.
1137 /// use std::collections::VecDeque;
1139 /// let v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1140 /// let range = v.range(2..).copied().collect::<VecDeque<_>>();
1141 /// assert_eq!(range, [3]);
1143 /// // A full range covers all contents
1144 /// let all = v.range(..);
1145 /// assert_eq!(all.len(), 3);
1148 #[stable(feature = "deque_range", since = "1.51.0")]
1149 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1151 R: RangeBounds<usize>,
1153 let (tail, head) = self.range_tail_head(range);
1157 // The shared reference we have in &self is maintained in the '_ of Iter.
1158 ring: unsafe { self.buffer_as_slice() },
1162 /// Creates an iterator that covers the specified mutable range in the `VecDeque`.
1166 /// Panics if the starting point is greater than the end point or if
1167 /// the end point is greater than the length of the vector.
1172 /// use std::collections::VecDeque;
1174 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1175 /// for v in v.range_mut(2..) {
1178 /// assert_eq!(v, vec![1, 2, 6]);
1180 /// // A full range covers all contents
1181 /// for v in v.range_mut(..) {
1184 /// assert_eq!(v, vec![2, 4, 12]);
1187 #[stable(feature = "deque_range", since = "1.51.0")]
1188 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1190 R: RangeBounds<usize>,
1192 let (tail, head) = self.range_tail_head(range);
1194 // SAFETY: The internal `IterMut` safety invariant is established because the
1195 // `ring` we create is a dereferencable slice for lifetime '_.
1199 ring: ptr::slice_from_raw_parts_mut(self.ptr(), self.cap()),
1200 phantom: PhantomData,
1204 /// Creates a draining iterator that removes the specified range in the
1205 /// `VecDeque` and yields the removed items.
1207 /// Note 1: The element range is removed even if the iterator is not
1208 /// consumed until the end.
1210 /// Note 2: It is unspecified how many elements are removed from the deque,
1211 /// if the `Drain` value is not dropped, but the borrow it holds expires
1212 /// (e.g., due to `mem::forget`).
1216 /// Panics if the starting point is greater than the end point or if
1217 /// the end point is greater than the length of the vector.
1222 /// use std::collections::VecDeque;
1224 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1225 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
1226 /// assert_eq!(drained, [3]);
1227 /// assert_eq!(v, [1, 2]);
1229 /// // A full range clears all contents
1231 /// assert!(v.is_empty());
1234 #[stable(feature = "drain", since = "1.6.0")]
1235 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1237 R: RangeBounds<usize>,
1241 // When the Drain is first created, the source deque is shortened to
1242 // make sure no uninitialized or moved-from elements are accessible at
1243 // all if the Drain's destructor never gets to run.
1245 // Drain will ptr::read out the values to remove.
1246 // When finished, the remaining data will be copied back to cover the hole,
1247 // and the head/tail values will be restored correctly.
1249 let (drain_tail, drain_head) = self.range_tail_head(range);
1251 // The deque's elements are parted into three segments:
1252 // * self.tail -> drain_tail
1253 // * drain_tail -> drain_head
1254 // * drain_head -> self.head
1256 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1258 // We store drain_tail as self.head, and drain_head and self.head as
1259 // after_tail and after_head respectively on the Drain. This also
1260 // truncates the effective array such that if the Drain is leaked, we
1261 // have forgotten about the potentially moved values after the start of
1265 // [. . . o o x x o o . . .]
1267 let head = self.head;
1269 // "forget" about the values after the start of the drain until after
1270 // the drain is complete and the Drain destructor is run.
1271 self.head = drain_tail;
1274 deque: NonNull::from(&mut *self),
1275 after_tail: drain_head,
1280 // Crucially, we only create shared references from `self` here and read from
1281 // it. We do not write to `self` nor reborrow to a mutable reference.
1282 // Hence the raw pointer we created above, for `deque`, remains valid.
1283 ring: unsafe { self.buffer_as_slice() },
1288 /// Clears the `VecDeque`, removing all values.
1293 /// use std::collections::VecDeque;
1295 /// let mut v = VecDeque::new();
1298 /// assert!(v.is_empty());
1300 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub fn clear(&mut self) {
1306 /// Returns `true` if the `VecDeque` contains an element equal to the
1312 /// use std::collections::VecDeque;
1314 /// let mut vector: VecDeque<u32> = VecDeque::new();
1316 /// vector.push_back(0);
1317 /// vector.push_back(1);
1319 /// assert_eq!(vector.contains(&1), true);
1320 /// assert_eq!(vector.contains(&10), false);
1322 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1323 pub fn contains(&self, x: &T) -> bool
1327 let (a, b) = self.as_slices();
1328 a.contains(x) || b.contains(x)
1331 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1337 /// use std::collections::VecDeque;
1339 /// let mut d = VecDeque::new();
1340 /// assert_eq!(d.front(), None);
1344 /// assert_eq!(d.front(), Some(&1));
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 pub fn front(&self) -> Option<&T> {
1351 /// Provides a mutable reference to the front element, or `None` if the
1352 /// `VecDeque` is empty.
1357 /// use std::collections::VecDeque;
1359 /// let mut d = VecDeque::new();
1360 /// assert_eq!(d.front_mut(), None);
1364 /// match d.front_mut() {
1365 /// Some(x) => *x = 9,
1368 /// assert_eq!(d.front(), Some(&9));
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 pub fn front_mut(&mut self) -> Option<&mut T> {
1375 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1381 /// use std::collections::VecDeque;
1383 /// let mut d = VecDeque::new();
1384 /// assert_eq!(d.back(), None);
1388 /// assert_eq!(d.back(), Some(&2));
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 pub fn back(&self) -> Option<&T> {
1392 self.get(self.len().wrapping_sub(1))
1395 /// Provides a mutable reference to the back element, or `None` if the
1396 /// `VecDeque` is empty.
1401 /// use std::collections::VecDeque;
1403 /// let mut d = VecDeque::new();
1404 /// assert_eq!(d.back(), None);
1408 /// match d.back_mut() {
1409 /// Some(x) => *x = 9,
1412 /// assert_eq!(d.back(), Some(&9));
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 pub fn back_mut(&mut self) -> Option<&mut T> {
1416 self.get_mut(self.len().wrapping_sub(1))
1419 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1425 /// use std::collections::VecDeque;
1427 /// let mut d = VecDeque::new();
1431 /// assert_eq!(d.pop_front(), Some(1));
1432 /// assert_eq!(d.pop_front(), Some(2));
1433 /// assert_eq!(d.pop_front(), None);
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 pub fn pop_front(&mut self) -> Option<T> {
1437 if self.is_empty() {
1440 let tail = self.tail;
1441 self.tail = self.wrap_add(self.tail, 1);
1442 unsafe { Some(self.buffer_read(tail)) }
1446 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1452 /// use std::collections::VecDeque;
1454 /// let mut buf = VecDeque::new();
1455 /// assert_eq!(buf.pop_back(), None);
1456 /// buf.push_back(1);
1457 /// buf.push_back(3);
1458 /// assert_eq!(buf.pop_back(), Some(3));
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 pub fn pop_back(&mut self) -> Option<T> {
1462 if self.is_empty() {
1465 self.head = self.wrap_sub(self.head, 1);
1466 let head = self.head;
1467 unsafe { Some(self.buffer_read(head)) }
1471 /// Prepends an element to the `VecDeque`.
1476 /// use std::collections::VecDeque;
1478 /// let mut d = VecDeque::new();
1479 /// d.push_front(1);
1480 /// d.push_front(2);
1481 /// assert_eq!(d.front(), Some(&2));
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 pub fn push_front(&mut self, value: T) {
1489 self.tail = self.wrap_sub(self.tail, 1);
1490 let tail = self.tail;
1492 self.buffer_write(tail, value);
1496 /// Appends an element to the back of the `VecDeque`.
1501 /// use std::collections::VecDeque;
1503 /// let mut buf = VecDeque::new();
1504 /// buf.push_back(1);
1505 /// buf.push_back(3);
1506 /// assert_eq!(3, *buf.back().unwrap());
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 pub fn push_back(&mut self, value: T) {
1514 let head = self.head;
1515 self.head = self.wrap_add(self.head, 1);
1516 unsafe { self.buffer_write(head, value) }
1520 fn is_contiguous(&self) -> bool {
1521 // FIXME: Should we consider `head == 0` to mean
1522 // that `self` is contiguous?
1523 self.tail <= self.head
1526 /// Removes an element from anywhere in the `VecDeque` and returns it,
1527 /// replacing it with the first element.
1529 /// This does not preserve ordering, but is *O*(1).
1531 /// Returns `None` if `index` is out of bounds.
1533 /// Element at index 0 is the front of the queue.
1538 /// use std::collections::VecDeque;
1540 /// let mut buf = VecDeque::new();
1541 /// assert_eq!(buf.swap_remove_front(0), None);
1542 /// buf.push_back(1);
1543 /// buf.push_back(2);
1544 /// buf.push_back(3);
1545 /// assert_eq!(buf, [1, 2, 3]);
1547 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1548 /// assert_eq!(buf, [2, 1]);
1550 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1551 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1552 let length = self.len();
1553 if length > 0 && index < length && index != 0 {
1554 self.swap(index, 0);
1555 } else if index >= length {
1561 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1564 /// This does not preserve ordering, but is *O*(1).
1566 /// Returns `None` if `index` is out of bounds.
1568 /// Element at index 0 is the front of the queue.
1573 /// use std::collections::VecDeque;
1575 /// let mut buf = VecDeque::new();
1576 /// assert_eq!(buf.swap_remove_back(0), None);
1577 /// buf.push_back(1);
1578 /// buf.push_back(2);
1579 /// buf.push_back(3);
1580 /// assert_eq!(buf, [1, 2, 3]);
1582 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1583 /// assert_eq!(buf, [3, 2]);
1585 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1586 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1587 let length = self.len();
1588 if length > 0 && index < length - 1 {
1589 self.swap(index, length - 1);
1590 } else if index >= length {
1596 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1597 /// greater than or equal to `index` towards the back.
1599 /// Element at index 0 is the front of the queue.
1603 /// Panics if `index` is greater than `VecDeque`'s length
1608 /// use std::collections::VecDeque;
1610 /// let mut vec_deque = VecDeque::new();
1611 /// vec_deque.push_back('a');
1612 /// vec_deque.push_back('b');
1613 /// vec_deque.push_back('c');
1614 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1616 /// vec_deque.insert(1, 'd');
1617 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1619 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1620 pub fn insert(&mut self, index: usize, value: T) {
1621 assert!(index <= self.len(), "index out of bounds");
1626 // Move the least number of elements in the ring buffer and insert
1629 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1631 // There are three main cases:
1632 // Elements are contiguous
1633 // - special case when tail is 0
1634 // Elements are discontiguous and the insert is in the tail section
1635 // Elements are discontiguous and the insert is in the head section
1637 // For each of those there are two more cases:
1638 // Insert is closer to tail
1639 // Insert is closer to head
1641 // Key: H - self.head
1643 // o - Valid element
1644 // I - Insertion element
1645 // A - The element that should be after the insertion point
1646 // M - Indicates element was moved
1648 let idx = self.wrap_add(self.tail, index);
1650 let distance_to_tail = index;
1651 let distance_to_head = self.len() - index;
1653 let contiguous = self.is_contiguous();
1655 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1656 (true, true, _) if index == 0 => {
1661 // [A o o o o o o . . . . . . . . .]
1664 // [A o o o o o o o . . . . . I]
1667 self.tail = self.wrap_sub(self.tail, 1);
1669 (true, true, _) => {
1671 // contiguous, insert closer to tail:
1674 // [. . . o o A o o o o . . . . . .]
1677 // [. . o o I A o o o o . . . . . .]
1680 // contiguous, insert closer to tail and tail is 0:
1684 // [o o A o o o o . . . . . . . . .]
1687 // [o I A o o o o o . . . . . . . o]
1690 let new_tail = self.wrap_sub(self.tail, 1);
1692 self.copy(new_tail, self.tail, 1);
1693 // Already moved the tail, so we only copy `index - 1` elements.
1694 self.copy(self.tail, self.tail + 1, index - 1);
1696 self.tail = new_tail;
1699 (true, false, _) => {
1701 // contiguous, insert closer to head:
1704 // [. . . o o o o A o o . . . . . .]
1707 // [. . . o o o o I A o o . . . . .]
1710 self.copy(idx + 1, idx, self.head - idx);
1711 self.head = self.wrap_add(self.head, 1);
1714 (false, true, true) => {
1716 // discontiguous, insert closer to tail, tail section:
1719 // [o o o o o o . . . . . o o A o o]
1722 // [o o o o o o . . . . o o I A o o]
1725 self.copy(self.tail - 1, self.tail, index);
1729 (false, false, true) => {
1731 // discontiguous, insert closer to head, tail section:
1734 // [o o . . . . . . . o o o o o A o]
1737 // [o o o . . . . . . o o o o o I A]
1740 // copy elements up to new head
1741 self.copy(1, 0, self.head);
1743 // copy last element into empty spot at bottom of buffer
1744 self.copy(0, self.cap() - 1, 1);
1746 // move elements from idx to end forward not including ^ element
1747 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1752 (false, true, false) if idx == 0 => {
1754 // discontiguous, insert is closer to tail, head section,
1755 // and is at index zero in the internal buffer:
1758 // [A o o o o o o o o o . . . o o o]
1761 // [A o o o o o o o o o . . o o o I]
1764 // copy elements up to new tail
1765 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1767 // copy last element into empty spot at bottom of buffer
1768 self.copy(self.cap() - 1, 0, 1);
1773 (false, true, false) => {
1775 // discontiguous, insert closer to tail, head section:
1778 // [o o o A o o o o o o . . . o o o]
1781 // [o o I A o o o o o o . . o o o o]
1784 // copy elements up to new tail
1785 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1787 // copy last element into empty spot at bottom of buffer
1788 self.copy(self.cap() - 1, 0, 1);
1790 // move elements from idx-1 to end forward not including ^ element
1791 self.copy(0, 1, idx - 1);
1796 (false, false, false) => {
1798 // discontiguous, insert closer to head, head section:
1801 // [o o o o A o o . . . . . . o o o]
1804 // [o o o o I A o o . . . . . o o o]
1807 self.copy(idx + 1, idx, self.head - idx);
1813 // tail might've been changed so we need to recalculate
1814 let new_idx = self.wrap_add(self.tail, index);
1816 self.buffer_write(new_idx, value);
1820 /// Removes and returns the element at `index` from the `VecDeque`.
1821 /// Whichever end is closer to the removal point will be moved to make
1822 /// room, and all the affected elements will be moved to new positions.
1823 /// Returns `None` if `index` is out of bounds.
1825 /// Element at index 0 is the front of the queue.
1830 /// use std::collections::VecDeque;
1832 /// let mut buf = VecDeque::new();
1833 /// buf.push_back(1);
1834 /// buf.push_back(2);
1835 /// buf.push_back(3);
1836 /// assert_eq!(buf, [1, 2, 3]);
1838 /// assert_eq!(buf.remove(1), Some(2));
1839 /// assert_eq!(buf, [1, 3]);
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 pub fn remove(&mut self, index: usize) -> Option<T> {
1843 if self.is_empty() || self.len() <= index {
1847 // There are three main cases:
1848 // Elements are contiguous
1849 // Elements are discontiguous and the removal is in the tail section
1850 // Elements are discontiguous and the removal is in the head section
1851 // - special case when elements are technically contiguous,
1852 // but self.head = 0
1854 // For each of those there are two more cases:
1855 // Insert is closer to tail
1856 // Insert is closer to head
1858 // Key: H - self.head
1860 // o - Valid element
1861 // x - Element marked for removal
1862 // R - Indicates element that is being removed
1863 // M - Indicates element was moved
1865 let idx = self.wrap_add(self.tail, index);
1867 let elem = unsafe { Some(self.buffer_read(idx)) };
1869 let distance_to_tail = index;
1870 let distance_to_head = self.len() - index;
1872 let contiguous = self.is_contiguous();
1874 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1875 (true, true, _) => {
1877 // contiguous, remove closer to tail:
1880 // [. . . o o x o o o o . . . . . .]
1883 // [. . . . o o o o o o . . . . . .]
1886 self.copy(self.tail + 1, self.tail, index);
1890 (true, false, _) => {
1892 // contiguous, remove closer to head:
1895 // [. . . o o o o x o o . . . . . .]
1898 // [. . . o o o o o o . . . . . . .]
1901 self.copy(idx, idx + 1, self.head - idx - 1);
1905 (false, true, true) => {
1907 // discontiguous, remove closer to tail, tail section:
1910 // [o o o o o o . . . . . o o x o o]
1913 // [o o o o o o . . . . . . o o o o]
1916 self.copy(self.tail + 1, self.tail, index);
1917 self.tail = self.wrap_add(self.tail, 1);
1920 (false, false, false) => {
1922 // discontiguous, remove closer to head, head section:
1925 // [o o o o x o o . . . . . . o o o]
1928 // [o o o o o o . . . . . . . o o o]
1931 self.copy(idx, idx + 1, self.head - idx - 1);
1935 (false, false, true) => {
1937 // discontiguous, remove closer to head, tail section:
1940 // [o o o . . . . . . o o o o o x o]
1943 // [o o . . . . . . . o o o o o o o]
1946 // or quasi-discontiguous, remove next to head, tail section:
1949 // [. . . . . . . . . o o o o o x o]
1952 // [. . . . . . . . . o o o o o o .]
1955 // draw in elements in the tail section
1956 self.copy(idx, idx + 1, self.cap() - idx - 1);
1958 // Prevents underflow.
1960 // copy first element into empty spot
1961 self.copy(self.cap() - 1, 0, 1);
1963 // move elements in the head section backwards
1964 self.copy(0, 1, self.head - 1);
1967 self.head = self.wrap_sub(self.head, 1);
1970 (false, true, false) => {
1972 // discontiguous, remove closer to tail, head section:
1975 // [o o x o o o o o o o . . . o o o]
1978 // [o o o o o o o o o o . . . . o o]
1981 // draw in elements up to idx
1982 self.copy(1, 0, idx);
1984 // copy last element into empty spot
1985 self.copy(0, self.cap() - 1, 1);
1987 // move elements from tail to end forward, excluding the last one
1988 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1990 self.tail = self.wrap_add(self.tail, 1);
1998 /// Splits the `VecDeque` into two at the given index.
2000 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2001 /// and the returned `VecDeque` contains elements `[at, len)`.
2003 /// Note that the capacity of `self` does not change.
2005 /// Element at index 0 is the front of the queue.
2009 /// Panics if `at > len`.
2014 /// use std::collections::VecDeque;
2016 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
2017 /// let buf2 = buf.split_off(1);
2018 /// assert_eq!(buf, [1]);
2019 /// assert_eq!(buf2, [2, 3]);
2022 #[must_use = "use `.truncate()` if you don't need the other half"]
2023 #[stable(feature = "split_off", since = "1.4.0")]
2024 pub fn split_off(&mut self, at: usize) -> Self
2028 let len = self.len();
2029 assert!(at <= len, "`at` out of bounds");
2031 let other_len = len - at;
2032 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2035 let (first_half, second_half) = self.as_slices();
2037 let first_len = first_half.len();
2038 let second_len = second_half.len();
2040 // `at` lies in the first half.
2041 let amount_in_first = first_len - at;
2043 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2045 // just take all of the second half.
2046 ptr::copy_nonoverlapping(
2047 second_half.as_ptr(),
2048 other.ptr().add(amount_in_first),
2052 // `at` lies in the second half, need to factor in the elements we skipped
2053 // in the first half.
2054 let offset = at - first_len;
2055 let amount_in_second = second_len - offset;
2056 ptr::copy_nonoverlapping(
2057 second_half.as_ptr().add(offset),
2064 // Cleanup where the ends of the buffers are
2065 self.head = self.wrap_sub(self.head, other_len);
2066 other.head = other.wrap_index(other_len);
2071 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2075 /// Panics if the new number of elements in self overflows a `usize`.
2080 /// use std::collections::VecDeque;
2082 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
2083 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
2084 /// buf.append(&mut buf2);
2085 /// assert_eq!(buf, [1, 2, 3, 4]);
2086 /// assert_eq!(buf2, []);
2089 #[stable(feature = "append", since = "1.4.0")]
2090 pub fn append(&mut self, other: &mut Self) {
2092 self.extend(other.drain(..));
2095 /// Retains only the elements specified by the predicate.
2097 /// In other words, remove all elements `e` such that `f(&e)` returns false.
2098 /// This method operates in place, visiting each element exactly once in the
2099 /// original order, and preserves the order of the retained elements.
2104 /// use std::collections::VecDeque;
2106 /// let mut buf = VecDeque::new();
2107 /// buf.extend(1..5);
2108 /// buf.retain(|&x| x % 2 == 0);
2109 /// assert_eq!(buf, [2, 4]);
2112 /// Because the elements are visited exactly once in the original order,
2113 /// external state may be used to decide which elements to keep.
2116 /// use std::collections::VecDeque;
2118 /// let mut buf = VecDeque::new();
2119 /// buf.extend(1..6);
2121 /// let keep = [false, true, true, false, true];
2122 /// let mut iter = keep.iter();
2123 /// buf.retain(|_| *iter.next().unwrap());
2124 /// assert_eq!(buf, [2, 3, 5]);
2126 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2127 pub fn retain<F>(&mut self, mut f: F)
2129 F: FnMut(&T) -> bool,
2131 let len = self.len();
2135 // Stage 1: All values are retained.
2144 // Stage 2: Swap retained value into current idx.
2151 self.swap(idx, cur);
2155 // Stage 3: Trancate all values after idx.
2161 // This may panic or abort
2163 fn grow(&mut self) {
2165 let old_cap = self.cap();
2166 // Double the buffer size.
2167 self.buf.reserve_exact(old_cap, old_cap);
2168 assert!(self.cap() == old_cap * 2);
2170 self.handle_capacity_increase(old_cap);
2172 debug_assert!(!self.is_full());
2176 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
2177 /// either by removing excess elements from the back or by appending
2178 /// elements generated by calling `generator` to the back.
2183 /// use std::collections::VecDeque;
2185 /// let mut buf = VecDeque::new();
2186 /// buf.push_back(5);
2187 /// buf.push_back(10);
2188 /// buf.push_back(15);
2189 /// assert_eq!(buf, [5, 10, 15]);
2191 /// buf.resize_with(5, Default::default);
2192 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2194 /// buf.resize_with(2, || unreachable!());
2195 /// assert_eq!(buf, [5, 10]);
2197 /// let mut state = 100;
2198 /// buf.resize_with(5, || { state += 1; state });
2199 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2201 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2202 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2203 let len = self.len();
2206 self.extend(repeat_with(generator).take(new_len - len))
2208 self.truncate(new_len);
2212 /// Rearranges the internal storage of this deque so it is one contiguous
2213 /// slice, which is then returned.
2215 /// This method does not allocate and does not change the order of the
2216 /// inserted elements. As it returns a mutable slice, this can be used to
2219 /// Once the internal storage is contiguous, the [`as_slices`] and
2220 /// [`as_mut_slices`] methods will return the entire contents of the
2221 /// `VecDeque` in a single slice.
2223 /// [`as_slices`]: VecDeque::as_slices
2224 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2228 /// Sorting the content of a deque.
2231 /// use std::collections::VecDeque;
2233 /// let mut buf = VecDeque::with_capacity(15);
2235 /// buf.push_back(2);
2236 /// buf.push_back(1);
2237 /// buf.push_front(3);
2239 /// // sorting the deque
2240 /// buf.make_contiguous().sort();
2241 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2243 /// // sorting it in reverse order
2244 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2245 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2248 /// Getting immutable access to the contiguous slice.
2251 /// use std::collections::VecDeque;
2253 /// let mut buf = VecDeque::new();
2255 /// buf.push_back(2);
2256 /// buf.push_back(1);
2257 /// buf.push_front(3);
2259 /// buf.make_contiguous();
2260 /// if let (slice, &[]) = buf.as_slices() {
2261 /// // we can now be sure that `slice` contains all elements of the deque,
2262 /// // while still having immutable access to `buf`.
2263 /// assert_eq!(buf.len(), slice.len());
2264 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2267 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2268 pub fn make_contiguous(&mut self) -> &mut [T] {
2269 if self.is_contiguous() {
2270 let tail = self.tail;
2271 let head = self.head;
2272 return unsafe { RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0 };
2275 let buf = self.buf.ptr();
2276 let cap = self.cap();
2277 let len = self.len();
2279 let free = self.tail - self.head;
2280 let tail_len = cap - self.tail;
2282 if free >= tail_len {
2283 // there is enough free space to copy the tail in one go,
2284 // this means that we first shift the head backwards, and then
2285 // copy the tail to the correct position.
2287 // from: DEFGH....ABC
2290 ptr::copy(buf, buf.add(tail_len), self.head);
2292 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2298 } else if free > self.head {
2299 // FIXME: We currently do not consider ....ABCDEFGH
2300 // to be contiguous because `head` would be `0` in this
2301 // case. While we probably want to change this it
2302 // isn't trivial as a few places expect `is_contiguous`
2303 // to mean that we can just slice using `buf[tail..head]`.
2305 // there is enough free space to copy the head in one go,
2306 // this means that we first shift the tail forwards, and then
2307 // copy the head to the correct position.
2309 // from: FGH....ABCDE
2312 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2314 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2317 self.tail = self.head;
2318 self.head = self.wrap_add(self.tail, len);
2321 // free is smaller than both head and tail,
2322 // this means we have to slowly "swap" the tail and the head.
2324 // from: EFGHI...ABCD or HIJK.ABCDEFG
2325 // to: ABCDEFGHI... or ABCDEFGHIJK.
2326 let mut left_edge: usize = 0;
2327 let mut right_edge: usize = self.tail;
2329 // The general problem looks like this
2330 // GHIJKLM...ABCDEF - before any swaps
2331 // ABCDEFM...GHIJKL - after 1 pass of swaps
2332 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2333 // - then restart the algorithm with a new (smaller) store
2334 // Sometimes the temp store is reached when the right edge is at the end
2335 // of the buffer - this means we've hit the right order with fewer swaps!
2338 // ABCDEF.. - after four only swaps we've finished
2339 while left_edge < len && right_edge != cap {
2340 let mut right_offset = 0;
2341 for i in left_edge..right_edge {
2342 right_offset = (i - left_edge) % (cap - right_edge);
2343 let src: isize = (right_edge + right_offset) as isize;
2344 ptr::swap(buf.add(i), buf.offset(src));
2346 let n_ops = right_edge - left_edge;
2348 right_edge += right_offset + 1;
2356 let tail = self.tail;
2357 let head = self.head;
2358 unsafe { RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0 }
2361 /// Rotates the double-ended queue `mid` places to the left.
2364 /// - Rotates item `mid` into the first position.
2365 /// - Pops the first `mid` items and pushes them to the end.
2366 /// - Rotates `len() - mid` places to the right.
2370 /// If `mid` is greater than `len()`. Note that `mid == len()`
2371 /// does _not_ panic and is a no-op rotation.
2375 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2380 /// use std::collections::VecDeque;
2382 /// let mut buf: VecDeque<_> = (0..10).collect();
2384 /// buf.rotate_left(3);
2385 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2387 /// for i in 1..10 {
2388 /// assert_eq!(i * 3 % 10, buf[0]);
2389 /// buf.rotate_left(3);
2391 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2393 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2394 pub fn rotate_left(&mut self, mid: usize) {
2395 assert!(mid <= self.len());
2396 let k = self.len() - mid;
2398 unsafe { self.rotate_left_inner(mid) }
2400 unsafe { self.rotate_right_inner(k) }
2404 /// Rotates the double-ended queue `k` places to the right.
2407 /// - Rotates the first item into position `k`.
2408 /// - Pops the last `k` items and pushes them to the front.
2409 /// - Rotates `len() - k` places to the left.
2413 /// If `k` is greater than `len()`. Note that `k == len()`
2414 /// does _not_ panic and is a no-op rotation.
2418 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2423 /// use std::collections::VecDeque;
2425 /// let mut buf: VecDeque<_> = (0..10).collect();
2427 /// buf.rotate_right(3);
2428 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2430 /// for i in 1..10 {
2431 /// assert_eq!(0, buf[i * 3 % 10]);
2432 /// buf.rotate_right(3);
2434 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2436 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2437 pub fn rotate_right(&mut self, k: usize) {
2438 assert!(k <= self.len());
2439 let mid = self.len() - k;
2441 unsafe { self.rotate_right_inner(k) }
2443 unsafe { self.rotate_left_inner(mid) }
2447 // SAFETY: the following two methods require that the rotation amount
2448 // be less than half the length of the deque.
2450 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2451 // but than `min` is never more than half the capacity, regardless of x,
2452 // so it's sound to call here because we're calling with something
2453 // less than half the length, which is never above half the capacity.
2455 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2456 debug_assert!(mid * 2 <= self.len());
2458 self.wrap_copy(self.head, self.tail, mid);
2460 self.head = self.wrap_add(self.head, mid);
2461 self.tail = self.wrap_add(self.tail, mid);
2464 unsafe fn rotate_right_inner(&mut self, k: usize) {
2465 debug_assert!(k * 2 <= self.len());
2466 self.head = self.wrap_sub(self.head, k);
2467 self.tail = self.wrap_sub(self.tail, k);
2469 self.wrap_copy(self.tail, self.head, k);
2473 /// Binary searches this sorted `VecDeque` for a given element.
2475 /// If the value is found then [`Result::Ok`] is returned, containing the
2476 /// index of the matching element. If there are multiple matches, then any
2477 /// one of the matches could be returned. If the value is not found then
2478 /// [`Result::Err`] is returned, containing the index where a matching
2479 /// element could be inserted while maintaining sorted order.
2481 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2483 /// [`binary_search_by`]: VecDeque::binary_search_by
2484 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2485 /// [`partition_point`]: VecDeque::partition_point
2489 /// Looks up a series of four elements. The first is found, with a
2490 /// uniquely determined position; the second and third are not
2491 /// found; the fourth could match any position in `[1, 4]`.
2494 /// use std::collections::VecDeque;
2496 /// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2498 /// assert_eq!(deque.binary_search(&13), Ok(9));
2499 /// assert_eq!(deque.binary_search(&4), Err(7));
2500 /// assert_eq!(deque.binary_search(&100), Err(13));
2501 /// let r = deque.binary_search(&1);
2502 /// assert!(matches!(r, Ok(1..=4)));
2505 /// If you want to insert an item to a sorted `VecDeque`, while maintaining
2509 /// use std::collections::VecDeque;
2511 /// let mut deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2513 /// let idx = deque.binary_search(&num).unwrap_or_else(|x| x);
2514 /// deque.insert(idx, num);
2515 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2517 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2519 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2523 self.binary_search_by(|e| e.cmp(x))
2526 /// Binary searches this sorted `VecDeque` with a comparator function.
2528 /// The comparator function should implement an order consistent
2529 /// with the sort order of the underlying `VecDeque`, returning an
2530 /// order code that indicates whether its argument is `Less`,
2531 /// `Equal` or `Greater` than the desired target.
2533 /// If the value is found then [`Result::Ok`] is returned, containing the
2534 /// index of the matching element. If there are multiple matches, then any
2535 /// one of the matches could be returned. If the value is not found then
2536 /// [`Result::Err`] is returned, containing the index where a matching
2537 /// element could be inserted while maintaining sorted order.
2539 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2541 /// [`binary_search`]: VecDeque::binary_search
2542 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2543 /// [`partition_point`]: VecDeque::partition_point
2547 /// Looks up a series of four elements. The first is found, with a
2548 /// uniquely determined position; the second and third are not
2549 /// found; the fourth could match any position in `[1, 4]`.
2552 /// use std::collections::VecDeque;
2554 /// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2556 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2557 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2558 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2559 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2560 /// assert!(matches!(r, Ok(1..=4)));
2562 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2563 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2565 F: FnMut(&'a T) -> Ordering,
2567 let (front, back) = self.as_slices();
2568 let cmp_back = back.first().map(|elem| f(elem));
2570 if let Some(Ordering::Equal) = cmp_back {
2572 } else if let Some(Ordering::Less) = cmp_back {
2573 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2575 front.binary_search_by(f)
2579 /// Binary searches this sorted `VecDeque` with a key extraction function.
2581 /// Assumes that the `VecDeque` is sorted by the key, for instance with
2582 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2584 /// If the value is found then [`Result::Ok`] is returned, containing the
2585 /// index of the matching element. If there are multiple matches, then any
2586 /// one of the matches could be returned. If the value is not found then
2587 /// [`Result::Err`] is returned, containing the index where a matching
2588 /// element could be inserted while maintaining sorted order.
2590 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2592 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2593 /// [`binary_search`]: VecDeque::binary_search
2594 /// [`binary_search_by`]: VecDeque::binary_search_by
2595 /// [`partition_point`]: VecDeque::partition_point
2599 /// Looks up a series of four elements in a slice of pairs sorted by
2600 /// their second elements. The first is found, with a uniquely
2601 /// determined position; the second and third are not found; the
2602 /// fourth could match any position in `[1, 4]`.
2605 /// use std::collections::VecDeque;
2607 /// let deque: VecDeque<_> = vec![(0, 0), (2, 1), (4, 1), (5, 1),
2608 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2609 /// (1, 21), (2, 34), (4, 55)].into();
2611 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2612 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2613 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2614 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2615 /// assert!(matches!(r, Ok(1..=4)));
2617 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2619 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2621 F: FnMut(&'a T) -> B,
2624 self.binary_search_by(|k| f(k).cmp(b))
2627 /// Returns the index of the partition point according to the given predicate
2628 /// (the index of the first element of the second partition).
2630 /// The deque is assumed to be partitioned according to the given predicate.
2631 /// This means that all elements for which the predicate returns true are at the start of the deque
2632 /// and all elements for which the predicate returns false are at the end.
2633 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2634 /// (all odd numbers are at the start, all even at the end).
2636 /// If this deque is not partitioned, the returned result is unspecified and meaningless,
2637 /// as this method performs a kind of binary search.
2639 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2641 /// [`binary_search`]: VecDeque::binary_search
2642 /// [`binary_search_by`]: VecDeque::binary_search_by
2643 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2648 /// use std::collections::VecDeque;
2650 /// let deque: VecDeque<_> = vec![1, 2, 3, 3, 5, 6, 7].into();
2651 /// let i = deque.partition_point(|&x| x < 5);
2653 /// assert_eq!(i, 4);
2654 /// assert!(deque.iter().take(i).all(|&x| x < 5));
2655 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2657 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2658 pub fn partition_point<P>(&self, mut pred: P) -> usize
2660 P: FnMut(&T) -> bool,
2662 let (front, back) = self.as_slices();
2664 if let Some(true) = back.first().map(|v| pred(v)) {
2665 back.partition_point(pred) + front.len()
2667 front.partition_point(pred)
2672 impl<T: Clone, A: Allocator> VecDeque<T, A> {
2673 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2674 /// either by removing excess elements from the back or by appending clones of `value`
2680 /// use std::collections::VecDeque;
2682 /// let mut buf = VecDeque::new();
2683 /// buf.push_back(5);
2684 /// buf.push_back(10);
2685 /// buf.push_back(15);
2686 /// assert_eq!(buf, [5, 10, 15]);
2688 /// buf.resize(2, 0);
2689 /// assert_eq!(buf, [5, 10]);
2691 /// buf.resize(5, 20);
2692 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2694 #[stable(feature = "deque_extras", since = "1.16.0")]
2695 pub fn resize(&mut self, new_len: usize, value: T) {
2696 self.resize_with(new_len, || value.clone());
2700 /// Returns the index in the underlying buffer for a given logical element index.
2702 fn wrap_index(index: usize, size: usize) -> usize {
2703 // size is always a power of 2
2704 debug_assert!(size.is_power_of_two());
2708 /// Calculate the number of elements left to be read in the buffer
2710 fn count(tail: usize, head: usize, size: usize) -> usize {
2711 // size is always a power of 2
2712 (head.wrapping_sub(tail)) & (size - 1)
2715 #[stable(feature = "rust1", since = "1.0.0")]
2716 impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
2717 fn eq(&self, other: &Self) -> bool {
2718 if self.len() != other.len() {
2721 let (sa, sb) = self.as_slices();
2722 let (oa, ob) = other.as_slices();
2723 if sa.len() == oa.len() {
2724 sa == oa && sb == ob
2725 } else if sa.len() < oa.len() {
2726 // Always divisible in three sections, for example:
2727 // self: [a b c|d e f]
2728 // other: [0 1 2 3|4 5]
2729 // front = 3, mid = 1,
2730 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2731 let front = sa.len();
2732 let mid = oa.len() - front;
2734 let (oa_front, oa_mid) = oa.split_at(front);
2735 let (sb_mid, sb_back) = sb.split_at(mid);
2736 debug_assert_eq!(sa.len(), oa_front.len());
2737 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2738 debug_assert_eq!(sb_back.len(), ob.len());
2739 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2741 let front = oa.len();
2742 let mid = sa.len() - front;
2744 let (sa_front, sa_mid) = sa.split_at(front);
2745 let (ob_mid, ob_back) = ob.split_at(mid);
2746 debug_assert_eq!(sa_front.len(), oa.len());
2747 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2748 debug_assert_eq!(sb.len(), ob_back.len());
2749 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2754 #[stable(feature = "rust1", since = "1.0.0")]
2755 impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
2757 __impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2758 __impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2759 __impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2760 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2761 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2762 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2764 #[stable(feature = "rust1", since = "1.0.0")]
2765 impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
2766 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2767 self.iter().partial_cmp(other.iter())
2771 #[stable(feature = "rust1", since = "1.0.0")]
2772 impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
2774 fn cmp(&self, other: &Self) -> Ordering {
2775 self.iter().cmp(other.iter())
2779 #[stable(feature = "rust1", since = "1.0.0")]
2780 impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
2781 fn hash<H: Hasher>(&self, state: &mut H) {
2782 self.len().hash(state);
2783 // It's not possible to use Hash::hash_slice on slices
2784 // returned by as_slices method as their length can vary
2785 // in otherwise identical deques.
2787 // Hasher only guarantees equivalence for the exact same
2788 // set of calls to its methods.
2789 self.iter().for_each(|elem| elem.hash(state));
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
2798 fn index(&self, index: usize) -> &T {
2799 self.get(index).expect("Out of bounds access")
2803 #[stable(feature = "rust1", since = "1.0.0")]
2804 impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
2806 fn index_mut(&mut self, index: usize) -> &mut T {
2807 self.get_mut(index).expect("Out of bounds access")
2811 #[stable(feature = "rust1", since = "1.0.0")]
2812 impl<T> FromIterator<T> for VecDeque<T> {
2813 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
2814 let iterator = iter.into_iter();
2815 let (lower, _) = iterator.size_hint();
2816 let mut deq = VecDeque::with_capacity(lower);
2817 deq.extend(iterator);
2822 #[stable(feature = "rust1", since = "1.0.0")]
2823 impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
2825 type IntoIter = IntoIter<T, A>;
2827 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2829 fn into_iter(self) -> IntoIter<T, A> {
2830 IntoIter { inner: self }
2834 #[stable(feature = "rust1", since = "1.0.0")]
2835 impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
2837 type IntoIter = Iter<'a, T>;
2839 fn into_iter(self) -> Iter<'a, T> {
2844 #[stable(feature = "rust1", since = "1.0.0")]
2845 impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
2846 type Item = &'a mut T;
2847 type IntoIter = IterMut<'a, T>;
2849 fn into_iter(self) -> IterMut<'a, T> {
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
2856 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2857 // This function should be the moral equivalent of:
2859 // for item in iter.into_iter() {
2860 // self.push_back(item);
2862 let mut iter = iter.into_iter();
2863 while let Some(element) = iter.next() {
2864 if self.len() == self.capacity() {
2865 let (lower, _) = iter.size_hint();
2866 self.reserve(lower.saturating_add(1));
2869 let head = self.head;
2870 self.head = self.wrap_add(self.head, 1);
2872 self.buffer_write(head, element);
2878 fn extend_one(&mut self, elem: T) {
2879 self.push_back(elem);
2883 fn extend_reserve(&mut self, additional: usize) {
2884 self.reserve(additional);
2888 #[stable(feature = "extend_ref", since = "1.2.0")]
2889 impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
2890 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2891 self.extend(iter.into_iter().cloned());
2895 fn extend_one(&mut self, &elem: &T) {
2896 self.push_back(elem);
2900 fn extend_reserve(&mut self, additional: usize) {
2901 self.reserve(additional);
2905 #[stable(feature = "rust1", since = "1.0.0")]
2906 impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
2907 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2908 f.debug_list().entries(self).finish()
2912 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2913 impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
2914 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2916 /// [`Vec<T>`]: crate::vec::Vec
2917 /// [`VecDeque<T>`]: crate::collections::VecDeque
2919 /// This avoids reallocating where possible, but the conditions for that are
2920 /// strict, and subject to change, and so shouldn't be relied upon unless the
2921 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
2922 fn from(mut other: Vec<T, A>) -> Self {
2923 let len = other.len();
2924 if mem::size_of::<T>() == 0 {
2925 // There's no actual allocation for ZSTs to worry about capacity,
2926 // but `VecDeque` can't handle as much length as `Vec`.
2927 assert!(len < MAXIMUM_ZST_CAPACITY, "capacity overflow");
2929 // We need to resize if the capacity is not a power of two, too small or
2930 // doesn't have at least one free space. We do this while it's still in
2931 // the `Vec` so the items will drop on panic.
2932 let min_cap = cmp::max(MINIMUM_CAPACITY, len) + 1;
2933 let cap = cmp::max(min_cap, other.capacity()).next_power_of_two();
2934 if other.capacity() != cap {
2935 other.reserve_exact(cap - len);
2940 let (other_buf, len, capacity, alloc) = other.into_raw_parts_with_alloc();
2941 let buf = RawVec::from_raw_parts_in(other_buf, capacity, alloc);
2942 VecDeque { tail: 0, head: len, buf }
2947 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2948 impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
2949 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2951 /// [`Vec<T>`]: crate::vec::Vec
2952 /// [`VecDeque<T>`]: crate::collections::VecDeque
2954 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
2955 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2960 /// use std::collections::VecDeque;
2962 /// // This one is *O*(1).
2963 /// let deque: VecDeque<_> = (1..5).collect();
2964 /// let ptr = deque.as_slices().0.as_ptr();
2965 /// let vec = Vec::from(deque);
2966 /// assert_eq!(vec, [1, 2, 3, 4]);
2967 /// assert_eq!(vec.as_ptr(), ptr);
2969 /// // This one needs data rearranging.
2970 /// let mut deque: VecDeque<_> = (1..5).collect();
2971 /// deque.push_front(9);
2972 /// deque.push_front(8);
2973 /// let ptr = deque.as_slices().1.as_ptr();
2974 /// let vec = Vec::from(deque);
2975 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2976 /// assert_eq!(vec.as_ptr(), ptr);
2978 fn from(mut other: VecDeque<T, A>) -> Self {
2979 other.make_contiguous();
2982 let other = ManuallyDrop::new(other);
2983 let buf = other.buf.ptr();
2984 let len = other.len();
2985 let cap = other.cap();
2986 let alloc = ptr::read(other.allocator());
2988 if other.tail != 0 {
2989 ptr::copy(buf.add(other.tail), buf, len);
2991 Vec::from_raw_parts_in(buf, len, cap, alloc)
2996 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
2997 impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
2999 /// use std::collections::VecDeque;
3001 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
3002 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
3003 /// assert_eq!(deq1, deq2);
3005 fn from(arr: [T; N]) -> Self {
3006 core::array::IntoIter::new(arr).collect()