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 // ignore-tidy-filelength
13 use core::cmp::{self, Ordering};
15 use core::hash::{Hash, Hasher};
16 use core::iter::{repeat_with, FromIterator, FusedIterator};
17 use core::marker::PhantomData;
18 use core::mem::{self, replace, ManuallyDrop};
19 use core::ops::{Index, IndexMut, Range, RangeBounds, Try};
20 use core::ptr::{self, NonNull};
23 use crate::collections::TryReserveError;
24 use crate::raw_vec::RawVec;
27 #[stable(feature = "drain", since = "1.6.0")]
28 pub use self::drain::Drain;
35 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
36 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
38 const MAXIMUM_ZST_CAPACITY: usize = 1 << (core::mem::size_of::<usize>() * 8 - 1); // Largest possible power of two
40 /// A double-ended queue implemented with a growable ring buffer.
42 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
43 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
44 /// push onto the back in this manner, and iterating over `VecDeque` goes front
47 /// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
48 /// in memory. If you want to access the elements as a single slice, such as for
49 /// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
50 /// so that its elements do not wrap, and returns a mutable slice to the
51 /// now-contiguous element sequence.
53 /// [`push_back`]: VecDeque::push_back
54 /// [`pop_front`]: VecDeque::pop_front
55 /// [`extend`]: VecDeque::extend
56 /// [`append`]: VecDeque::append
57 /// [`make_contiguous`]: VecDeque::make_contiguous
58 #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_type")]
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub struct VecDeque<T> {
61 // tail and head are pointers into the buffer. Tail always points
62 // to the first element that could be read, Head always points
63 // to where data should be written.
64 // If tail == head the buffer is empty. The length of the ringbuffer
65 // is defined as the distance between the two.
71 /// PairSlices pairs up equal length slice parts of two deques
73 /// For example, given deques "A" and "B" with the following division into slices:
75 /// A: [0 1 2] [3 4 5]
78 /// It produces the following sequence of matching slices:
84 /// and the uneven remainder of either A or B is skipped.
85 struct PairSlices<'a, 'b, T> {
92 impl<'a, 'b, T> PairSlices<'a, 'b, T> {
93 fn from(to: &'a mut VecDeque<T>, from: &'b VecDeque<T>) -> Self {
94 let (a0, a1) = to.as_mut_slices();
95 let (b0, b1) = from.as_slices();
96 PairSlices { a0, a1, b0, b1 }
99 fn has_remainder(&self) -> bool {
103 fn remainder(self) -> impl Iterator<Item = &'b [T]> {
104 array::IntoIter::new([self.b0, self.b1])
108 impl<'a, 'b, T> Iterator for PairSlices<'a, 'b, T> {
109 type Item = (&'a mut [T], &'b [T]);
110 fn next(&mut self) -> Option<Self::Item> {
111 // Get next part length
112 let part = cmp::min(self.a0.len(), self.b0.len());
116 let (p0, p1) = replace(&mut self.a0, &mut []).split_at_mut(part);
117 let (q0, q1) = self.b0.split_at(part);
119 // Move a1 into a0, if it's empty (and b1, b0 the same way).
122 if self.a0.is_empty() {
123 self.a0 = replace(&mut self.a1, &mut []);
125 if self.b0.is_empty() {
126 self.b0 = replace(&mut self.b1, &[]);
132 #[stable(feature = "rust1", since = "1.0.0")]
133 impl<T: Clone> Clone for VecDeque<T> {
134 fn clone(&self) -> VecDeque<T> {
135 self.iter().cloned().collect()
138 fn clone_from(&mut self, other: &Self) {
139 self.truncate(other.len());
141 let mut iter = PairSlices::from(self, other);
142 while let Some((dst, src)) = iter.next() {
143 dst.clone_from_slice(&src);
146 if iter.has_remainder() {
147 for remainder in iter.remainder() {
148 self.extend(remainder.iter().cloned());
154 #[stable(feature = "rust1", since = "1.0.0")]
155 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
157 /// Runs the destructor for all items in the slice when it gets dropped (normally or
158 /// during unwinding).
159 struct Dropper<'a, T>(&'a mut [T]);
161 impl<'a, T> Drop for Dropper<'a, T> {
164 ptr::drop_in_place(self.0);
169 let (front, back) = self.as_mut_slices();
171 let _back_dropper = Dropper(back);
173 ptr::drop_in_place(front);
175 // RawVec handles deallocation
179 #[stable(feature = "rust1", since = "1.0.0")]
180 impl<T> Default for VecDeque<T> {
181 /// Creates an empty `VecDeque<T>`.
183 fn default() -> VecDeque<T> {
188 impl<T> VecDeque<T> {
189 /// Marginally more convenient
191 fn ptr(&self) -> *mut T {
195 /// Marginally more convenient
197 fn cap(&self) -> usize {
198 if mem::size_of::<T>() == 0 {
199 // For zero sized types, we are always at maximum capacity
206 /// Turn ptr into a slice
208 unsafe fn buffer_as_slice(&self) -> &[T] {
209 unsafe { slice::from_raw_parts(self.ptr(), self.cap()) }
212 /// Turn ptr into a mut slice
214 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
215 unsafe { slice::from_raw_parts_mut(self.ptr(), self.cap()) }
218 /// Moves an element out of the buffer
220 unsafe fn buffer_read(&mut self, off: usize) -> T {
221 unsafe { ptr::read(self.ptr().add(off)) }
224 /// Writes an element into the buffer, moving it.
226 unsafe fn buffer_write(&mut self, off: usize, value: T) {
228 ptr::write(self.ptr().add(off), value);
232 /// Returns `true` if the buffer is at full capacity.
234 fn is_full(&self) -> bool {
235 self.cap() - self.len() == 1
238 /// Returns the index in the underlying buffer for a given logical element
241 fn wrap_index(&self, idx: usize) -> usize {
242 wrap_index(idx, self.cap())
245 /// Returns the index in the underlying buffer for a given logical element
248 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
249 wrap_index(idx.wrapping_add(addend), self.cap())
252 /// Returns the index in the underlying buffer for a given logical element
253 /// index - subtrahend.
255 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
256 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
259 /// Copies a contiguous block of memory len long from src to dst
261 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
263 dst + len <= self.cap(),
264 "cpy dst={} src={} len={} cap={}",
271 src + len <= self.cap(),
272 "cpy dst={} src={} len={} cap={}",
279 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
283 /// Copies a contiguous block of memory len long from src to dst
285 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
287 dst + len <= self.cap(),
288 "cno dst={} src={} len={} cap={}",
295 src + len <= self.cap(),
296 "cno dst={} src={} len={} cap={}",
303 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
307 /// Copies a potentially wrapping block of memory len long from src to dest.
308 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
309 /// most one continuous overlapping region between src and dest).
310 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
312 fn diff(a: usize, b: usize) -> usize {
313 if a <= b { b - a } else { a - b }
316 cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
317 "wrc dst={} src={} len={} cap={}",
324 if src == dst || len == 0 {
328 let dst_after_src = self.wrap_sub(dst, src) < len;
330 let src_pre_wrap_len = self.cap() - src;
331 let dst_pre_wrap_len = self.cap() - dst;
332 let src_wraps = src_pre_wrap_len < len;
333 let dst_wraps = dst_pre_wrap_len < len;
335 match (dst_after_src, src_wraps, dst_wraps) {
336 (_, false, false) => {
337 // src doesn't wrap, dst doesn't wrap
340 // 1 [_ _ A A B B C C _]
341 // 2 [_ _ A A A A B B _]
345 self.copy(dst, src, len);
348 (false, false, true) => {
349 // dst before src, src doesn't wrap, dst wraps
352 // 1 [A A B B _ _ _ C C]
353 // 2 [A A B B _ _ _ A A]
354 // 3 [B B B B _ _ _ A A]
358 self.copy(dst, src, dst_pre_wrap_len);
359 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
362 (true, false, true) => {
363 // src before dst, src doesn't wrap, dst wraps
366 // 1 [C C _ _ _ A A B B]
367 // 2 [B B _ _ _ A A B B]
368 // 3 [B B _ _ _ A A A A]
372 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
373 self.copy(dst, src, dst_pre_wrap_len);
376 (false, true, false) => {
377 // dst before src, src wraps, dst doesn't wrap
380 // 1 [C C _ _ _ A A B B]
381 // 2 [C C _ _ _ B B B B]
382 // 3 [C C _ _ _ B B C C]
386 self.copy(dst, src, src_pre_wrap_len);
387 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
390 (true, true, false) => {
391 // src before dst, src wraps, dst doesn't wrap
394 // 1 [A A B B _ _ _ C C]
395 // 2 [A A A A _ _ _ C C]
396 // 3 [C C A A _ _ _ C C]
400 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
401 self.copy(dst, src, src_pre_wrap_len);
404 (false, true, true) => {
405 // dst before src, src wraps, dst wraps
408 // 1 [A B C D _ E F G H]
409 // 2 [A B C D _ E G H H]
410 // 3 [A B C D _ E G H A]
411 // 4 [B C C D _ E G H A]
414 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
415 let delta = dst_pre_wrap_len - src_pre_wrap_len;
417 self.copy(dst, src, src_pre_wrap_len);
418 self.copy(dst + src_pre_wrap_len, 0, delta);
419 self.copy(0, delta, len - dst_pre_wrap_len);
422 (true, true, true) => {
423 // src before dst, src wraps, dst wraps
426 // 1 [A B C D _ E F G H]
427 // 2 [A A B D _ E F G H]
428 // 3 [H A B D _ E F G H]
429 // 4 [H A B D _ E F F G]
432 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
433 let delta = src_pre_wrap_len - dst_pre_wrap_len;
435 self.copy(delta, 0, len - src_pre_wrap_len);
436 self.copy(0, self.cap() - delta, delta);
437 self.copy(dst, src, dst_pre_wrap_len);
443 /// Frobs the head and tail sections around to handle the fact that we
444 /// just reallocated. Unsafe because it trusts old_capacity.
446 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
447 let new_capacity = self.cap();
449 // Move the shortest contiguous section of the ring buffer
451 // [o o o o o o o . ]
453 // A [o o o o o o o . . . . . . . . . ]
455 // [o o . o o o o o ]
457 // B [. . . o o o o o o o . . . . . . ]
459 // [o o o o o . o o ]
461 // C [o o o o o . . . . . . . . . o o ]
463 if self.tail <= self.head {
466 } else if self.head < old_capacity - self.tail {
469 self.copy_nonoverlapping(old_capacity, 0, self.head);
471 self.head += old_capacity;
472 debug_assert!(self.head > self.tail);
475 let new_tail = new_capacity - (old_capacity - self.tail);
477 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
479 self.tail = new_tail;
480 debug_assert!(self.head < self.tail);
482 debug_assert!(self.head < self.cap());
483 debug_assert!(self.tail < self.cap());
484 debug_assert!(self.cap().count_ones() == 1);
488 impl<T> VecDeque<T> {
489 /// Creates an empty `VecDeque`.
494 /// use std::collections::VecDeque;
496 /// let vector: VecDeque<u32> = VecDeque::new();
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn new() -> VecDeque<T> {
500 VecDeque::with_capacity(INITIAL_CAPACITY)
503 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
508 /// use std::collections::VecDeque;
510 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
512 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
514 // +1 since the ringbuffer always leaves one space empty
515 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
516 assert!(cap > capacity, "capacity overflow");
518 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity(cap) }
521 /// Provides a reference to the element at the given index.
523 /// Element at index 0 is the front of the queue.
528 /// use std::collections::VecDeque;
530 /// let mut buf = VecDeque::new();
531 /// buf.push_back(3);
532 /// buf.push_back(4);
533 /// buf.push_back(5);
534 /// assert_eq!(buf.get(1), Some(&4));
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn get(&self, index: usize) -> Option<&T> {
538 if index < self.len() {
539 let idx = self.wrap_add(self.tail, index);
540 unsafe { Some(&*self.ptr().add(idx)) }
546 /// Provides a mutable reference to the element at the given index.
548 /// Element at index 0 is the front of the queue.
553 /// use std::collections::VecDeque;
555 /// let mut buf = VecDeque::new();
556 /// buf.push_back(3);
557 /// buf.push_back(4);
558 /// buf.push_back(5);
559 /// if let Some(elem) = buf.get_mut(1) {
563 /// assert_eq!(buf[1], 7);
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
567 if index < self.len() {
568 let idx = self.wrap_add(self.tail, index);
569 unsafe { Some(&mut *self.ptr().add(idx)) }
575 /// Swaps elements at indices `i` and `j`.
577 /// `i` and `j` may be equal.
579 /// Element at index 0 is the front of the queue.
583 /// Panics if either index is out of bounds.
588 /// use std::collections::VecDeque;
590 /// let mut buf = VecDeque::new();
591 /// buf.push_back(3);
592 /// buf.push_back(4);
593 /// buf.push_back(5);
594 /// assert_eq!(buf, [3, 4, 5]);
596 /// assert_eq!(buf, [5, 4, 3]);
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub fn swap(&mut self, i: usize, j: usize) {
600 assert!(i < self.len());
601 assert!(j < self.len());
602 let ri = self.wrap_add(self.tail, i);
603 let rj = self.wrap_add(self.tail, j);
604 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
607 /// Returns the number of elements the `VecDeque` can hold without
613 /// use std::collections::VecDeque;
615 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
616 /// assert!(buf.capacity() >= 10);
619 #[stable(feature = "rust1", since = "1.0.0")]
620 pub fn capacity(&self) -> usize {
624 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
625 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
627 /// Note that the allocator may give the collection more space than it requests. Therefore
628 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
629 /// insertions are expected.
633 /// Panics if the new capacity overflows `usize`.
638 /// use std::collections::VecDeque;
640 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
641 /// buf.reserve_exact(10);
642 /// assert!(buf.capacity() >= 11);
645 /// [`reserve`]: VecDeque::reserve
646 #[stable(feature = "rust1", since = "1.0.0")]
647 pub fn reserve_exact(&mut self, additional: usize) {
648 self.reserve(additional);
651 /// Reserves capacity for at least `additional` more elements to be inserted in the given
652 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
656 /// Panics if the new capacity overflows `usize`.
661 /// use std::collections::VecDeque;
663 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
665 /// assert!(buf.capacity() >= 11);
667 #[stable(feature = "rust1", since = "1.0.0")]
668 pub fn reserve(&mut self, additional: usize) {
669 let old_cap = self.cap();
670 let used_cap = self.len() + 1;
671 let new_cap = used_cap
672 .checked_add(additional)
673 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
674 .expect("capacity overflow");
676 if new_cap > old_cap {
677 self.buf.reserve_exact(used_cap, new_cap - used_cap);
679 self.handle_capacity_increase(old_cap);
684 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
685 /// be inserted in the given `VecDeque<T>`. After calling `try_reserve_exact`,
686 /// capacity will be greater than or equal to `self.len() + additional`.
687 /// Does nothing if the capacity is already sufficient.
689 /// Note that the allocator may give the collection more space than it
690 /// requests. Therefore, capacity can not be relied upon to be precisely
691 /// minimal. Prefer `reserve` if future insertions are expected.
695 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
701 /// #![feature(try_reserve)]
702 /// use std::collections::TryReserveError;
703 /// use std::collections::VecDeque;
705 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
706 /// let mut output = VecDeque::new();
708 /// // Pre-reserve the memory, exiting if we can't
709 /// output.try_reserve_exact(data.len())?;
711 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
712 /// output.extend(data.iter().map(|&val| {
713 /// val * 2 + 5 // very complicated
718 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
720 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
721 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
722 self.try_reserve(additional)
725 /// Tries to reserve capacity for at least `additional` more elements to be inserted
726 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
727 /// frequent reallocations. After calling `try_reserve`, capacity will be
728 /// greater than or equal to `self.len() + additional`. Does nothing if
729 /// capacity is already sufficient.
733 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
739 /// #![feature(try_reserve)]
740 /// use std::collections::TryReserveError;
741 /// use std::collections::VecDeque;
743 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
744 /// let mut output = VecDeque::new();
746 /// // Pre-reserve the memory, exiting if we can't
747 /// output.try_reserve(data.len())?;
749 /// // Now we know this can't OOM in the middle of our complex work
750 /// output.extend(data.iter().map(|&val| {
751 /// val * 2 + 5 // very complicated
756 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
758 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
759 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
760 let old_cap = self.cap();
761 let used_cap = self.len() + 1;
762 let new_cap = used_cap
763 .checked_add(additional)
764 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
765 .ok_or(TryReserveError::CapacityOverflow)?;
767 if new_cap > old_cap {
768 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
770 self.handle_capacity_increase(old_cap);
776 /// Shrinks the capacity of the `VecDeque` as much as possible.
778 /// It will drop down as close as possible to the length but the allocator may still inform the
779 /// `VecDeque` that there is space for a few more elements.
784 /// use std::collections::VecDeque;
786 /// let mut buf = VecDeque::with_capacity(15);
787 /// buf.extend(0..4);
788 /// assert_eq!(buf.capacity(), 15);
789 /// buf.shrink_to_fit();
790 /// assert!(buf.capacity() >= 4);
792 #[stable(feature = "deque_extras_15", since = "1.5.0")]
793 pub fn shrink_to_fit(&mut self) {
797 /// Shrinks the capacity of the `VecDeque` with a lower bound.
799 /// The capacity will remain at least as large as both the length
800 /// and the supplied value.
802 /// Panics if the current capacity is smaller than the supplied
803 /// minimum capacity.
808 /// #![feature(shrink_to)]
809 /// use std::collections::VecDeque;
811 /// let mut buf = VecDeque::with_capacity(15);
812 /// buf.extend(0..4);
813 /// assert_eq!(buf.capacity(), 15);
814 /// buf.shrink_to(6);
815 /// assert!(buf.capacity() >= 6);
816 /// buf.shrink_to(0);
817 /// assert!(buf.capacity() >= 4);
819 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
820 pub fn shrink_to(&mut self, min_capacity: usize) {
821 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
823 // +1 since the ringbuffer always leaves one space empty
824 // len + 1 can't overflow for an existing, well-formed ringbuffer.
825 let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
826 .next_power_of_two();
828 if target_cap < self.cap() {
829 // There are three cases of interest:
830 // All elements are out of desired bounds
831 // Elements are contiguous, and head is out of desired bounds
832 // Elements are discontiguous, and tail is out of desired bounds
834 // At all other times, element positions are unaffected.
836 // Indicates that elements at the head should be moved.
837 let head_outside = self.head == 0 || self.head >= target_cap;
838 // Move elements from out of desired bounds (positions after target_cap)
839 if self.tail >= target_cap && head_outside {
841 // [. . . . . . . . o o o o o o o . ]
843 // [o o o o o o o . ]
845 self.copy_nonoverlapping(0, self.tail, self.len());
847 self.head = self.len();
849 } else if self.tail != 0 && self.tail < target_cap && head_outside {
851 // [. . . o o o o o o o . . . . . . ]
853 // [o o . o o o o o ]
854 let len = self.wrap_sub(self.head, target_cap);
856 self.copy_nonoverlapping(0, target_cap, len);
859 debug_assert!(self.head < self.tail);
860 } else if self.tail >= target_cap {
862 // [o o o o o . . . . . . . . . o o ]
864 // [o o o o o . o o ]
865 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
866 let len = self.cap() - self.tail;
867 let new_tail = target_cap - len;
869 self.copy_nonoverlapping(new_tail, self.tail, len);
871 self.tail = new_tail;
872 debug_assert!(self.head < self.tail);
875 self.buf.shrink_to_fit(target_cap);
877 debug_assert!(self.head < self.cap());
878 debug_assert!(self.tail < self.cap());
879 debug_assert!(self.cap().count_ones() == 1);
883 /// Shortens the `VecDeque`, keeping the first `len` elements and dropping
886 /// If `len` is greater than the `VecDeque`'s current length, this has no
892 /// use std::collections::VecDeque;
894 /// let mut buf = VecDeque::new();
895 /// buf.push_back(5);
896 /// buf.push_back(10);
897 /// buf.push_back(15);
898 /// assert_eq!(buf, [5, 10, 15]);
900 /// assert_eq!(buf, [5]);
902 #[stable(feature = "deque_extras", since = "1.16.0")]
903 pub fn truncate(&mut self, len: usize) {
904 /// Runs the destructor for all items in the slice when it gets dropped (normally or
905 /// during unwinding).
906 struct Dropper<'a, T>(&'a mut [T]);
908 impl<'a, T> Drop for Dropper<'a, T> {
911 ptr::drop_in_place(self.0);
918 // * Any slice passed to `drop_in_place` is valid; the second case has
919 // `len <= front.len()` and returning on `len > self.len()` ensures
920 // `begin <= back.len()` in the first case
921 // * The head of the VecDeque is moved before calling `drop_in_place`,
922 // so no value is dropped twice if `drop_in_place` panics
924 if len > self.len() {
927 let num_dropped = self.len() - len;
928 let (front, back) = self.as_mut_slices();
929 if len > front.len() {
930 let begin = len - front.len();
931 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
932 self.head = self.wrap_sub(self.head, num_dropped);
933 ptr::drop_in_place(drop_back);
935 let drop_back = back as *mut _;
936 let drop_front = front.get_unchecked_mut(len..) as *mut _;
937 self.head = self.wrap_sub(self.head, num_dropped);
939 // Make sure the second half is dropped even when a destructor
940 // in the first one panics.
941 let _back_dropper = Dropper(&mut *drop_back);
942 ptr::drop_in_place(drop_front);
947 /// Returns a front-to-back iterator.
952 /// use std::collections::VecDeque;
954 /// let mut buf = VecDeque::new();
955 /// buf.push_back(5);
956 /// buf.push_back(3);
957 /// buf.push_back(4);
958 /// let b: &[_] = &[&5, &3, &4];
959 /// let c: Vec<&i32> = buf.iter().collect();
960 /// assert_eq!(&c[..], b);
962 #[stable(feature = "rust1", since = "1.0.0")]
963 pub fn iter(&self) -> Iter<'_, T> {
964 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } }
967 /// Returns a front-to-back iterator that returns mutable references.
972 /// use std::collections::VecDeque;
974 /// let mut buf = VecDeque::new();
975 /// buf.push_back(5);
976 /// buf.push_back(3);
977 /// buf.push_back(4);
978 /// for num in buf.iter_mut() {
981 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
982 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
984 #[stable(feature = "rust1", since = "1.0.0")]
985 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
986 // SAFETY: The internal `IterMut` safety invariant is established because the
987 // `ring` we create is a dereferencable slice for lifetime '_.
991 ring: ptr::slice_from_raw_parts_mut(self.ptr(), self.cap()),
992 phantom: PhantomData,
996 /// Returns a pair of slices which contain, in order, the contents of the
999 /// If [`make_contiguous`] was previously called, all elements of the
1000 /// `VecDeque` will be in the first slice and the second slice will be empty.
1002 /// [`make_contiguous`]: VecDeque::make_contiguous
1007 /// use std::collections::VecDeque;
1009 /// let mut vector = VecDeque::new();
1011 /// vector.push_back(0);
1012 /// vector.push_back(1);
1013 /// vector.push_back(2);
1015 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
1017 /// vector.push_front(10);
1018 /// vector.push_front(9);
1020 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1023 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1024 pub fn as_slices(&self) -> (&[T], &[T]) {
1026 let buf = self.buffer_as_slice();
1027 RingSlices::ring_slices(buf, self.head, self.tail)
1031 /// Returns a pair of slices which contain, in order, the contents of the
1034 /// If [`make_contiguous`] was previously called, all elements of the
1035 /// `VecDeque` will be in the first slice and the second slice will be empty.
1037 /// [`make_contiguous`]: VecDeque::make_contiguous
1042 /// use std::collections::VecDeque;
1044 /// let mut vector = VecDeque::new();
1046 /// vector.push_back(0);
1047 /// vector.push_back(1);
1049 /// vector.push_front(10);
1050 /// vector.push_front(9);
1052 /// vector.as_mut_slices().0[0] = 42;
1053 /// vector.as_mut_slices().1[0] = 24;
1054 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
1057 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1058 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1060 let head = self.head;
1061 let tail = self.tail;
1062 let buf = self.buffer_as_mut_slice();
1063 RingSlices::ring_slices(buf, head, tail)
1067 /// Returns the number of elements in the `VecDeque`.
1072 /// use std::collections::VecDeque;
1074 /// let mut v = VecDeque::new();
1075 /// assert_eq!(v.len(), 0);
1077 /// assert_eq!(v.len(), 1);
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub fn len(&self) -> usize {
1081 count(self.tail, self.head, self.cap())
1084 /// Returns `true` if the `VecDeque` is empty.
1089 /// use std::collections::VecDeque;
1091 /// let mut v = VecDeque::new();
1092 /// assert!(v.is_empty());
1093 /// v.push_front(1);
1094 /// assert!(!v.is_empty());
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 pub fn is_empty(&self) -> bool {
1098 self.tail == self.head
1101 fn range_tail_head<R>(&self, range: R) -> (usize, usize)
1103 R: RangeBounds<usize>,
1105 let Range { start, end } = range.assert_len(self.len());
1106 let tail = self.wrap_add(self.tail, start);
1107 let head = self.wrap_add(self.tail, end);
1111 /// Creates an iterator that covers the specified range in the `VecDeque`.
1115 /// Panics if the starting point is greater than the end point or if
1116 /// the end point is greater than the length of the vector.
1121 /// #![feature(deque_range)]
1123 /// use std::collections::VecDeque;
1125 /// let v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1126 /// let range = v.range(2..).copied().collect::<VecDeque<_>>();
1127 /// assert_eq!(range, [3]);
1129 /// // A full range covers all contents
1130 /// let all = v.range(..);
1131 /// assert_eq!(all.len(), 3);
1134 #[unstable(feature = "deque_range", issue = "74217")]
1135 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1137 R: RangeBounds<usize>,
1139 let (tail, head) = self.range_tail_head(range);
1143 // The shared reference we have in &self is maintained in the '_ of Iter.
1144 ring: unsafe { self.buffer_as_slice() },
1148 /// Creates an iterator that covers the specified mutable range in the `VecDeque`.
1152 /// Panics if the starting point is greater than the end point or if
1153 /// the end point is greater than the length of the vector.
1158 /// #![feature(deque_range)]
1160 /// use std::collections::VecDeque;
1162 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1163 /// for v in v.range_mut(2..) {
1166 /// assert_eq!(v, vec![1, 2, 6]);
1168 /// // A full range covers all contents
1169 /// for v in v.range_mut(..) {
1172 /// assert_eq!(v, vec![2, 4, 12]);
1175 #[unstable(feature = "deque_range", issue = "74217")]
1176 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1178 R: RangeBounds<usize>,
1180 let (tail, head) = self.range_tail_head(range);
1182 // SAFETY: The internal `IterMut` safety invariant is established because the
1183 // `ring` we create is a dereferencable slice for lifetime '_.
1187 ring: ptr::slice_from_raw_parts_mut(self.ptr(), self.cap()),
1188 phantom: PhantomData,
1192 /// Creates a draining iterator that removes the specified range in the
1193 /// `VecDeque` and yields the removed items.
1195 /// Note 1: The element range is removed even if the iterator is not
1196 /// consumed until the end.
1198 /// Note 2: It is unspecified how many elements are removed from the deque,
1199 /// if the `Drain` value is not dropped, but the borrow it holds expires
1200 /// (e.g., due to `mem::forget`).
1204 /// Panics if the starting point is greater than the end point or if
1205 /// the end point is greater than the length of the vector.
1210 /// use std::collections::VecDeque;
1212 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1213 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
1214 /// assert_eq!(drained, [3]);
1215 /// assert_eq!(v, [1, 2]);
1217 /// // A full range clears all contents
1219 /// assert!(v.is_empty());
1222 #[stable(feature = "drain", since = "1.6.0")]
1223 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1225 R: RangeBounds<usize>,
1229 // When the Drain is first created, the source deque is shortened to
1230 // make sure no uninitialized or moved-from elements are accessible at
1231 // all if the Drain's destructor never gets to run.
1233 // Drain will ptr::read out the values to remove.
1234 // When finished, the remaining data will be copied back to cover the hole,
1235 // and the head/tail values will be restored correctly.
1237 let (drain_tail, drain_head) = self.range_tail_head(range);
1239 // The deque's elements are parted into three segments:
1240 // * self.tail -> drain_tail
1241 // * drain_tail -> drain_head
1242 // * drain_head -> self.head
1244 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1246 // We store drain_tail as self.head, and drain_head and self.head as
1247 // after_tail and after_head respectively on the Drain. This also
1248 // truncates the effective array such that if the Drain is leaked, we
1249 // have forgotten about the potentially moved values after the start of
1253 // [. . . o o x x o o . . .]
1255 let head = self.head;
1257 // "forget" about the values after the start of the drain until after
1258 // the drain is complete and the Drain destructor is run.
1259 self.head = drain_tail;
1262 deque: NonNull::from(&mut *self),
1263 after_tail: drain_head,
1268 // Crucially, we only create shared references from `self` here and read from
1269 // it. We do not write to `self` nor reborrow to a mutable reference.
1270 // Hence the raw pointer we created above, for `deque`, remains valid.
1271 ring: unsafe { self.buffer_as_slice() },
1276 /// Clears the `VecDeque`, removing all values.
1281 /// use std::collections::VecDeque;
1283 /// let mut v = VecDeque::new();
1286 /// assert!(v.is_empty());
1288 #[stable(feature = "rust1", since = "1.0.0")]
1290 pub fn clear(&mut self) {
1294 /// Returns `true` if the `VecDeque` contains an element equal to the
1300 /// use std::collections::VecDeque;
1302 /// let mut vector: VecDeque<u32> = VecDeque::new();
1304 /// vector.push_back(0);
1305 /// vector.push_back(1);
1307 /// assert_eq!(vector.contains(&1), true);
1308 /// assert_eq!(vector.contains(&10), false);
1310 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1311 pub fn contains(&self, x: &T) -> bool
1315 let (a, b) = self.as_slices();
1316 a.contains(x) || b.contains(x)
1319 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1325 /// use std::collections::VecDeque;
1327 /// let mut d = VecDeque::new();
1328 /// assert_eq!(d.front(), None);
1332 /// assert_eq!(d.front(), Some(&1));
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 pub fn front(&self) -> Option<&T> {
1336 if !self.is_empty() { Some(&self[0]) } else { None }
1339 /// Provides a mutable reference to the front element, or `None` if the
1340 /// `VecDeque` is empty.
1345 /// use std::collections::VecDeque;
1347 /// let mut d = VecDeque::new();
1348 /// assert_eq!(d.front_mut(), None);
1352 /// match d.front_mut() {
1353 /// Some(x) => *x = 9,
1356 /// assert_eq!(d.front(), Some(&9));
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 pub fn front_mut(&mut self) -> Option<&mut T> {
1360 if !self.is_empty() { Some(&mut self[0]) } else { None }
1363 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1369 /// use std::collections::VecDeque;
1371 /// let mut d = VecDeque::new();
1372 /// assert_eq!(d.back(), None);
1376 /// assert_eq!(d.back(), Some(&2));
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 pub fn back(&self) -> Option<&T> {
1380 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
1383 /// Provides a mutable reference to the back element, or `None` if the
1384 /// `VecDeque` is empty.
1389 /// use std::collections::VecDeque;
1391 /// let mut d = VecDeque::new();
1392 /// assert_eq!(d.back(), None);
1396 /// match d.back_mut() {
1397 /// Some(x) => *x = 9,
1400 /// assert_eq!(d.back(), Some(&9));
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 pub fn back_mut(&mut self) -> Option<&mut T> {
1404 let len = self.len();
1405 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
1408 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1414 /// use std::collections::VecDeque;
1416 /// let mut d = VecDeque::new();
1420 /// assert_eq!(d.pop_front(), Some(1));
1421 /// assert_eq!(d.pop_front(), Some(2));
1422 /// assert_eq!(d.pop_front(), None);
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 pub fn pop_front(&mut self) -> Option<T> {
1426 if self.is_empty() {
1429 let tail = self.tail;
1430 self.tail = self.wrap_add(self.tail, 1);
1431 unsafe { Some(self.buffer_read(tail)) }
1435 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1441 /// use std::collections::VecDeque;
1443 /// let mut buf = VecDeque::new();
1444 /// assert_eq!(buf.pop_back(), None);
1445 /// buf.push_back(1);
1446 /// buf.push_back(3);
1447 /// assert_eq!(buf.pop_back(), Some(3));
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 pub fn pop_back(&mut self) -> Option<T> {
1451 if self.is_empty() {
1454 self.head = self.wrap_sub(self.head, 1);
1455 let head = self.head;
1456 unsafe { Some(self.buffer_read(head)) }
1460 /// Prepends an element to the `VecDeque`.
1465 /// use std::collections::VecDeque;
1467 /// let mut d = VecDeque::new();
1468 /// d.push_front(1);
1469 /// d.push_front(2);
1470 /// assert_eq!(d.front(), Some(&2));
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub fn push_front(&mut self, value: T) {
1478 self.tail = self.wrap_sub(self.tail, 1);
1479 let tail = self.tail;
1481 self.buffer_write(tail, value);
1485 /// Appends an element to the back of the `VecDeque`.
1490 /// use std::collections::VecDeque;
1492 /// let mut buf = VecDeque::new();
1493 /// buf.push_back(1);
1494 /// buf.push_back(3);
1495 /// assert_eq!(3, *buf.back().unwrap());
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 pub fn push_back(&mut self, value: T) {
1503 let head = self.head;
1504 self.head = self.wrap_add(self.head, 1);
1505 unsafe { self.buffer_write(head, value) }
1509 fn is_contiguous(&self) -> bool {
1510 self.tail <= self.head
1513 /// Removes an element from anywhere in the `VecDeque` and returns it,
1514 /// replacing it with the first element.
1516 /// This does not preserve ordering, but is *O*(1).
1518 /// Returns `None` if `index` is out of bounds.
1520 /// Element at index 0 is the front of the queue.
1525 /// use std::collections::VecDeque;
1527 /// let mut buf = VecDeque::new();
1528 /// assert_eq!(buf.swap_remove_front(0), None);
1529 /// buf.push_back(1);
1530 /// buf.push_back(2);
1531 /// buf.push_back(3);
1532 /// assert_eq!(buf, [1, 2, 3]);
1534 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1535 /// assert_eq!(buf, [2, 1]);
1537 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1538 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1539 let length = self.len();
1540 if length > 0 && index < length && index != 0 {
1541 self.swap(index, 0);
1542 } else if index >= length {
1548 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1551 /// This does not preserve ordering, but is *O*(1).
1553 /// Returns `None` if `index` is out of bounds.
1555 /// Element at index 0 is the front of the queue.
1560 /// use std::collections::VecDeque;
1562 /// let mut buf = VecDeque::new();
1563 /// assert_eq!(buf.swap_remove_back(0), None);
1564 /// buf.push_back(1);
1565 /// buf.push_back(2);
1566 /// buf.push_back(3);
1567 /// assert_eq!(buf, [1, 2, 3]);
1569 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1570 /// assert_eq!(buf, [3, 2]);
1572 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1573 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1574 let length = self.len();
1575 if length > 0 && index < length - 1 {
1576 self.swap(index, length - 1);
1577 } else if index >= length {
1583 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1584 /// greater than or equal to `index` towards the back.
1586 /// Element at index 0 is the front of the queue.
1590 /// Panics if `index` is greater than `VecDeque`'s length
1595 /// use std::collections::VecDeque;
1597 /// let mut vec_deque = VecDeque::new();
1598 /// vec_deque.push_back('a');
1599 /// vec_deque.push_back('b');
1600 /// vec_deque.push_back('c');
1601 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1603 /// vec_deque.insert(1, 'd');
1604 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1606 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1607 pub fn insert(&mut self, index: usize, value: T) {
1608 assert!(index <= self.len(), "index out of bounds");
1613 // Move the least number of elements in the ring buffer and insert
1616 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1618 // There are three main cases:
1619 // Elements are contiguous
1620 // - special case when tail is 0
1621 // Elements are discontiguous and the insert is in the tail section
1622 // Elements are discontiguous and the insert is in the head section
1624 // For each of those there are two more cases:
1625 // Insert is closer to tail
1626 // Insert is closer to head
1628 // Key: H - self.head
1630 // o - Valid element
1631 // I - Insertion element
1632 // A - The element that should be after the insertion point
1633 // M - Indicates element was moved
1635 let idx = self.wrap_add(self.tail, index);
1637 let distance_to_tail = index;
1638 let distance_to_head = self.len() - index;
1640 let contiguous = self.is_contiguous();
1642 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1643 (true, true, _) if index == 0 => {
1648 // [A o o o o o o . . . . . . . . .]
1651 // [A o o o o o o o . . . . . I]
1654 self.tail = self.wrap_sub(self.tail, 1);
1656 (true, true, _) => {
1658 // contiguous, insert closer to tail:
1661 // [. . . o o A o o o o . . . . . .]
1664 // [. . o o I A o o o o . . . . . .]
1667 // contiguous, insert closer to tail and tail is 0:
1671 // [o o A o o o o . . . . . . . . .]
1674 // [o I A o o o o o . . . . . . . o]
1677 let new_tail = self.wrap_sub(self.tail, 1);
1679 self.copy(new_tail, self.tail, 1);
1680 // Already moved the tail, so we only copy `index - 1` elements.
1681 self.copy(self.tail, self.tail + 1, index - 1);
1683 self.tail = new_tail;
1686 (true, false, _) => {
1688 // contiguous, insert closer to head:
1691 // [. . . o o o o A o o . . . . . .]
1694 // [. . . o o o o I A o o . . . . .]
1697 self.copy(idx + 1, idx, self.head - idx);
1698 self.head = self.wrap_add(self.head, 1);
1701 (false, true, true) => {
1703 // discontiguous, insert closer to tail, tail section:
1706 // [o o o o o o . . . . . o o A o o]
1709 // [o o o o o o . . . . o o I A o o]
1712 self.copy(self.tail - 1, self.tail, index);
1716 (false, false, true) => {
1718 // discontiguous, insert closer to head, tail section:
1721 // [o o . . . . . . . o o o o o A o]
1724 // [o o o . . . . . . o o o o o I A]
1727 // copy elements up to new head
1728 self.copy(1, 0, self.head);
1730 // copy last element into empty spot at bottom of buffer
1731 self.copy(0, self.cap() - 1, 1);
1733 // move elements from idx to end forward not including ^ element
1734 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1739 (false, true, false) if idx == 0 => {
1741 // discontiguous, insert is closer to tail, head section,
1742 // and is at index zero in the internal buffer:
1745 // [A o o o o o o o o o . . . o o o]
1748 // [A o o o o o o o o o . . o o o I]
1751 // copy elements up to new tail
1752 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1754 // copy last element into empty spot at bottom of buffer
1755 self.copy(self.cap() - 1, 0, 1);
1760 (false, true, false) => {
1762 // discontiguous, insert closer to tail, head section:
1765 // [o o o A o o o o o o . . . o o o]
1768 // [o o I A o o o o o o . . o o o o]
1771 // copy elements up to new tail
1772 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1774 // copy last element into empty spot at bottom of buffer
1775 self.copy(self.cap() - 1, 0, 1);
1777 // move elements from idx-1 to end forward not including ^ element
1778 self.copy(0, 1, idx - 1);
1783 (false, false, false) => {
1785 // discontiguous, insert closer to head, head section:
1788 // [o o o o A o o . . . . . . o o o]
1791 // [o o o o I A o o . . . . . o o o]
1794 self.copy(idx + 1, idx, self.head - idx);
1800 // tail might've been changed so we need to recalculate
1801 let new_idx = self.wrap_add(self.tail, index);
1803 self.buffer_write(new_idx, value);
1807 /// Removes and returns the element at `index` from the `VecDeque`.
1808 /// Whichever end is closer to the removal point will be moved to make
1809 /// room, and all the affected elements will be moved to new positions.
1810 /// Returns `None` if `index` is out of bounds.
1812 /// Element at index 0 is the front of the queue.
1817 /// use std::collections::VecDeque;
1819 /// let mut buf = VecDeque::new();
1820 /// buf.push_back(1);
1821 /// buf.push_back(2);
1822 /// buf.push_back(3);
1823 /// assert_eq!(buf, [1, 2, 3]);
1825 /// assert_eq!(buf.remove(1), Some(2));
1826 /// assert_eq!(buf, [1, 3]);
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 pub fn remove(&mut self, index: usize) -> Option<T> {
1830 if self.is_empty() || self.len() <= index {
1834 // There are three main cases:
1835 // Elements are contiguous
1836 // Elements are discontiguous and the removal is in the tail section
1837 // Elements are discontiguous and the removal is in the head section
1838 // - special case when elements are technically contiguous,
1839 // but self.head = 0
1841 // For each of those there are two more cases:
1842 // Insert is closer to tail
1843 // Insert is closer to head
1845 // Key: H - self.head
1847 // o - Valid element
1848 // x - Element marked for removal
1849 // R - Indicates element that is being removed
1850 // M - Indicates element was moved
1852 let idx = self.wrap_add(self.tail, index);
1854 let elem = unsafe { Some(self.buffer_read(idx)) };
1856 let distance_to_tail = index;
1857 let distance_to_head = self.len() - index;
1859 let contiguous = self.is_contiguous();
1861 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1862 (true, true, _) => {
1864 // contiguous, remove closer to tail:
1867 // [. . . o o x o o o o . . . . . .]
1870 // [. . . . o o o o o o . . . . . .]
1873 self.copy(self.tail + 1, self.tail, index);
1877 (true, false, _) => {
1879 // contiguous, remove closer to head:
1882 // [. . . o o o o x o o . . . . . .]
1885 // [. . . o o o o o o . . . . . . .]
1888 self.copy(idx, idx + 1, self.head - idx - 1);
1892 (false, true, true) => {
1894 // discontiguous, remove closer to tail, tail section:
1897 // [o o o o o o . . . . . o o x o o]
1900 // [o o o o o o . . . . . . o o o o]
1903 self.copy(self.tail + 1, self.tail, index);
1904 self.tail = self.wrap_add(self.tail, 1);
1907 (false, false, false) => {
1909 // discontiguous, remove closer to head, head section:
1912 // [o o o o x o o . . . . . . o o o]
1915 // [o o o o o o . . . . . . . o o o]
1918 self.copy(idx, idx + 1, self.head - idx - 1);
1922 (false, false, true) => {
1924 // discontiguous, remove closer to head, tail section:
1927 // [o o o . . . . . . o o o o o x o]
1930 // [o o . . . . . . . o o o o o o o]
1933 // or quasi-discontiguous, remove next to head, tail section:
1936 // [. . . . . . . . . o o o o o x o]
1939 // [. . . . . . . . . o o o o o o .]
1942 // draw in elements in the tail section
1943 self.copy(idx, idx + 1, self.cap() - idx - 1);
1945 // Prevents underflow.
1947 // copy first element into empty spot
1948 self.copy(self.cap() - 1, 0, 1);
1950 // move elements in the head section backwards
1951 self.copy(0, 1, self.head - 1);
1954 self.head = self.wrap_sub(self.head, 1);
1957 (false, true, false) => {
1959 // discontiguous, remove closer to tail, head section:
1962 // [o o x o o o o o o o . . . o o o]
1965 // [o o o o o o o o o o . . . . o o]
1968 // draw in elements up to idx
1969 self.copy(1, 0, idx);
1971 // copy last element into empty spot
1972 self.copy(0, self.cap() - 1, 1);
1974 // move elements from tail to end forward, excluding the last one
1975 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1977 self.tail = self.wrap_add(self.tail, 1);
1985 /// Splits the `VecDeque` into two at the given index.
1987 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1988 /// and the returned `VecDeque` contains elements `[at, len)`.
1990 /// Note that the capacity of `self` does not change.
1992 /// Element at index 0 is the front of the queue.
1996 /// Panics if `at > len`.
2001 /// use std::collections::VecDeque;
2003 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
2004 /// let buf2 = buf.split_off(1);
2005 /// assert_eq!(buf, [1]);
2006 /// assert_eq!(buf2, [2, 3]);
2009 #[must_use = "use `.truncate()` if you don't need the other half"]
2010 #[stable(feature = "split_off", since = "1.4.0")]
2011 pub fn split_off(&mut self, at: usize) -> Self {
2012 let len = self.len();
2013 assert!(at <= len, "`at` out of bounds");
2015 let other_len = len - at;
2016 let mut other = VecDeque::with_capacity(other_len);
2019 let (first_half, second_half) = self.as_slices();
2021 let first_len = first_half.len();
2022 let second_len = second_half.len();
2024 // `at` lies in the first half.
2025 let amount_in_first = first_len - at;
2027 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2029 // just take all of the second half.
2030 ptr::copy_nonoverlapping(
2031 second_half.as_ptr(),
2032 other.ptr().add(amount_in_first),
2036 // `at` lies in the second half, need to factor in the elements we skipped
2037 // in the first half.
2038 let offset = at - first_len;
2039 let amount_in_second = second_len - offset;
2040 ptr::copy_nonoverlapping(
2041 second_half.as_ptr().add(offset),
2048 // Cleanup where the ends of the buffers are
2049 self.head = self.wrap_sub(self.head, other_len);
2050 other.head = other.wrap_index(other_len);
2055 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2059 /// Panics if the new number of elements in self overflows a `usize`.
2064 /// use std::collections::VecDeque;
2066 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
2067 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
2068 /// buf.append(&mut buf2);
2069 /// assert_eq!(buf, [1, 2, 3, 4]);
2070 /// assert_eq!(buf2, []);
2073 #[stable(feature = "append", since = "1.4.0")]
2074 pub fn append(&mut self, other: &mut Self) {
2076 self.extend(other.drain(..));
2079 /// Retains only the elements specified by the predicate.
2081 /// In other words, remove all elements `e` such that `f(&e)` returns false.
2082 /// This method operates in place, visiting each element exactly once in the
2083 /// original order, and preserves the order of the retained elements.
2088 /// use std::collections::VecDeque;
2090 /// let mut buf = VecDeque::new();
2091 /// buf.extend(1..5);
2092 /// buf.retain(|&x| x % 2 == 0);
2093 /// assert_eq!(buf, [2, 4]);
2096 /// The exact order may be useful for tracking external state, like an index.
2099 /// use std::collections::VecDeque;
2101 /// let mut buf = VecDeque::new();
2102 /// buf.extend(1..6);
2104 /// let keep = [false, true, true, false, true];
2106 /// buf.retain(|_| (keep[i], i += 1).0);
2107 /// assert_eq!(buf, [2, 3, 5]);
2109 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2110 pub fn retain<F>(&mut self, mut f: F)
2112 F: FnMut(&T) -> bool,
2114 let len = self.len();
2120 self.swap(i - del, i);
2124 self.truncate(len - del);
2128 // This may panic or abort
2130 fn grow(&mut self) {
2132 let old_cap = self.cap();
2133 // Double the buffer size.
2134 self.buf.reserve_exact(old_cap, old_cap);
2135 assert!(self.cap() == old_cap * 2);
2137 self.handle_capacity_increase(old_cap);
2139 debug_assert!(!self.is_full());
2143 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
2144 /// either by removing excess elements from the back or by appending
2145 /// elements generated by calling `generator` to the back.
2150 /// use std::collections::VecDeque;
2152 /// let mut buf = VecDeque::new();
2153 /// buf.push_back(5);
2154 /// buf.push_back(10);
2155 /// buf.push_back(15);
2156 /// assert_eq!(buf, [5, 10, 15]);
2158 /// buf.resize_with(5, Default::default);
2159 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2161 /// buf.resize_with(2, || unreachable!());
2162 /// assert_eq!(buf, [5, 10]);
2164 /// let mut state = 100;
2165 /// buf.resize_with(5, || { state += 1; state });
2166 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2168 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2169 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2170 let len = self.len();
2173 self.extend(repeat_with(generator).take(new_len - len))
2175 self.truncate(new_len);
2179 /// Rearranges the internal storage of this deque so it is one contiguous
2180 /// slice, which is then returned.
2182 /// This method does not allocate and does not change the order of the
2183 /// inserted elements. As it returns a mutable slice, this can be used to
2186 /// Once the internal storage is contiguous, the [`as_slices`] and
2187 /// [`as_mut_slices`] methods will return the entire contents of the
2188 /// `VecDeque` in a single slice.
2190 /// [`as_slices`]: VecDeque::as_slices
2191 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2195 /// Sorting the content of a deque.
2198 /// use std::collections::VecDeque;
2200 /// let mut buf = VecDeque::with_capacity(15);
2202 /// buf.push_back(2);
2203 /// buf.push_back(1);
2204 /// buf.push_front(3);
2206 /// // sorting the deque
2207 /// buf.make_contiguous().sort();
2208 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2210 /// // sorting it in reverse order
2211 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2212 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2215 /// Getting immutable access to the contiguous slice.
2218 /// use std::collections::VecDeque;
2220 /// let mut buf = VecDeque::new();
2222 /// buf.push_back(2);
2223 /// buf.push_back(1);
2224 /// buf.push_front(3);
2226 /// buf.make_contiguous();
2227 /// if let (slice, &[]) = buf.as_slices() {
2228 /// // we can now be sure that `slice` contains all elements of the deque,
2229 /// // while still having immutable access to `buf`.
2230 /// assert_eq!(buf.len(), slice.len());
2231 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2234 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2235 pub fn make_contiguous(&mut self) -> &mut [T] {
2236 if self.is_contiguous() {
2237 let tail = self.tail;
2238 let head = self.head;
2239 return unsafe { &mut self.buffer_as_mut_slice()[tail..head] };
2242 let buf = self.buf.ptr();
2243 let cap = self.cap();
2244 let len = self.len();
2246 let free = self.tail - self.head;
2247 let tail_len = cap - self.tail;
2249 if free >= tail_len {
2250 // there is enough free space to copy the tail in one go,
2251 // this means that we first shift the head backwards, and then
2252 // copy the tail to the correct position.
2254 // from: DEFGH....ABC
2257 ptr::copy(buf, buf.add(tail_len), self.head);
2259 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2265 } else if free >= self.head {
2266 // there is enough free space to copy the head in one go,
2267 // this means that we first shift the tail forwards, and then
2268 // copy the head to the correct position.
2270 // from: FGH....ABCDE
2273 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2275 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2278 self.tail = self.head;
2279 self.head = self.tail + len;
2282 // free is smaller than both head and tail,
2283 // this means we have to slowly "swap" the tail and the head.
2285 // from: EFGHI...ABCD or HIJK.ABCDEFG
2286 // to: ABCDEFGHI... or ABCDEFGHIJK.
2287 let mut left_edge: usize = 0;
2288 let mut right_edge: usize = self.tail;
2290 // The general problem looks like this
2291 // GHIJKLM...ABCDEF - before any swaps
2292 // ABCDEFM...GHIJKL - after 1 pass of swaps
2293 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2294 // - then restart the algorithm with a new (smaller) store
2295 // Sometimes the temp store is reached when the right edge is at the end
2296 // of the buffer - this means we've hit the right order with fewer swaps!
2299 // ABCDEF.. - after four only swaps we've finished
2300 while left_edge < len && right_edge != cap {
2301 let mut right_offset = 0;
2302 for i in left_edge..right_edge {
2303 right_offset = (i - left_edge) % (cap - right_edge);
2304 let src: isize = (right_edge + right_offset) as isize;
2305 ptr::swap(buf.add(i), buf.offset(src));
2307 let n_ops = right_edge - left_edge;
2309 right_edge += right_offset + 1;
2317 let tail = self.tail;
2318 let head = self.head;
2319 unsafe { &mut self.buffer_as_mut_slice()[tail..head] }
2322 /// Rotates the double-ended queue `mid` places to the left.
2325 /// - Rotates item `mid` into the first position.
2326 /// - Pops the first `mid` items and pushes them to the end.
2327 /// - Rotates `len() - mid` places to the right.
2331 /// If `mid` is greater than `len()`. Note that `mid == len()`
2332 /// does _not_ panic and is a no-op rotation.
2336 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2341 /// use std::collections::VecDeque;
2343 /// let mut buf: VecDeque<_> = (0..10).collect();
2345 /// buf.rotate_left(3);
2346 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2348 /// for i in 1..10 {
2349 /// assert_eq!(i * 3 % 10, buf[0]);
2350 /// buf.rotate_left(3);
2352 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2354 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2355 pub fn rotate_left(&mut self, mid: usize) {
2356 assert!(mid <= self.len());
2357 let k = self.len() - mid;
2359 unsafe { self.rotate_left_inner(mid) }
2361 unsafe { self.rotate_right_inner(k) }
2365 /// Rotates the double-ended queue `k` places to the right.
2368 /// - Rotates the first item into position `k`.
2369 /// - Pops the last `k` items and pushes them to the front.
2370 /// - Rotates `len() - k` places to the left.
2374 /// If `k` is greater than `len()`. Note that `k == len()`
2375 /// does _not_ panic and is a no-op rotation.
2379 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2384 /// use std::collections::VecDeque;
2386 /// let mut buf: VecDeque<_> = (0..10).collect();
2388 /// buf.rotate_right(3);
2389 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2391 /// for i in 1..10 {
2392 /// assert_eq!(0, buf[i * 3 % 10]);
2393 /// buf.rotate_right(3);
2395 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2397 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2398 pub fn rotate_right(&mut self, k: usize) {
2399 assert!(k <= self.len());
2400 let mid = self.len() - k;
2402 unsafe { self.rotate_right_inner(k) }
2404 unsafe { self.rotate_left_inner(mid) }
2408 // SAFETY: the following two methods require that the rotation amount
2409 // be less than half the length of the deque.
2411 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2412 // but than `min` is never more than half the capacity, regardless of x,
2413 // so it's sound to call here because we're calling with something
2414 // less than half the length, which is never above half the capacity.
2416 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2417 debug_assert!(mid * 2 <= self.len());
2419 self.wrap_copy(self.head, self.tail, mid);
2421 self.head = self.wrap_add(self.head, mid);
2422 self.tail = self.wrap_add(self.tail, mid);
2425 unsafe fn rotate_right_inner(&mut self, k: usize) {
2426 debug_assert!(k * 2 <= self.len());
2427 self.head = self.wrap_sub(self.head, k);
2428 self.tail = self.wrap_sub(self.tail, k);
2430 self.wrap_copy(self.tail, self.head, k);
2434 /// Binary searches this sorted `VecDeque` for a given element.
2436 /// If the value is found then [`Result::Ok`] is returned, containing the
2437 /// index of the matching element. If there are multiple matches, then any
2438 /// one of the matches could be returned. If the value is not found then
2439 /// [`Result::Err`] is returned, containing the index where a matching
2440 /// element could be inserted while maintaining sorted order.
2444 /// Looks up a series of four elements. The first is found, with a
2445 /// uniquely determined position; the second and third are not
2446 /// found; the fourth could match any position in `[1, 4]`.
2449 /// #![feature(vecdeque_binary_search)]
2450 /// use std::collections::VecDeque;
2452 /// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2454 /// assert_eq!(deque.binary_search(&13), Ok(9));
2455 /// assert_eq!(deque.binary_search(&4), Err(7));
2456 /// assert_eq!(deque.binary_search(&100), Err(13));
2457 /// let r = deque.binary_search(&1);
2458 /// assert!(matches!(r, Ok(1..=4)));
2461 /// If you want to insert an item to a sorted `VecDeque`, while maintaining
2465 /// #![feature(vecdeque_binary_search)]
2466 /// use std::collections::VecDeque;
2468 /// let mut deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2470 /// let idx = deque.binary_search(&num).unwrap_or_else(|x| x);
2471 /// deque.insert(idx, num);
2472 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2474 #[unstable(feature = "vecdeque_binary_search", issue = "78021")]
2476 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2480 self.binary_search_by(|e| e.cmp(x))
2483 /// Binary searches this sorted `VecDeque` with a comparator function.
2485 /// The comparator function should implement an order consistent
2486 /// with the sort order of the underlying `VecDeque`, returning an
2487 /// order code that indicates whether its argument is `Less`,
2488 /// `Equal` or `Greater` than the desired target.
2490 /// If the value is found then [`Result::Ok`] is returned, containing the
2491 /// index of the matching element. If there are multiple matches, then any
2492 /// one of the matches could be returned. If the value is not found then
2493 /// [`Result::Err`] is returned, containing the index where a matching
2494 /// element could be inserted while maintaining sorted order.
2498 /// Looks up a series of four elements. The first is found, with a
2499 /// uniquely determined position; the second and third are not
2500 /// found; the fourth could match any position in `[1, 4]`.
2503 /// #![feature(vecdeque_binary_search)]
2504 /// use std::collections::VecDeque;
2506 /// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2508 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2509 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2510 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2511 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2512 /// assert!(matches!(r, Ok(1..=4)));
2514 #[unstable(feature = "vecdeque_binary_search", issue = "78021")]
2515 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2517 F: FnMut(&'a T) -> Ordering,
2519 let (front, back) = self.as_slices();
2521 if let Some(Ordering::Less | Ordering::Equal) = back.first().map(|elem| f(elem)) {
2522 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2524 front.binary_search_by(f)
2528 /// Binary searches this sorted `VecDeque` with a key extraction function.
2530 /// Assumes that the `VecDeque` is sorted by the key, for instance with
2531 /// [`make_contiguous().sort_by_key()`](#method.make_contiguous) using the same
2532 /// key extraction function.
2534 /// If the value is found then [`Result::Ok`] is returned, containing the
2535 /// index of the matching element. If there are multiple matches, then any
2536 /// one of the matches could be returned. If the value is not found then
2537 /// [`Result::Err`] is returned, containing the index where a matching
2538 /// element could be inserted while maintaining sorted order.
2542 /// Looks up a series of four elements in a slice of pairs sorted by
2543 /// their second elements. The first is found, with a uniquely
2544 /// determined position; the second and third are not found; the
2545 /// fourth could match any position in `[1, 4]`.
2548 /// #![feature(vecdeque_binary_search)]
2549 /// use std::collections::VecDeque;
2551 /// let deque: VecDeque<_> = vec![(0, 0), (2, 1), (4, 1), (5, 1),
2552 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2553 /// (1, 21), (2, 34), (4, 55)].into();
2555 /// assert_eq!(deque.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
2556 /// assert_eq!(deque.binary_search_by_key(&4, |&(a,b)| b), Err(7));
2557 /// assert_eq!(deque.binary_search_by_key(&100, |&(a,b)| b), Err(13));
2558 /// let r = deque.binary_search_by_key(&1, |&(a,b)| b);
2559 /// assert!(matches!(r, Ok(1..=4)));
2561 #[unstable(feature = "vecdeque_binary_search", issue = "78021")]
2563 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2565 F: FnMut(&'a T) -> B,
2568 self.binary_search_by(|k| f(k).cmp(b))
2572 impl<T: Clone> VecDeque<T> {
2573 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2574 /// either by removing excess elements from the back or by appending clones of `value`
2580 /// use std::collections::VecDeque;
2582 /// let mut buf = VecDeque::new();
2583 /// buf.push_back(5);
2584 /// buf.push_back(10);
2585 /// buf.push_back(15);
2586 /// assert_eq!(buf, [5, 10, 15]);
2588 /// buf.resize(2, 0);
2589 /// assert_eq!(buf, [5, 10]);
2591 /// buf.resize(5, 20);
2592 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2594 #[stable(feature = "deque_extras", since = "1.16.0")]
2595 pub fn resize(&mut self, new_len: usize, value: T) {
2596 self.resize_with(new_len, || value.clone());
2600 /// Returns the index in the underlying buffer for a given logical element index.
2602 fn wrap_index(index: usize, size: usize) -> usize {
2603 // size is always a power of 2
2604 debug_assert!(size.is_power_of_two());
2608 /// Returns the two slices that cover the `VecDeque`'s valid range
2609 trait RingSlices: Sized {
2610 fn slice(self, from: usize, to: usize) -> Self;
2611 fn split_at(self, i: usize) -> (Self, Self);
2613 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
2614 let contiguous = tail <= head;
2616 let (empty, buf) = buf.split_at(0);
2617 (buf.slice(tail, head), empty)
2619 let (mid, right) = buf.split_at(tail);
2620 let (left, _) = mid.split_at(head);
2626 impl<T> RingSlices for &[T] {
2627 fn slice(self, from: usize, to: usize) -> Self {
2630 fn split_at(self, i: usize) -> (Self, Self) {
2635 impl<T> RingSlices for &mut [T] {
2636 fn slice(self, from: usize, to: usize) -> Self {
2639 fn split_at(self, i: usize) -> (Self, Self) {
2640 (*self).split_at_mut(i)
2644 impl<T> RingSlices for *mut [T] {
2645 fn slice(self, from: usize, to: usize) -> Self {
2646 assert!(from <= to && to < self.len());
2647 // Not using `get_unchecked_mut` to keep this a safe operation.
2648 let len = to - from;
2649 ptr::slice_from_raw_parts_mut(self.as_mut_ptr().wrapping_add(from), len)
2652 fn split_at(self, mid: usize) -> (Self, Self) {
2653 let len = self.len();
2654 let ptr = self.as_mut_ptr();
2655 assert!(mid <= len);
2657 ptr::slice_from_raw_parts_mut(ptr, mid),
2658 ptr::slice_from_raw_parts_mut(ptr.wrapping_add(mid), len - mid),
2663 /// Calculate the number of elements left to be read in the buffer
2665 fn count(tail: usize, head: usize, size: usize) -> usize {
2666 // size is always a power of 2
2667 (head.wrapping_sub(tail)) & (size - 1)
2670 /// An iterator over the elements of a `VecDeque`.
2672 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
2673 /// documentation for more.
2675 /// [`iter`]: VecDeque::iter
2676 #[stable(feature = "rust1", since = "1.0.0")]
2677 pub struct Iter<'a, T: 'a> {
2683 #[stable(feature = "collection_debug", since = "1.17.0")]
2684 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
2685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2686 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2687 f.debug_tuple("Iter").field(&front).field(&back).finish()
2691 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2692 #[stable(feature = "rust1", since = "1.0.0")]
2693 impl<T> Clone for Iter<'_, T> {
2694 fn clone(&self) -> Self {
2695 Iter { ring: self.ring, tail: self.tail, head: self.head }
2699 #[stable(feature = "rust1", since = "1.0.0")]
2700 impl<'a, T> Iterator for Iter<'a, T> {
2704 fn next(&mut self) -> Option<&'a T> {
2705 if self.tail == self.head {
2708 let tail = self.tail;
2709 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2710 unsafe { Some(self.ring.get_unchecked(tail)) }
2714 fn size_hint(&self) -> (usize, Option<usize>) {
2715 let len = count(self.tail, self.head, self.ring.len());
2719 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2721 F: FnMut(Acc, Self::Item) -> Acc,
2723 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2724 accum = front.iter().fold(accum, &mut f);
2725 back.iter().fold(accum, &mut f)
2728 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2731 F: FnMut(B, Self::Item) -> R,
2734 let (mut iter, final_res);
2735 if self.tail <= self.head {
2736 // single slice self.ring[self.tail..self.head]
2737 iter = self.ring[self.tail..self.head].iter();
2738 final_res = iter.try_fold(init, &mut f);
2740 // two slices: self.ring[self.tail..], self.ring[..self.head]
2741 let (front, back) = self.ring.split_at(self.tail);
2742 let mut back_iter = back.iter();
2743 let res = back_iter.try_fold(init, &mut f);
2744 let len = self.ring.len();
2745 self.tail = (self.ring.len() - back_iter.len()) & (len - 1);
2746 iter = front[..self.head].iter();
2747 final_res = iter.try_fold(res?, &mut f);
2749 self.tail = self.head - iter.len();
2753 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2754 if n >= count(self.tail, self.head, self.ring.len()) {
2755 self.tail = self.head;
2758 self.tail = wrap_index(self.tail.wrapping_add(n), self.ring.len());
2764 fn last(mut self) -> Option<&'a T> {
2769 #[stable(feature = "rust1", since = "1.0.0")]
2770 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2772 fn next_back(&mut self) -> Option<&'a T> {
2773 if self.tail == self.head {
2776 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2777 unsafe { Some(self.ring.get_unchecked(self.head)) }
2780 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2782 F: FnMut(Acc, Self::Item) -> Acc,
2784 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2785 accum = back.iter().rfold(accum, &mut f);
2786 front.iter().rfold(accum, &mut f)
2789 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
2792 F: FnMut(B, Self::Item) -> R,
2795 let (mut iter, final_res);
2796 if self.tail <= self.head {
2797 // single slice self.ring[self.tail..self.head]
2798 iter = self.ring[self.tail..self.head].iter();
2799 final_res = iter.try_rfold(init, &mut f);
2801 // two slices: self.ring[self.tail..], self.ring[..self.head]
2802 let (front, back) = self.ring.split_at(self.tail);
2803 let mut front_iter = front[..self.head].iter();
2804 let res = front_iter.try_rfold(init, &mut f);
2805 self.head = front_iter.len();
2807 final_res = iter.try_rfold(res?, &mut f);
2809 self.head = self.tail + iter.len();
2814 #[stable(feature = "rust1", since = "1.0.0")]
2815 impl<T> ExactSizeIterator for Iter<'_, T> {
2816 fn is_empty(&self) -> bool {
2817 self.head == self.tail
2821 #[stable(feature = "fused", since = "1.26.0")]
2822 impl<T> FusedIterator for Iter<'_, T> {}
2824 /// A mutable iterator over the elements of a `VecDeque`.
2826 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2827 /// documentation for more.
2829 /// [`iter_mut`]: VecDeque::iter_mut
2830 #[stable(feature = "rust1", since = "1.0.0")]
2831 pub struct IterMut<'a, T: 'a> {
2832 // Internal safety invariant: the entire slice is dereferencable.
2836 phantom: PhantomData<&'a mut [T]>,
2839 // SAFETY: we do nothing thread-local and there is no interior mutability,
2840 // so the usual structural `Send`/`Sync` apply.
2841 #[stable(feature = "rust1", since = "1.0.0")]
2842 unsafe impl<T: Send> Send for IterMut<'_, T> {}
2843 #[stable(feature = "rust1", since = "1.0.0")]
2844 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
2846 #[stable(feature = "collection_debug", since = "1.17.0")]
2847 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
2848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2849 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2850 // SAFETY: these are the elements we have not handed out yet, so aliasing is fine.
2851 // The `IterMut` invariant also ensures everything is dereferencable.
2852 let (front, back) = unsafe { (&*front, &*back) };
2853 f.debug_tuple("IterMut").field(&front).field(&back).finish()
2857 #[stable(feature = "rust1", since = "1.0.0")]
2858 impl<'a, T> Iterator for IterMut<'a, T> {
2859 type Item = &'a mut T;
2862 fn next(&mut self) -> Option<&'a mut T> {
2863 if self.tail == self.head {
2866 let tail = self.tail;
2867 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2870 let elem = self.ring.get_unchecked_mut(tail);
2876 fn size_hint(&self) -> (usize, Option<usize>) {
2877 let len = count(self.tail, self.head, self.ring.len());
2881 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2883 F: FnMut(Acc, Self::Item) -> Acc,
2885 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2886 // SAFETY: these are the elements we have not handed out yet, so aliasing is fine.
2887 // The `IterMut` invariant also ensures everything is dereferencable.
2888 let (front, back) = unsafe { (&mut *front, &mut *back) };
2889 accum = front.iter_mut().fold(accum, &mut f);
2890 back.iter_mut().fold(accum, &mut f)
2893 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2894 if n >= count(self.tail, self.head, self.ring.len()) {
2895 self.tail = self.head;
2898 self.tail = wrap_index(self.tail.wrapping_add(n), self.ring.len());
2904 fn last(mut self) -> Option<&'a mut T> {
2909 #[stable(feature = "rust1", since = "1.0.0")]
2910 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2912 fn next_back(&mut self) -> Option<&'a mut T> {
2913 if self.tail == self.head {
2916 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2919 let elem = self.ring.get_unchecked_mut(self.head);
2924 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2926 F: FnMut(Acc, Self::Item) -> Acc,
2928 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2929 // SAFETY: these are the elements we have not handed out yet, so aliasing is fine.
2930 // The `IterMut` invariant also ensures everything is dereferencable.
2931 let (front, back) = unsafe { (&mut *front, &mut *back) };
2932 accum = back.iter_mut().rfold(accum, &mut f);
2933 front.iter_mut().rfold(accum, &mut f)
2937 #[stable(feature = "rust1", since = "1.0.0")]
2938 impl<T> ExactSizeIterator for IterMut<'_, T> {
2939 fn is_empty(&self) -> bool {
2940 self.head == self.tail
2944 #[stable(feature = "fused", since = "1.26.0")]
2945 impl<T> FusedIterator for IterMut<'_, T> {}
2947 /// An owning iterator over the elements of a `VecDeque`.
2949 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`]
2950 /// (provided by the `IntoIterator` trait). See its documentation for more.
2952 /// [`into_iter`]: VecDeque::into_iter
2954 #[stable(feature = "rust1", since = "1.0.0")]
2955 pub struct IntoIter<T> {
2959 #[stable(feature = "collection_debug", since = "1.17.0")]
2960 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2962 f.debug_tuple("IntoIter").field(&self.inner).finish()
2966 #[stable(feature = "rust1", since = "1.0.0")]
2967 impl<T> Iterator for IntoIter<T> {
2971 fn next(&mut self) -> Option<T> {
2972 self.inner.pop_front()
2976 fn size_hint(&self) -> (usize, Option<usize>) {
2977 let len = self.inner.len();
2982 #[stable(feature = "rust1", since = "1.0.0")]
2983 impl<T> DoubleEndedIterator for IntoIter<T> {
2985 fn next_back(&mut self) -> Option<T> {
2986 self.inner.pop_back()
2990 #[stable(feature = "rust1", since = "1.0.0")]
2991 impl<T> ExactSizeIterator for IntoIter<T> {
2992 fn is_empty(&self) -> bool {
2993 self.inner.is_empty()
2997 #[stable(feature = "fused", since = "1.26.0")]
2998 impl<T> FusedIterator for IntoIter<T> {}
3000 #[stable(feature = "rust1", since = "1.0.0")]
3001 impl<A: PartialEq> PartialEq for VecDeque<A> {
3002 fn eq(&self, other: &VecDeque<A>) -> bool {
3003 if self.len() != other.len() {
3006 let (sa, sb) = self.as_slices();
3007 let (oa, ob) = other.as_slices();
3008 if sa.len() == oa.len() {
3009 sa == oa && sb == ob
3010 } else if sa.len() < oa.len() {
3011 // Always divisible in three sections, for example:
3012 // self: [a b c|d e f]
3013 // other: [0 1 2 3|4 5]
3014 // front = 3, mid = 1,
3015 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
3016 let front = sa.len();
3017 let mid = oa.len() - front;
3019 let (oa_front, oa_mid) = oa.split_at(front);
3020 let (sb_mid, sb_back) = sb.split_at(mid);
3021 debug_assert_eq!(sa.len(), oa_front.len());
3022 debug_assert_eq!(sb_mid.len(), oa_mid.len());
3023 debug_assert_eq!(sb_back.len(), ob.len());
3024 sa == oa_front && sb_mid == oa_mid && sb_back == ob
3026 let front = oa.len();
3027 let mid = sa.len() - front;
3029 let (sa_front, sa_mid) = sa.split_at(front);
3030 let (ob_mid, ob_back) = ob.split_at(mid);
3031 debug_assert_eq!(sa_front.len(), oa.len());
3032 debug_assert_eq!(sa_mid.len(), ob_mid.len());
3033 debug_assert_eq!(sb.len(), ob_back.len());
3034 sa_front == oa && sa_mid == ob_mid && sb == ob_back
3039 #[stable(feature = "rust1", since = "1.0.0")]
3040 impl<A: Eq> Eq for VecDeque<A> {}
3042 macro_rules! __impl_slice_eq1 {
3043 ([$($vars:tt)*] $lhs:ty, $rhs:ty, $($constraints:tt)*) => {
3044 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
3045 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
3050 fn eq(&self, other: &$rhs) -> bool {
3051 if self.len() != other.len() {
3054 let (sa, sb) = self.as_slices();
3055 let (oa, ob) = other[..].split_at(sa.len());
3056 sa == oa && sb == ob
3062 __impl_slice_eq1! { [] VecDeque<A>, Vec<B>, }
3063 __impl_slice_eq1! { [] VecDeque<A>, &[B], }
3064 __impl_slice_eq1! { [] VecDeque<A>, &mut [B], }
3065 __impl_slice_eq1! { [const N: usize] VecDeque<A>, [B; N], }
3066 __impl_slice_eq1! { [const N: usize] VecDeque<A>, &[B; N], }
3067 __impl_slice_eq1! { [const N: usize] VecDeque<A>, &mut [B; N], }
3069 #[stable(feature = "rust1", since = "1.0.0")]
3070 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
3071 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
3072 self.iter().partial_cmp(other.iter())
3076 #[stable(feature = "rust1", since = "1.0.0")]
3077 impl<A: Ord> Ord for VecDeque<A> {
3079 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
3080 self.iter().cmp(other.iter())
3084 #[stable(feature = "rust1", since = "1.0.0")]
3085 impl<A: Hash> Hash for VecDeque<A> {
3086 fn hash<H: Hasher>(&self, state: &mut H) {
3087 self.len().hash(state);
3088 let (a, b) = self.as_slices();
3089 Hash::hash_slice(a, state);
3090 Hash::hash_slice(b, state);
3094 #[stable(feature = "rust1", since = "1.0.0")]
3095 impl<A> Index<usize> for VecDeque<A> {
3099 fn index(&self, index: usize) -> &A {
3100 self.get(index).expect("Out of bounds access")
3104 #[stable(feature = "rust1", since = "1.0.0")]
3105 impl<A> IndexMut<usize> for VecDeque<A> {
3107 fn index_mut(&mut self, index: usize) -> &mut A {
3108 self.get_mut(index).expect("Out of bounds access")
3112 #[stable(feature = "rust1", since = "1.0.0")]
3113 impl<A> FromIterator<A> for VecDeque<A> {
3114 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
3115 let iterator = iter.into_iter();
3116 let (lower, _) = iterator.size_hint();
3117 let mut deq = VecDeque::with_capacity(lower);
3118 deq.extend(iterator);
3123 #[stable(feature = "rust1", since = "1.0.0")]
3124 impl<T> IntoIterator for VecDeque<T> {
3126 type IntoIter = IntoIter<T>;
3128 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
3130 fn into_iter(self) -> IntoIter<T> {
3131 IntoIter { inner: self }
3135 #[stable(feature = "rust1", since = "1.0.0")]
3136 impl<'a, T> IntoIterator for &'a VecDeque<T> {
3138 type IntoIter = Iter<'a, T>;
3140 fn into_iter(self) -> Iter<'a, T> {
3145 #[stable(feature = "rust1", since = "1.0.0")]
3146 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
3147 type Item = &'a mut T;
3148 type IntoIter = IterMut<'a, T>;
3150 fn into_iter(self) -> IterMut<'a, T> {
3155 #[stable(feature = "rust1", since = "1.0.0")]
3156 impl<A> Extend<A> for VecDeque<A> {
3157 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
3158 // This function should be the moral equivalent of:
3160 // for item in iter.into_iter() {
3161 // self.push_back(item);
3163 let mut iter = iter.into_iter();
3164 while let Some(element) = iter.next() {
3165 if self.len() == self.capacity() {
3166 let (lower, _) = iter.size_hint();
3167 self.reserve(lower.saturating_add(1));
3170 let head = self.head;
3171 self.head = self.wrap_add(self.head, 1);
3173 self.buffer_write(head, element);
3179 fn extend_one(&mut self, elem: A) {
3180 self.push_back(elem);
3184 fn extend_reserve(&mut self, additional: usize) {
3185 self.reserve(additional);
3189 #[stable(feature = "extend_ref", since = "1.2.0")]
3190 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
3191 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3192 self.extend(iter.into_iter().cloned());
3196 fn extend_one(&mut self, &elem: &T) {
3197 self.push_back(elem);
3201 fn extend_reserve(&mut self, additional: usize) {
3202 self.reserve(additional);
3206 #[stable(feature = "rust1", since = "1.0.0")]
3207 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
3208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3209 f.debug_list().entries(self).finish()
3213 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3214 impl<T> From<Vec<T>> for VecDeque<T> {
3215 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3217 /// [`Vec<T>`]: crate::vec::Vec
3218 /// [`VecDeque<T>`]: crate::collections::VecDeque
3220 /// This avoids reallocating where possible, but the conditions for that are
3221 /// strict, and subject to change, and so shouldn't be relied upon unless the
3222 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
3223 fn from(other: Vec<T>) -> Self {
3225 let mut other = ManuallyDrop::new(other);
3226 let other_buf = other.as_mut_ptr();
3227 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
3228 let len = other.len();
3230 // We need to extend the buf if it's not a power of two, too small
3231 // or doesn't have at least one free space
3232 if !buf.capacity().is_power_of_two()
3233 || (buf.capacity() < (MINIMUM_CAPACITY + 1))
3234 || (buf.capacity() == len)
3236 let cap = cmp::max(buf.capacity() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
3237 buf.reserve_exact(len, cap - len);
3240 VecDeque { tail: 0, head: len, buf }
3245 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3246 impl<T> From<VecDeque<T>> for Vec<T> {
3247 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
3249 /// [`Vec<T>`]: crate::vec::Vec
3250 /// [`VecDeque<T>`]: crate::collections::VecDeque
3252 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
3253 /// the circular buffer doesn't happen to be at the beginning of the allocation.
3258 /// use std::collections::VecDeque;
3260 /// // This one is *O*(1).
3261 /// let deque: VecDeque<_> = (1..5).collect();
3262 /// let ptr = deque.as_slices().0.as_ptr();
3263 /// let vec = Vec::from(deque);
3264 /// assert_eq!(vec, [1, 2, 3, 4]);
3265 /// assert_eq!(vec.as_ptr(), ptr);
3267 /// // This one needs data rearranging.
3268 /// let mut deque: VecDeque<_> = (1..5).collect();
3269 /// deque.push_front(9);
3270 /// deque.push_front(8);
3271 /// let ptr = deque.as_slices().1.as_ptr();
3272 /// let vec = Vec::from(deque);
3273 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
3274 /// assert_eq!(vec.as_ptr(), ptr);
3276 fn from(mut other: VecDeque<T>) -> Self {
3277 other.make_contiguous();
3280 let other = ManuallyDrop::new(other);
3281 let buf = other.buf.ptr();
3282 let len = other.len();
3283 let cap = other.cap();
3285 if other.head != 0 {
3286 ptr::copy(buf.add(other.tail), buf, len);
3288 Vec::from_raw_parts(buf, len, cap)