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
12 use core::cmp::{self, Ordering};
14 use core::hash::{Hash, Hasher};
15 use core::iter::{once, repeat_with, FromIterator, FusedIterator};
16 use core::mem::{self, replace, ManuallyDrop};
17 use core::ops::{Index, IndexMut, Range, RangeBounds, Try};
18 use core::ptr::{self, NonNull};
21 use crate::collections::TryReserveError;
22 use crate::raw_vec::RawVec;
25 #[stable(feature = "drain", since = "1.6.0")]
26 pub use self::drain::Drain;
33 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
34 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
36 const MAXIMUM_ZST_CAPACITY: usize = 1 << (core::mem::size_of::<usize>() * 8 - 1); // Largest possible power of two
38 /// A double-ended queue implemented with a growable ring buffer.
40 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
41 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
42 /// push onto the back in this manner, and iterating over `VecDeque` goes front
45 /// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
46 /// in memory. If you want to access the elements as a single slice, such as for
47 /// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
48 /// so that its elements do not wrap, and returns a mutable slice to the
49 /// now-contiguous element sequence.
51 /// [`push_back`]: VecDeque::push_back
52 /// [`pop_front`]: VecDeque::pop_front
53 /// [`extend`]: VecDeque::extend
54 /// [`append`]: VecDeque::append
55 /// [`make_contiguous`]: VecDeque::make_contiguous
56 #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_type")]
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub struct VecDeque<T> {
59 // tail and head are pointers into the buffer. Tail always points
60 // to the first element that could be read, Head always points
61 // to where data should be written.
62 // If tail == head the buffer is empty. The length of the ringbuffer
63 // is defined as the distance between the two.
69 /// PairSlices pairs up equal length slice parts of two deques
71 /// For example, given deques "A" and "B" with the following division into slices:
73 /// A: [0 1 2] [3 4 5]
76 /// It produces the following sequence of matching slices:
82 /// and the uneven remainder of either A or B is skipped.
83 struct PairSlices<'a, 'b, T> {
90 impl<'a, 'b, T> PairSlices<'a, 'b, T> {
91 fn from(to: &'a mut VecDeque<T>, from: &'b VecDeque<T>) -> Self {
92 let (a0, a1) = to.as_mut_slices();
93 let (b0, b1) = from.as_slices();
94 PairSlices { a0, a1, b0, b1 }
97 fn has_remainder(&self) -> bool {
101 fn remainder(self) -> impl Iterator<Item = &'b [T]> {
102 once(self.b0).chain(once(self.b1))
106 impl<'a, 'b, T> Iterator for PairSlices<'a, 'b, T> {
107 type Item = (&'a mut [T], &'b [T]);
108 fn next(&mut self) -> Option<Self::Item> {
109 // Get next part length
110 let part = cmp::min(self.a0.len(), self.b0.len());
114 let (p0, p1) = replace(&mut self.a0, &mut []).split_at_mut(part);
115 let (q0, q1) = self.b0.split_at(part);
117 // Move a1 into a0, if it's empty (and b1, b0 the same way).
120 if self.a0.is_empty() {
121 self.a0 = replace(&mut self.a1, &mut []);
123 if self.b0.is_empty() {
124 self.b0 = replace(&mut self.b1, &[]);
130 #[stable(feature = "rust1", since = "1.0.0")]
131 impl<T: Clone> Clone for VecDeque<T> {
132 fn clone(&self) -> VecDeque<T> {
133 self.iter().cloned().collect()
136 fn clone_from(&mut self, other: &Self) {
137 self.truncate(other.len());
139 let mut iter = PairSlices::from(self, other);
140 while let Some((dst, src)) = iter.next() {
141 dst.clone_from_slice(&src);
144 if iter.has_remainder() {
145 for remainder in iter.remainder() {
146 self.extend(remainder.iter().cloned());
152 #[stable(feature = "rust1", since = "1.0.0")]
153 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
155 /// Runs the destructor for all items in the slice when it gets dropped (normally or
156 /// during unwinding).
157 struct Dropper<'a, T>(&'a mut [T]);
159 impl<'a, T> Drop for Dropper<'a, T> {
162 ptr::drop_in_place(self.0);
167 let (front, back) = self.as_mut_slices();
169 let _back_dropper = Dropper(back);
171 ptr::drop_in_place(front);
173 // RawVec handles deallocation
177 #[stable(feature = "rust1", since = "1.0.0")]
178 impl<T> Default for VecDeque<T> {
179 /// Creates an empty `VecDeque<T>`.
181 fn default() -> VecDeque<T> {
186 impl<T> VecDeque<T> {
187 /// Marginally more convenient
189 fn ptr(&self) -> *mut T {
193 /// Marginally more convenient
195 fn cap(&self) -> usize {
196 if mem::size_of::<T>() == 0 {
197 // For zero sized types, we are always at maximum capacity
204 /// Turn ptr into a slice
206 unsafe fn buffer_as_slice(&self) -> &[T] {
207 unsafe { slice::from_raw_parts(self.ptr(), self.cap()) }
210 /// Turn ptr into a mut slice
212 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
213 unsafe { slice::from_raw_parts_mut(self.ptr(), self.cap()) }
216 /// Moves an element out of the buffer
218 unsafe fn buffer_read(&mut self, off: usize) -> T {
219 unsafe { ptr::read(self.ptr().add(off)) }
222 /// Writes an element into the buffer, moving it.
224 unsafe fn buffer_write(&mut self, off: usize, value: T) {
226 ptr::write(self.ptr().add(off), value);
230 /// Returns `true` if the buffer is at full capacity.
232 fn is_full(&self) -> bool {
233 self.cap() - self.len() == 1
236 /// Returns the index in the underlying buffer for a given logical element
239 fn wrap_index(&self, idx: usize) -> usize {
240 wrap_index(idx, self.cap())
243 /// Returns the index in the underlying buffer for a given logical element
246 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
247 wrap_index(idx.wrapping_add(addend), self.cap())
250 /// Returns the index in the underlying buffer for a given logical element
251 /// index - subtrahend.
253 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
254 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
257 /// Copies a contiguous block of memory len long from src to dst
259 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
261 dst + len <= self.cap(),
262 "cpy dst={} src={} len={} cap={}",
269 src + len <= self.cap(),
270 "cpy dst={} src={} len={} cap={}",
277 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
281 /// Copies a contiguous block of memory len long from src to dst
283 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
285 dst + len <= self.cap(),
286 "cno dst={} src={} len={} cap={}",
293 src + len <= self.cap(),
294 "cno dst={} src={} len={} cap={}",
301 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
305 /// Copies a potentially wrapping block of memory len long from src to dest.
306 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
307 /// most one continuous overlapping region between src and dest).
308 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
310 fn diff(a: usize, b: usize) -> usize {
311 if a <= b { b - a } else { a - b }
314 cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
315 "wrc dst={} src={} len={} cap={}",
322 if src == dst || len == 0 {
326 let dst_after_src = self.wrap_sub(dst, src) < len;
328 let src_pre_wrap_len = self.cap() - src;
329 let dst_pre_wrap_len = self.cap() - dst;
330 let src_wraps = src_pre_wrap_len < len;
331 let dst_wraps = dst_pre_wrap_len < len;
333 match (dst_after_src, src_wraps, dst_wraps) {
334 (_, false, false) => {
335 // src doesn't wrap, dst doesn't wrap
338 // 1 [_ _ A A B B C C _]
339 // 2 [_ _ A A A A B B _]
343 self.copy(dst, src, len);
346 (false, false, true) => {
347 // dst before src, src doesn't wrap, dst wraps
350 // 1 [A A B B _ _ _ C C]
351 // 2 [A A B B _ _ _ A A]
352 // 3 [B B B B _ _ _ A A]
356 self.copy(dst, src, dst_pre_wrap_len);
357 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
360 (true, false, true) => {
361 // src before dst, src doesn't wrap, dst wraps
364 // 1 [C C _ _ _ A A B B]
365 // 2 [B B _ _ _ A A B B]
366 // 3 [B B _ _ _ A A A A]
370 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
371 self.copy(dst, src, dst_pre_wrap_len);
374 (false, true, false) => {
375 // dst before src, src wraps, dst doesn't wrap
378 // 1 [C C _ _ _ A A B B]
379 // 2 [C C _ _ _ B B B B]
380 // 3 [C C _ _ _ B B C C]
384 self.copy(dst, src, src_pre_wrap_len);
385 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
388 (true, true, false) => {
389 // src before dst, src wraps, dst doesn't wrap
392 // 1 [A A B B _ _ _ C C]
393 // 2 [A A A A _ _ _ C C]
394 // 3 [C C A A _ _ _ C C]
398 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
399 self.copy(dst, src, src_pre_wrap_len);
402 (false, true, true) => {
403 // dst before src, src wraps, dst wraps
406 // 1 [A B C D _ E F G H]
407 // 2 [A B C D _ E G H H]
408 // 3 [A B C D _ E G H A]
409 // 4 [B C C D _ E G H A]
412 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
413 let delta = dst_pre_wrap_len - src_pre_wrap_len;
415 self.copy(dst, src, src_pre_wrap_len);
416 self.copy(dst + src_pre_wrap_len, 0, delta);
417 self.copy(0, delta, len - dst_pre_wrap_len);
420 (true, true, true) => {
421 // src before dst, src wraps, dst wraps
424 // 1 [A B C D _ E F G H]
425 // 2 [A A B D _ E F G H]
426 // 3 [H A B D _ E F G H]
427 // 4 [H A B D _ E F F G]
430 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
431 let delta = src_pre_wrap_len - dst_pre_wrap_len;
433 self.copy(delta, 0, len - src_pre_wrap_len);
434 self.copy(0, self.cap() - delta, delta);
435 self.copy(dst, src, dst_pre_wrap_len);
441 /// Frobs the head and tail sections around to handle the fact that we
442 /// just reallocated. Unsafe because it trusts old_capacity.
444 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
445 let new_capacity = self.cap();
447 // Move the shortest contiguous section of the ring buffer
449 // [o o o o o o o . ]
451 // A [o o o o o o o . . . . . . . . . ]
453 // [o o . o o o o o ]
455 // B [. . . o o o o o o o . . . . . . ]
457 // [o o o o o . o o ]
459 // C [o o o o o . . . . . . . . . o o ]
461 if self.tail <= self.head {
464 } else if self.head < old_capacity - self.tail {
467 self.copy_nonoverlapping(old_capacity, 0, self.head);
469 self.head += old_capacity;
470 debug_assert!(self.head > self.tail);
473 let new_tail = new_capacity - (old_capacity - self.tail);
475 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
477 self.tail = new_tail;
478 debug_assert!(self.head < self.tail);
480 debug_assert!(self.head < self.cap());
481 debug_assert!(self.tail < self.cap());
482 debug_assert!(self.cap().count_ones() == 1);
486 impl<T> VecDeque<T> {
487 /// Creates an empty `VecDeque`.
492 /// use std::collections::VecDeque;
494 /// let vector: VecDeque<u32> = VecDeque::new();
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub fn new() -> VecDeque<T> {
498 VecDeque::with_capacity(INITIAL_CAPACITY)
501 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
506 /// use std::collections::VecDeque;
508 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
512 // +1 since the ringbuffer always leaves one space empty
513 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
514 assert!(cap > capacity, "capacity overflow");
516 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity(cap) }
519 /// Provides a reference to the element at the given index.
521 /// Element at index 0 is the front of the queue.
526 /// use std::collections::VecDeque;
528 /// let mut buf = VecDeque::new();
529 /// buf.push_back(3);
530 /// buf.push_back(4);
531 /// buf.push_back(5);
532 /// assert_eq!(buf.get(1), Some(&4));
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn get(&self, index: usize) -> Option<&T> {
536 if index < self.len() {
537 let idx = self.wrap_add(self.tail, index);
538 unsafe { Some(&*self.ptr().add(idx)) }
544 /// Provides a mutable reference to the element at the given index.
546 /// Element at index 0 is the front of the queue.
551 /// use std::collections::VecDeque;
553 /// let mut buf = VecDeque::new();
554 /// buf.push_back(3);
555 /// buf.push_back(4);
556 /// buf.push_back(5);
557 /// if let Some(elem) = buf.get_mut(1) {
561 /// assert_eq!(buf[1], 7);
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
565 if index < self.len() {
566 let idx = self.wrap_add(self.tail, index);
567 unsafe { Some(&mut *self.ptr().add(idx)) }
573 /// Swaps elements at indices `i` and `j`.
575 /// `i` and `j` may be equal.
577 /// Element at index 0 is the front of the queue.
581 /// Panics if either index is out of bounds.
586 /// use std::collections::VecDeque;
588 /// let mut buf = VecDeque::new();
589 /// buf.push_back(3);
590 /// buf.push_back(4);
591 /// buf.push_back(5);
592 /// assert_eq!(buf, [3, 4, 5]);
594 /// assert_eq!(buf, [5, 4, 3]);
596 #[stable(feature = "rust1", since = "1.0.0")]
597 pub fn swap(&mut self, i: usize, j: usize) {
598 assert!(i < self.len());
599 assert!(j < self.len());
600 let ri = self.wrap_add(self.tail, i);
601 let rj = self.wrap_add(self.tail, j);
602 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
605 /// Returns the number of elements the `VecDeque` can hold without
611 /// use std::collections::VecDeque;
613 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
614 /// assert!(buf.capacity() >= 10);
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn capacity(&self) -> usize {
622 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
623 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
625 /// Note that the allocator may give the collection more space than it requests. Therefore
626 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
627 /// insertions are expected.
631 /// Panics if the new capacity overflows `usize`.
636 /// use std::collections::VecDeque;
638 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
639 /// buf.reserve_exact(10);
640 /// assert!(buf.capacity() >= 11);
643 /// [`reserve`]: VecDeque::reserve
644 #[stable(feature = "rust1", since = "1.0.0")]
645 pub fn reserve_exact(&mut self, additional: usize) {
646 self.reserve(additional);
649 /// Reserves capacity for at least `additional` more elements to be inserted in the given
650 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
654 /// Panics if the new capacity overflows `usize`.
659 /// use std::collections::VecDeque;
661 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
663 /// assert!(buf.capacity() >= 11);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn reserve(&mut self, additional: usize) {
667 let old_cap = self.cap();
668 let used_cap = self.len() + 1;
669 let new_cap = used_cap
670 .checked_add(additional)
671 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
672 .expect("capacity overflow");
674 if new_cap > old_cap {
675 self.buf.reserve_exact(used_cap, new_cap - used_cap);
677 self.handle_capacity_increase(old_cap);
682 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
683 /// be inserted in the given `VecDeque<T>`. After calling `try_reserve_exact`,
684 /// capacity will be greater than or equal to `self.len() + additional`.
685 /// Does nothing if the capacity is already sufficient.
687 /// Note that the allocator may give the collection more space than it
688 /// requests. Therefore, capacity can not be relied upon to be precisely
689 /// minimal. Prefer `reserve` if future insertions are expected.
693 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
699 /// #![feature(try_reserve)]
700 /// use std::collections::TryReserveError;
701 /// use std::collections::VecDeque;
703 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
704 /// let mut output = VecDeque::new();
706 /// // Pre-reserve the memory, exiting if we can't
707 /// output.try_reserve_exact(data.len())?;
709 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
710 /// output.extend(data.iter().map(|&val| {
711 /// val * 2 + 5 // very complicated
716 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
718 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
719 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
720 self.try_reserve(additional)
723 /// Tries to reserve capacity for at least `additional` more elements to be inserted
724 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
725 /// frequent reallocations. After calling `try_reserve`, capacity will be
726 /// greater than or equal to `self.len() + additional`. Does nothing if
727 /// capacity is already sufficient.
731 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
737 /// #![feature(try_reserve)]
738 /// use std::collections::TryReserveError;
739 /// use std::collections::VecDeque;
741 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
742 /// let mut output = VecDeque::new();
744 /// // Pre-reserve the memory, exiting if we can't
745 /// output.try_reserve(data.len())?;
747 /// // Now we know this can't OOM in the middle of our complex work
748 /// output.extend(data.iter().map(|&val| {
749 /// val * 2 + 5 // very complicated
754 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
756 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
757 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
758 let old_cap = self.cap();
759 let used_cap = self.len() + 1;
760 let new_cap = used_cap
761 .checked_add(additional)
762 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
763 .ok_or(TryReserveError::CapacityOverflow)?;
765 if new_cap > old_cap {
766 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
768 self.handle_capacity_increase(old_cap);
774 /// Shrinks the capacity of the `VecDeque` as much as possible.
776 /// It will drop down as close as possible to the length but the allocator may still inform the
777 /// `VecDeque` that there is space for a few more elements.
782 /// use std::collections::VecDeque;
784 /// let mut buf = VecDeque::with_capacity(15);
785 /// buf.extend(0..4);
786 /// assert_eq!(buf.capacity(), 15);
787 /// buf.shrink_to_fit();
788 /// assert!(buf.capacity() >= 4);
790 #[stable(feature = "deque_extras_15", since = "1.5.0")]
791 pub fn shrink_to_fit(&mut self) {
795 /// Shrinks the capacity of the `VecDeque` with a lower bound.
797 /// The capacity will remain at least as large as both the length
798 /// and the supplied value.
800 /// Panics if the current capacity is smaller than the supplied
801 /// minimum capacity.
806 /// #![feature(shrink_to)]
807 /// use std::collections::VecDeque;
809 /// let mut buf = VecDeque::with_capacity(15);
810 /// buf.extend(0..4);
811 /// assert_eq!(buf.capacity(), 15);
812 /// buf.shrink_to(6);
813 /// assert!(buf.capacity() >= 6);
814 /// buf.shrink_to(0);
815 /// assert!(buf.capacity() >= 4);
817 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
818 pub fn shrink_to(&mut self, min_capacity: usize) {
819 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
821 // +1 since the ringbuffer always leaves one space empty
822 // len + 1 can't overflow for an existing, well-formed ringbuffer.
823 let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
824 .next_power_of_two();
826 if target_cap < self.cap() {
827 // There are three cases of interest:
828 // All elements are out of desired bounds
829 // Elements are contiguous, and head is out of desired bounds
830 // Elements are discontiguous, and tail is out of desired bounds
832 // At all other times, element positions are unaffected.
834 // Indicates that elements at the head should be moved.
835 let head_outside = self.head == 0 || self.head >= target_cap;
836 // Move elements from out of desired bounds (positions after target_cap)
837 if self.tail >= target_cap && head_outside {
839 // [. . . . . . . . o o o o o o o . ]
841 // [o o o o o o o . ]
843 self.copy_nonoverlapping(0, self.tail, self.len());
845 self.head = self.len();
847 } else if self.tail != 0 && self.tail < target_cap && head_outside {
849 // [. . . o o o o o o o . . . . . . ]
851 // [o o . o o o o o ]
852 let len = self.wrap_sub(self.head, target_cap);
854 self.copy_nonoverlapping(0, target_cap, len);
857 debug_assert!(self.head < self.tail);
858 } else if self.tail >= target_cap {
860 // [o o o o o . . . . . . . . . o o ]
862 // [o o o o o . o o ]
863 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
864 let len = self.cap() - self.tail;
865 let new_tail = target_cap - len;
867 self.copy_nonoverlapping(new_tail, self.tail, len);
869 self.tail = new_tail;
870 debug_assert!(self.head < self.tail);
873 self.buf.shrink_to_fit(target_cap);
875 debug_assert!(self.head < self.cap());
876 debug_assert!(self.tail < self.cap());
877 debug_assert!(self.cap().count_ones() == 1);
881 /// Shortens the `VecDeque`, keeping the first `len` elements and dropping
884 /// If `len` is greater than the `VecDeque`'s current length, this has no
890 /// use std::collections::VecDeque;
892 /// let mut buf = VecDeque::new();
893 /// buf.push_back(5);
894 /// buf.push_back(10);
895 /// buf.push_back(15);
896 /// assert_eq!(buf, [5, 10, 15]);
898 /// assert_eq!(buf, [5]);
900 #[stable(feature = "deque_extras", since = "1.16.0")]
901 pub fn truncate(&mut self, len: usize) {
902 /// Runs the destructor for all items in the slice when it gets dropped (normally or
903 /// during unwinding).
904 struct Dropper<'a, T>(&'a mut [T]);
906 impl<'a, T> Drop for Dropper<'a, T> {
909 ptr::drop_in_place(self.0);
916 // * Any slice passed to `drop_in_place` is valid; the second case has
917 // `len <= front.len()` and returning on `len > self.len()` ensures
918 // `begin <= back.len()` in the first case
919 // * The head of the VecDeque is moved before calling `drop_in_place`,
920 // so no value is dropped twice if `drop_in_place` panics
922 if len > self.len() {
925 let num_dropped = self.len() - len;
926 let (front, back) = self.as_mut_slices();
927 if len > front.len() {
928 let begin = len - front.len();
929 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
930 self.head = self.wrap_sub(self.head, num_dropped);
931 ptr::drop_in_place(drop_back);
933 let drop_back = back as *mut _;
934 let drop_front = front.get_unchecked_mut(len..) as *mut _;
935 self.head = self.wrap_sub(self.head, num_dropped);
937 // Make sure the second half is dropped even when a destructor
938 // in the first one panics.
939 let _back_dropper = Dropper(&mut *drop_back);
940 ptr::drop_in_place(drop_front);
945 /// Returns a front-to-back iterator.
950 /// use std::collections::VecDeque;
952 /// let mut buf = VecDeque::new();
953 /// buf.push_back(5);
954 /// buf.push_back(3);
955 /// buf.push_back(4);
956 /// let b: &[_] = &[&5, &3, &4];
957 /// let c: Vec<&i32> = buf.iter().collect();
958 /// assert_eq!(&c[..], b);
960 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn iter(&self) -> Iter<'_, T> {
962 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } }
965 /// Returns a front-to-back iterator that returns mutable references.
970 /// use std::collections::VecDeque;
972 /// let mut buf = VecDeque::new();
973 /// buf.push_back(5);
974 /// buf.push_back(3);
975 /// buf.push_back(4);
976 /// for num in buf.iter_mut() {
979 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
980 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
982 #[stable(feature = "rust1", since = "1.0.0")]
983 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
984 IterMut { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_mut_slice() } }
987 /// Returns a pair of slices which contain, in order, the contents of the
990 /// If [`make_contiguous`] was previously called, all elements of the
991 /// `VecDeque` will be in the first slice and the second slice will be empty.
993 /// [`make_contiguous`]: VecDeque::make_contiguous
998 /// use std::collections::VecDeque;
1000 /// let mut vector = VecDeque::new();
1002 /// vector.push_back(0);
1003 /// vector.push_back(1);
1004 /// vector.push_back(2);
1006 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
1008 /// vector.push_front(10);
1009 /// vector.push_front(9);
1011 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1014 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1015 pub fn as_slices(&self) -> (&[T], &[T]) {
1017 let buf = self.buffer_as_slice();
1018 RingSlices::ring_slices(buf, self.head, self.tail)
1022 /// Returns a pair of slices which contain, in order, the contents of the
1025 /// If [`make_contiguous`] was previously called, all elements of the
1026 /// `VecDeque` will be in the first slice and the second slice will be empty.
1028 /// [`make_contiguous`]: VecDeque::make_contiguous
1033 /// use std::collections::VecDeque;
1035 /// let mut vector = VecDeque::new();
1037 /// vector.push_back(0);
1038 /// vector.push_back(1);
1040 /// vector.push_front(10);
1041 /// vector.push_front(9);
1043 /// vector.as_mut_slices().0[0] = 42;
1044 /// vector.as_mut_slices().1[0] = 24;
1045 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
1048 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1049 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1051 let head = self.head;
1052 let tail = self.tail;
1053 let buf = self.buffer_as_mut_slice();
1054 RingSlices::ring_slices(buf, head, tail)
1058 /// Returns the number of elements in the `VecDeque`.
1063 /// use std::collections::VecDeque;
1065 /// let mut v = VecDeque::new();
1066 /// assert_eq!(v.len(), 0);
1068 /// assert_eq!(v.len(), 1);
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 pub fn len(&self) -> usize {
1072 count(self.tail, self.head, self.cap())
1075 /// Returns `true` if the `VecDeque` is empty.
1080 /// use std::collections::VecDeque;
1082 /// let mut v = VecDeque::new();
1083 /// assert!(v.is_empty());
1084 /// v.push_front(1);
1085 /// assert!(!v.is_empty());
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub fn is_empty(&self) -> bool {
1089 self.tail == self.head
1092 fn range_tail_head<R>(&self, range: R) -> (usize, usize)
1094 R: RangeBounds<usize>,
1096 let Range { start, end } = slice::check_range(self.len(), range);
1097 let tail = self.wrap_add(self.tail, start);
1098 let head = self.wrap_add(self.tail, end);
1102 /// Creates an iterator that covers the specified range in the `VecDeque`.
1106 /// Panics if the starting point is greater than the end point or if
1107 /// the end point is greater than the length of the vector.
1112 /// #![feature(deque_range)]
1114 /// use std::collections::VecDeque;
1116 /// let v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1117 /// let range = v.range(2..).copied().collect::<VecDeque<_>>();
1118 /// assert_eq!(range, [3]);
1120 /// // A full range covers all contents
1121 /// let all = v.range(..);
1122 /// assert_eq!(all.len(), 3);
1125 #[unstable(feature = "deque_range", issue = "74217")]
1126 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1128 R: RangeBounds<usize>,
1130 let (tail, head) = self.range_tail_head(range);
1134 // The shared reference we have in &self is maintained in the '_ of Iter.
1135 ring: unsafe { self.buffer_as_slice() },
1139 /// Creates an iterator that covers the specified mutable range in the `VecDeque`.
1143 /// Panics if the starting point is greater than the end point or if
1144 /// the end point is greater than the length of the vector.
1149 /// #![feature(deque_range)]
1151 /// use std::collections::VecDeque;
1153 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1154 /// for v in v.range_mut(2..) {
1157 /// assert_eq!(v, vec![1, 2, 6]);
1159 /// // A full range covers all contents
1160 /// for v in v.range_mut(..) {
1163 /// assert_eq!(v, vec![2, 4, 12]);
1166 #[unstable(feature = "deque_range", issue = "74217")]
1167 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1169 R: RangeBounds<usize>,
1171 let (tail, head) = self.range_tail_head(range);
1175 // The shared reference we have in &mut self is maintained in the '_ of IterMut.
1176 ring: unsafe { self.buffer_as_mut_slice() },
1180 /// Creates a draining iterator that removes the specified range in the
1181 /// `VecDeque` and yields the removed items.
1183 /// Note 1: The element range is removed even if the iterator is not
1184 /// consumed until the end.
1186 /// Note 2: It is unspecified how many elements are removed from the deque,
1187 /// if the `Drain` value is not dropped, but the borrow it holds expires
1188 /// (e.g., due to `mem::forget`).
1192 /// Panics if the starting point is greater than the end point or if
1193 /// the end point is greater than the length of the vector.
1198 /// use std::collections::VecDeque;
1200 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1201 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
1202 /// assert_eq!(drained, [3]);
1203 /// assert_eq!(v, [1, 2]);
1205 /// // A full range clears all contents
1207 /// assert!(v.is_empty());
1210 #[stable(feature = "drain", since = "1.6.0")]
1211 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1213 R: RangeBounds<usize>,
1217 // When the Drain is first created, the source deque is shortened to
1218 // make sure no uninitialized or moved-from elements are accessible at
1219 // all if the Drain's destructor never gets to run.
1221 // Drain will ptr::read out the values to remove.
1222 // When finished, the remaining data will be copied back to cover the hole,
1223 // and the head/tail values will be restored correctly.
1225 let (drain_tail, drain_head) = self.range_tail_head(range);
1227 // The deque's elements are parted into three segments:
1228 // * self.tail -> drain_tail
1229 // * drain_tail -> drain_head
1230 // * drain_head -> self.head
1232 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1234 // We store drain_tail as self.head, and drain_head and self.head as
1235 // after_tail and after_head respectively on the Drain. This also
1236 // truncates the effective array such that if the Drain is leaked, we
1237 // have forgotten about the potentially moved values after the start of
1241 // [. . . o o x x o o . . .]
1243 let head = self.head;
1245 // "forget" about the values after the start of the drain until after
1246 // the drain is complete and the Drain destructor is run.
1247 self.head = drain_tail;
1250 deque: NonNull::from(&mut *self),
1251 after_tail: drain_head,
1256 // Crucially, we only create shared references from `self` here and read from
1257 // it. We do not write to `self` nor reborrow to a mutable reference.
1258 // Hence the raw pointer we created above, for `deque`, remains valid.
1259 ring: unsafe { self.buffer_as_slice() },
1264 /// Clears the `VecDeque`, removing all values.
1269 /// use std::collections::VecDeque;
1271 /// let mut v = VecDeque::new();
1274 /// assert!(v.is_empty());
1276 #[stable(feature = "rust1", since = "1.0.0")]
1278 pub fn clear(&mut self) {
1282 /// Returns `true` if the `VecDeque` contains an element equal to the
1288 /// use std::collections::VecDeque;
1290 /// let mut vector: VecDeque<u32> = VecDeque::new();
1292 /// vector.push_back(0);
1293 /// vector.push_back(1);
1295 /// assert_eq!(vector.contains(&1), true);
1296 /// assert_eq!(vector.contains(&10), false);
1298 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1299 pub fn contains(&self, x: &T) -> bool
1303 let (a, b) = self.as_slices();
1304 a.contains(x) || b.contains(x)
1307 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1313 /// use std::collections::VecDeque;
1315 /// let mut d = VecDeque::new();
1316 /// assert_eq!(d.front(), None);
1320 /// assert_eq!(d.front(), Some(&1));
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 pub fn front(&self) -> Option<&T> {
1324 if !self.is_empty() { Some(&self[0]) } else { None }
1327 /// Provides a mutable reference to the front element, or `None` if the
1328 /// `VecDeque` is empty.
1333 /// use std::collections::VecDeque;
1335 /// let mut d = VecDeque::new();
1336 /// assert_eq!(d.front_mut(), None);
1340 /// match d.front_mut() {
1341 /// Some(x) => *x = 9,
1344 /// assert_eq!(d.front(), Some(&9));
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 pub fn front_mut(&mut self) -> Option<&mut T> {
1348 if !self.is_empty() { Some(&mut self[0]) } else { None }
1351 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1357 /// use std::collections::VecDeque;
1359 /// let mut d = VecDeque::new();
1360 /// assert_eq!(d.back(), None);
1364 /// assert_eq!(d.back(), Some(&2));
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 pub fn back(&self) -> Option<&T> {
1368 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
1371 /// Provides a mutable reference to the back element, or `None` if the
1372 /// `VecDeque` is empty.
1377 /// use std::collections::VecDeque;
1379 /// let mut d = VecDeque::new();
1380 /// assert_eq!(d.back(), None);
1384 /// match d.back_mut() {
1385 /// Some(x) => *x = 9,
1388 /// assert_eq!(d.back(), Some(&9));
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 pub fn back_mut(&mut self) -> Option<&mut T> {
1392 let len = self.len();
1393 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
1396 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1402 /// use std::collections::VecDeque;
1404 /// let mut d = VecDeque::new();
1408 /// assert_eq!(d.pop_front(), Some(1));
1409 /// assert_eq!(d.pop_front(), Some(2));
1410 /// assert_eq!(d.pop_front(), None);
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 pub fn pop_front(&mut self) -> Option<T> {
1414 if self.is_empty() {
1417 let tail = self.tail;
1418 self.tail = self.wrap_add(self.tail, 1);
1419 unsafe { Some(self.buffer_read(tail)) }
1423 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1429 /// use std::collections::VecDeque;
1431 /// let mut buf = VecDeque::new();
1432 /// assert_eq!(buf.pop_back(), None);
1433 /// buf.push_back(1);
1434 /// buf.push_back(3);
1435 /// assert_eq!(buf.pop_back(), Some(3));
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 pub fn pop_back(&mut self) -> Option<T> {
1439 if self.is_empty() {
1442 self.head = self.wrap_sub(self.head, 1);
1443 let head = self.head;
1444 unsafe { Some(self.buffer_read(head)) }
1448 /// Prepends an element to the `VecDeque`.
1453 /// use std::collections::VecDeque;
1455 /// let mut d = VecDeque::new();
1456 /// d.push_front(1);
1457 /// d.push_front(2);
1458 /// assert_eq!(d.front(), Some(&2));
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 pub fn push_front(&mut self, value: T) {
1466 self.tail = self.wrap_sub(self.tail, 1);
1467 let tail = self.tail;
1469 self.buffer_write(tail, value);
1473 /// Appends an element to the back of the `VecDeque`.
1478 /// use std::collections::VecDeque;
1480 /// let mut buf = VecDeque::new();
1481 /// buf.push_back(1);
1482 /// buf.push_back(3);
1483 /// assert_eq!(3, *buf.back().unwrap());
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 pub fn push_back(&mut self, value: T) {
1491 let head = self.head;
1492 self.head = self.wrap_add(self.head, 1);
1493 unsafe { self.buffer_write(head, value) }
1497 fn is_contiguous(&self) -> bool {
1498 self.tail <= self.head
1501 /// Removes an element from anywhere in the `VecDeque` and returns it,
1502 /// replacing it with the first element.
1504 /// This does not preserve ordering, but is *O*(1).
1506 /// Returns `None` if `index` is out of bounds.
1508 /// Element at index 0 is the front of the queue.
1513 /// use std::collections::VecDeque;
1515 /// let mut buf = VecDeque::new();
1516 /// assert_eq!(buf.swap_remove_front(0), None);
1517 /// buf.push_back(1);
1518 /// buf.push_back(2);
1519 /// buf.push_back(3);
1520 /// assert_eq!(buf, [1, 2, 3]);
1522 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1523 /// assert_eq!(buf, [2, 1]);
1525 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1526 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1527 let length = self.len();
1528 if length > 0 && index < length && index != 0 {
1529 self.swap(index, 0);
1530 } else if index >= length {
1536 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1539 /// This does not preserve ordering, but is *O*(1).
1541 /// Returns `None` if `index` is out of bounds.
1543 /// Element at index 0 is the front of the queue.
1548 /// use std::collections::VecDeque;
1550 /// let mut buf = VecDeque::new();
1551 /// assert_eq!(buf.swap_remove_back(0), None);
1552 /// buf.push_back(1);
1553 /// buf.push_back(2);
1554 /// buf.push_back(3);
1555 /// assert_eq!(buf, [1, 2, 3]);
1557 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1558 /// assert_eq!(buf, [3, 2]);
1560 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1561 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1562 let length = self.len();
1563 if length > 0 && index < length - 1 {
1564 self.swap(index, length - 1);
1565 } else if index >= length {
1571 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1572 /// greater than or equal to `index` towards the back.
1574 /// Element at index 0 is the front of the queue.
1578 /// Panics if `index` is greater than `VecDeque`'s length
1583 /// use std::collections::VecDeque;
1585 /// let mut vec_deque = VecDeque::new();
1586 /// vec_deque.push_back('a');
1587 /// vec_deque.push_back('b');
1588 /// vec_deque.push_back('c');
1589 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1591 /// vec_deque.insert(1, 'd');
1592 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1594 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1595 pub fn insert(&mut self, index: usize, value: T) {
1596 assert!(index <= self.len(), "index out of bounds");
1601 // Move the least number of elements in the ring buffer and insert
1604 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1606 // There are three main cases:
1607 // Elements are contiguous
1608 // - special case when tail is 0
1609 // Elements are discontiguous and the insert is in the tail section
1610 // Elements are discontiguous and the insert is in the head section
1612 // For each of those there are two more cases:
1613 // Insert is closer to tail
1614 // Insert is closer to head
1616 // Key: H - self.head
1618 // o - Valid element
1619 // I - Insertion element
1620 // A - The element that should be after the insertion point
1621 // M - Indicates element was moved
1623 let idx = self.wrap_add(self.tail, index);
1625 let distance_to_tail = index;
1626 let distance_to_head = self.len() - index;
1628 let contiguous = self.is_contiguous();
1630 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1631 (true, true, _) if index == 0 => {
1636 // [A o o o o o o . . . . . . . . .]
1639 // [A o o o o o o o . . . . . I]
1642 self.tail = self.wrap_sub(self.tail, 1);
1644 (true, true, _) => {
1646 // contiguous, insert closer to tail:
1649 // [. . . o o A o o o o . . . . . .]
1652 // [. . o o I A o o o o . . . . . .]
1655 // contiguous, insert closer to tail and tail is 0:
1659 // [o o A o o o o . . . . . . . . .]
1662 // [o I A o o o o o . . . . . . . o]
1665 let new_tail = self.wrap_sub(self.tail, 1);
1667 self.copy(new_tail, self.tail, 1);
1668 // Already moved the tail, so we only copy `index - 1` elements.
1669 self.copy(self.tail, self.tail + 1, index - 1);
1671 self.tail = new_tail;
1674 (true, false, _) => {
1676 // contiguous, insert closer to head:
1679 // [. . . o o o o A o o . . . . . .]
1682 // [. . . o o o o I A o o . . . . .]
1685 self.copy(idx + 1, idx, self.head - idx);
1686 self.head = self.wrap_add(self.head, 1);
1689 (false, true, true) => {
1691 // discontiguous, insert closer to tail, tail section:
1694 // [o o o o o o . . . . . o o A o o]
1697 // [o o o o o o . . . . o o I A o o]
1700 self.copy(self.tail - 1, self.tail, index);
1704 (false, false, true) => {
1706 // discontiguous, insert closer to head, tail section:
1709 // [o o . . . . . . . o o o o o A o]
1712 // [o o o . . . . . . o o o o o I A]
1715 // copy elements up to new head
1716 self.copy(1, 0, self.head);
1718 // copy last element into empty spot at bottom of buffer
1719 self.copy(0, self.cap() - 1, 1);
1721 // move elements from idx to end forward not including ^ element
1722 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1727 (false, true, false) if idx == 0 => {
1729 // discontiguous, insert is closer to tail, head section,
1730 // and is at index zero in the internal buffer:
1733 // [A o o o o o o o o o . . . o o o]
1736 // [A o o o o o o o o o . . o o o I]
1739 // copy elements up to new tail
1740 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1742 // copy last element into empty spot at bottom of buffer
1743 self.copy(self.cap() - 1, 0, 1);
1748 (false, true, false) => {
1750 // discontiguous, insert closer to tail, head section:
1753 // [o o o A o o o o o o . . . o o o]
1756 // [o o I A o o o o o o . . o o o o]
1759 // copy elements up to new tail
1760 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1762 // copy last element into empty spot at bottom of buffer
1763 self.copy(self.cap() - 1, 0, 1);
1765 // move elements from idx-1 to end forward not including ^ element
1766 self.copy(0, 1, idx - 1);
1771 (false, false, false) => {
1773 // discontiguous, insert closer to head, head section:
1776 // [o o o o A o o . . . . . . o o o]
1779 // [o o o o I A o o . . . . . o o o]
1782 self.copy(idx + 1, idx, self.head - idx);
1788 // tail might've been changed so we need to recalculate
1789 let new_idx = self.wrap_add(self.tail, index);
1791 self.buffer_write(new_idx, value);
1795 /// Removes and returns the element at `index` from the `VecDeque`.
1796 /// Whichever end is closer to the removal point will be moved to make
1797 /// room, and all the affected elements will be moved to new positions.
1798 /// Returns `None` if `index` is out of bounds.
1800 /// Element at index 0 is the front of the queue.
1805 /// use std::collections::VecDeque;
1807 /// let mut buf = VecDeque::new();
1808 /// buf.push_back(1);
1809 /// buf.push_back(2);
1810 /// buf.push_back(3);
1811 /// assert_eq!(buf, [1, 2, 3]);
1813 /// assert_eq!(buf.remove(1), Some(2));
1814 /// assert_eq!(buf, [1, 3]);
1816 #[stable(feature = "rust1", since = "1.0.0")]
1817 pub fn remove(&mut self, index: usize) -> Option<T> {
1818 if self.is_empty() || self.len() <= index {
1822 // There are three main cases:
1823 // Elements are contiguous
1824 // Elements are discontiguous and the removal is in the tail section
1825 // Elements are discontiguous and the removal is in the head section
1826 // - special case when elements are technically contiguous,
1827 // but self.head = 0
1829 // For each of those there are two more cases:
1830 // Insert is closer to tail
1831 // Insert is closer to head
1833 // Key: H - self.head
1835 // o - Valid element
1836 // x - Element marked for removal
1837 // R - Indicates element that is being removed
1838 // M - Indicates element was moved
1840 let idx = self.wrap_add(self.tail, index);
1842 let elem = unsafe { Some(self.buffer_read(idx)) };
1844 let distance_to_tail = index;
1845 let distance_to_head = self.len() - index;
1847 let contiguous = self.is_contiguous();
1849 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1850 (true, true, _) => {
1852 // contiguous, remove closer to tail:
1855 // [. . . o o x o o o o . . . . . .]
1858 // [. . . . o o o o o o . . . . . .]
1861 self.copy(self.tail + 1, self.tail, index);
1865 (true, false, _) => {
1867 // contiguous, remove closer to head:
1870 // [. . . o o o o x o o . . . . . .]
1873 // [. . . o o o o o o . . . . . . .]
1876 self.copy(idx, idx + 1, self.head - idx - 1);
1880 (false, true, true) => {
1882 // discontiguous, remove closer to tail, tail section:
1885 // [o o o o o o . . . . . o o x o o]
1888 // [o o o o o o . . . . . . o o o o]
1891 self.copy(self.tail + 1, self.tail, index);
1892 self.tail = self.wrap_add(self.tail, 1);
1895 (false, false, false) => {
1897 // discontiguous, remove closer to head, head section:
1900 // [o o o o x o o . . . . . . o o o]
1903 // [o o o o o o . . . . . . . o o o]
1906 self.copy(idx, idx + 1, self.head - idx - 1);
1910 (false, false, true) => {
1912 // discontiguous, remove closer to head, tail section:
1915 // [o o o . . . . . . o o o o o x o]
1918 // [o o . . . . . . . o o o o o o o]
1921 // or quasi-discontiguous, remove next to head, tail section:
1924 // [. . . . . . . . . o o o o o x o]
1927 // [. . . . . . . . . o o o o o o .]
1930 // draw in elements in the tail section
1931 self.copy(idx, idx + 1, self.cap() - idx - 1);
1933 // Prevents underflow.
1935 // copy first element into empty spot
1936 self.copy(self.cap() - 1, 0, 1);
1938 // move elements in the head section backwards
1939 self.copy(0, 1, self.head - 1);
1942 self.head = self.wrap_sub(self.head, 1);
1945 (false, true, false) => {
1947 // discontiguous, remove closer to tail, head section:
1950 // [o o x o o o o o o o . . . o o o]
1953 // [o o o o o o o o o o . . . . o o]
1956 // draw in elements up to idx
1957 self.copy(1, 0, idx);
1959 // copy last element into empty spot
1960 self.copy(0, self.cap() - 1, 1);
1962 // move elements from tail to end forward, excluding the last one
1963 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1965 self.tail = self.wrap_add(self.tail, 1);
1973 /// Splits the `VecDeque` into two at the given index.
1975 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1976 /// and the returned `VecDeque` contains elements `[at, len)`.
1978 /// Note that the capacity of `self` does not change.
1980 /// Element at index 0 is the front of the queue.
1984 /// Panics if `at > len`.
1989 /// use std::collections::VecDeque;
1991 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1992 /// let buf2 = buf.split_off(1);
1993 /// assert_eq!(buf, [1]);
1994 /// assert_eq!(buf2, [2, 3]);
1997 #[must_use = "use `.truncate()` if you don't need the other half"]
1998 #[stable(feature = "split_off", since = "1.4.0")]
1999 pub fn split_off(&mut self, at: usize) -> Self {
2000 let len = self.len();
2001 assert!(at <= len, "`at` out of bounds");
2003 let other_len = len - at;
2004 let mut other = VecDeque::with_capacity(other_len);
2007 let (first_half, second_half) = self.as_slices();
2009 let first_len = first_half.len();
2010 let second_len = second_half.len();
2012 // `at` lies in the first half.
2013 let amount_in_first = first_len - at;
2015 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2017 // just take all of the second half.
2018 ptr::copy_nonoverlapping(
2019 second_half.as_ptr(),
2020 other.ptr().add(amount_in_first),
2024 // `at` lies in the second half, need to factor in the elements we skipped
2025 // in the first half.
2026 let offset = at - first_len;
2027 let amount_in_second = second_len - offset;
2028 ptr::copy_nonoverlapping(
2029 second_half.as_ptr().add(offset),
2036 // Cleanup where the ends of the buffers are
2037 self.head = self.wrap_sub(self.head, other_len);
2038 other.head = other.wrap_index(other_len);
2043 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2047 /// Panics if the new number of elements in self overflows a `usize`.
2052 /// use std::collections::VecDeque;
2054 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
2055 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
2056 /// buf.append(&mut buf2);
2057 /// assert_eq!(buf, [1, 2, 3, 4]);
2058 /// assert_eq!(buf2, []);
2061 #[stable(feature = "append", since = "1.4.0")]
2062 pub fn append(&mut self, other: &mut Self) {
2064 self.extend(other.drain(..));
2067 /// Retains only the elements specified by the predicate.
2069 /// In other words, remove all elements `e` such that `f(&e)` returns false.
2070 /// This method operates in place, visiting each element exactly once in the
2071 /// original order, and preserves the order of the retained elements.
2076 /// use std::collections::VecDeque;
2078 /// let mut buf = VecDeque::new();
2079 /// buf.extend(1..5);
2080 /// buf.retain(|&x| x % 2 == 0);
2081 /// assert_eq!(buf, [2, 4]);
2084 /// The exact order may be useful for tracking external state, like an index.
2087 /// use std::collections::VecDeque;
2089 /// let mut buf = VecDeque::new();
2090 /// buf.extend(1..6);
2092 /// let keep = [false, true, true, false, true];
2094 /// buf.retain(|_| (keep[i], i += 1).0);
2095 /// assert_eq!(buf, [2, 3, 5]);
2097 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2098 pub fn retain<F>(&mut self, mut f: F)
2100 F: FnMut(&T) -> bool,
2102 let len = self.len();
2108 self.swap(i - del, i);
2112 self.truncate(len - del);
2116 // This may panic or abort
2118 fn grow(&mut self) {
2120 let old_cap = self.cap();
2121 // Double the buffer size.
2122 self.buf.reserve_exact(old_cap, old_cap);
2123 assert!(self.cap() == old_cap * 2);
2125 self.handle_capacity_increase(old_cap);
2127 debug_assert!(!self.is_full());
2131 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
2132 /// either by removing excess elements from the back or by appending
2133 /// elements generated by calling `generator` to the back.
2138 /// use std::collections::VecDeque;
2140 /// let mut buf = VecDeque::new();
2141 /// buf.push_back(5);
2142 /// buf.push_back(10);
2143 /// buf.push_back(15);
2144 /// assert_eq!(buf, [5, 10, 15]);
2146 /// buf.resize_with(5, Default::default);
2147 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2149 /// buf.resize_with(2, || unreachable!());
2150 /// assert_eq!(buf, [5, 10]);
2152 /// let mut state = 100;
2153 /// buf.resize_with(5, || { state += 1; state });
2154 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2156 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2157 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2158 let len = self.len();
2161 self.extend(repeat_with(generator).take(new_len - len))
2163 self.truncate(new_len);
2167 /// Rearranges the internal storage of this deque so it is one contiguous
2168 /// slice, which is then returned.
2170 /// This method does not allocate and does not change the order of the
2171 /// inserted elements. As it returns a mutable slice, this can be used to
2172 /// sort or binary search a deque.
2174 /// Once the internal storage is contiguous, the [`as_slices`] and
2175 /// [`as_mut_slices`] methods will return the entire contents of the
2176 /// `VecDeque` in a single slice.
2178 /// [`as_slices`]: VecDeque::as_slices
2179 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2183 /// Sorting the content of a deque.
2186 /// use std::collections::VecDeque;
2188 /// let mut buf = VecDeque::with_capacity(15);
2190 /// buf.push_back(2);
2191 /// buf.push_back(1);
2192 /// buf.push_front(3);
2194 /// // sorting the deque
2195 /// buf.make_contiguous().sort();
2196 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2198 /// // sorting it in reverse order
2199 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2200 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2203 /// Getting immutable access to the contiguous slice.
2206 /// use std::collections::VecDeque;
2208 /// let mut buf = VecDeque::new();
2210 /// buf.push_back(2);
2211 /// buf.push_back(1);
2212 /// buf.push_front(3);
2214 /// buf.make_contiguous();
2215 /// if let (slice, &[]) = buf.as_slices() {
2216 /// // we can now be sure that `slice` contains all elements of the deque,
2217 /// // while still having immutable access to `buf`.
2218 /// assert_eq!(buf.len(), slice.len());
2219 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2222 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2223 pub fn make_contiguous(&mut self) -> &mut [T] {
2224 if self.is_contiguous() {
2225 let tail = self.tail;
2226 let head = self.head;
2227 return unsafe { &mut self.buffer_as_mut_slice()[tail..head] };
2230 let buf = self.buf.ptr();
2231 let cap = self.cap();
2232 let len = self.len();
2234 let free = self.tail - self.head;
2235 let tail_len = cap - self.tail;
2237 if free >= tail_len {
2238 // there is enough free space to copy the tail in one go,
2239 // this means that we first shift the head backwards, and then
2240 // copy the tail to the correct position.
2242 // from: DEFGH....ABC
2245 ptr::copy(buf, buf.add(tail_len), self.head);
2247 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2253 } else if free >= self.head {
2254 // there is enough free space to copy the head in one go,
2255 // this means that we first shift the tail forwards, and then
2256 // copy the head to the correct position.
2258 // from: FGH....ABCDE
2261 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2263 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2266 self.tail = self.head;
2267 self.head = self.tail + len;
2270 // free is smaller than both head and tail,
2271 // this means we have to slowly "swap" the tail and the head.
2273 // from: EFGHI...ABCD or HIJK.ABCDEFG
2274 // to: ABCDEFGHI... or ABCDEFGHIJK.
2275 let mut left_edge: usize = 0;
2276 let mut right_edge: usize = self.tail;
2278 // The general problem looks like this
2279 // GHIJKLM...ABCDEF - before any swaps
2280 // ABCDEFM...GHIJKL - after 1 pass of swaps
2281 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2282 // - then restart the algorithm with a new (smaller) store
2283 // Sometimes the temp store is reached when the right edge is at the end
2284 // of the buffer - this means we've hit the right order with fewer swaps!
2287 // ABCDEF.. - after four only swaps we've finished
2288 while left_edge < len && right_edge != cap {
2289 let mut right_offset = 0;
2290 for i in left_edge..right_edge {
2291 right_offset = (i - left_edge) % (cap - right_edge);
2292 let src: isize = (right_edge + right_offset) as isize;
2293 ptr::swap(buf.add(i), buf.offset(src));
2295 let n_ops = right_edge - left_edge;
2297 right_edge += right_offset + 1;
2305 let tail = self.tail;
2306 let head = self.head;
2307 unsafe { &mut self.buffer_as_mut_slice()[tail..head] }
2310 /// Rotates the double-ended queue `mid` places to the left.
2313 /// - Rotates item `mid` into the first position.
2314 /// - Pops the first `mid` items and pushes them to the end.
2315 /// - Rotates `len() - mid` places to the right.
2319 /// If `mid` is greater than `len()`. Note that `mid == len()`
2320 /// does _not_ panic and is a no-op rotation.
2324 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2329 /// use std::collections::VecDeque;
2331 /// let mut buf: VecDeque<_> = (0..10).collect();
2333 /// buf.rotate_left(3);
2334 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2336 /// for i in 1..10 {
2337 /// assert_eq!(i * 3 % 10, buf[0]);
2338 /// buf.rotate_left(3);
2340 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2342 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2343 pub fn rotate_left(&mut self, mid: usize) {
2344 assert!(mid <= self.len());
2345 let k = self.len() - mid;
2347 unsafe { self.rotate_left_inner(mid) }
2349 unsafe { self.rotate_right_inner(k) }
2353 /// Rotates the double-ended queue `k` places to the right.
2356 /// - Rotates the first item into position `k`.
2357 /// - Pops the last `k` items and pushes them to the front.
2358 /// - Rotates `len() - k` places to the left.
2362 /// If `k` is greater than `len()`. Note that `k == len()`
2363 /// does _not_ panic and is a no-op rotation.
2367 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2372 /// use std::collections::VecDeque;
2374 /// let mut buf: VecDeque<_> = (0..10).collect();
2376 /// buf.rotate_right(3);
2377 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2379 /// for i in 1..10 {
2380 /// assert_eq!(0, buf[i * 3 % 10]);
2381 /// buf.rotate_right(3);
2383 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2385 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2386 pub fn rotate_right(&mut self, k: usize) {
2387 assert!(k <= self.len());
2388 let mid = self.len() - k;
2390 unsafe { self.rotate_right_inner(k) }
2392 unsafe { self.rotate_left_inner(mid) }
2396 // SAFETY: the following two methods require that the rotation amount
2397 // be less than half the length of the deque.
2399 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2400 // but than `min` is never more than half the capacity, regardless of x,
2401 // so it's sound to call here because we're calling with something
2402 // less than half the length, which is never above half the capacity.
2404 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2405 debug_assert!(mid * 2 <= self.len());
2407 self.wrap_copy(self.head, self.tail, mid);
2409 self.head = self.wrap_add(self.head, mid);
2410 self.tail = self.wrap_add(self.tail, mid);
2413 unsafe fn rotate_right_inner(&mut self, k: usize) {
2414 debug_assert!(k * 2 <= self.len());
2415 self.head = self.wrap_sub(self.head, k);
2416 self.tail = self.wrap_sub(self.tail, k);
2418 self.wrap_copy(self.tail, self.head, k);
2423 impl<T: Clone> VecDeque<T> {
2424 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2425 /// either by removing excess elements from the back or by appending clones of `value`
2431 /// use std::collections::VecDeque;
2433 /// let mut buf = VecDeque::new();
2434 /// buf.push_back(5);
2435 /// buf.push_back(10);
2436 /// buf.push_back(15);
2437 /// assert_eq!(buf, [5, 10, 15]);
2439 /// buf.resize(2, 0);
2440 /// assert_eq!(buf, [5, 10]);
2442 /// buf.resize(5, 20);
2443 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2445 #[stable(feature = "deque_extras", since = "1.16.0")]
2446 pub fn resize(&mut self, new_len: usize, value: T) {
2447 self.resize_with(new_len, || value.clone());
2451 /// Returns the index in the underlying buffer for a given logical element index.
2453 fn wrap_index(index: usize, size: usize) -> usize {
2454 // size is always a power of 2
2455 debug_assert!(size.is_power_of_two());
2459 /// Returns the two slices that cover the `VecDeque`'s valid range
2460 trait RingSlices: Sized {
2461 fn slice(self, from: usize, to: usize) -> Self;
2462 fn split_at(self, i: usize) -> (Self, Self);
2464 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
2465 let contiguous = tail <= head;
2467 let (empty, buf) = buf.split_at(0);
2468 (buf.slice(tail, head), empty)
2470 let (mid, right) = buf.split_at(tail);
2471 let (left, _) = mid.split_at(head);
2477 impl<T> RingSlices for &[T] {
2478 fn slice(self, from: usize, to: usize) -> Self {
2481 fn split_at(self, i: usize) -> (Self, Self) {
2486 impl<T> RingSlices for &mut [T] {
2487 fn slice(self, from: usize, to: usize) -> Self {
2490 fn split_at(self, i: usize) -> (Self, Self) {
2491 (*self).split_at_mut(i)
2495 /// Calculate the number of elements left to be read in the buffer
2497 fn count(tail: usize, head: usize, size: usize) -> usize {
2498 // size is always a power of 2
2499 (head.wrapping_sub(tail)) & (size - 1)
2502 /// An iterator over the elements of a `VecDeque`.
2504 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
2505 /// documentation for more.
2507 /// [`iter`]: VecDeque::iter
2508 #[stable(feature = "rust1", since = "1.0.0")]
2509 pub struct Iter<'a, T: 'a> {
2515 #[stable(feature = "collection_debug", since = "1.17.0")]
2516 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
2517 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2518 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2519 f.debug_tuple("Iter").field(&front).field(&back).finish()
2523 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2524 #[stable(feature = "rust1", since = "1.0.0")]
2525 impl<T> Clone for Iter<'_, T> {
2526 fn clone(&self) -> Self {
2527 Iter { ring: self.ring, tail: self.tail, head: self.head }
2531 #[stable(feature = "rust1", since = "1.0.0")]
2532 impl<'a, T> Iterator for Iter<'a, T> {
2536 fn next(&mut self) -> Option<&'a T> {
2537 if self.tail == self.head {
2540 let tail = self.tail;
2541 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2542 unsafe { Some(self.ring.get_unchecked(tail)) }
2546 fn size_hint(&self) -> (usize, Option<usize>) {
2547 let len = count(self.tail, self.head, self.ring.len());
2551 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2553 F: FnMut(Acc, Self::Item) -> Acc,
2555 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2556 accum = front.iter().fold(accum, &mut f);
2557 back.iter().fold(accum, &mut f)
2560 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2563 F: FnMut(B, Self::Item) -> R,
2566 let (mut iter, final_res);
2567 if self.tail <= self.head {
2568 // single slice self.ring[self.tail..self.head]
2569 iter = self.ring[self.tail..self.head].iter();
2570 final_res = iter.try_fold(init, &mut f);
2572 // two slices: self.ring[self.tail..], self.ring[..self.head]
2573 let (front, back) = self.ring.split_at(self.tail);
2574 let mut back_iter = back.iter();
2575 let res = back_iter.try_fold(init, &mut f);
2576 let len = self.ring.len();
2577 self.tail = (self.ring.len() - back_iter.len()) & (len - 1);
2578 iter = front[..self.head].iter();
2579 final_res = iter.try_fold(res?, &mut f);
2581 self.tail = self.head - iter.len();
2585 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2586 if n >= count(self.tail, self.head, self.ring.len()) {
2587 self.tail = self.head;
2590 self.tail = wrap_index(self.tail.wrapping_add(n), self.ring.len());
2596 fn last(mut self) -> Option<&'a T> {
2601 #[stable(feature = "rust1", since = "1.0.0")]
2602 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2604 fn next_back(&mut self) -> Option<&'a T> {
2605 if self.tail == self.head {
2608 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2609 unsafe { Some(self.ring.get_unchecked(self.head)) }
2612 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2614 F: FnMut(Acc, Self::Item) -> Acc,
2616 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2617 accum = back.iter().rfold(accum, &mut f);
2618 front.iter().rfold(accum, &mut f)
2621 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
2624 F: FnMut(B, Self::Item) -> R,
2627 let (mut iter, final_res);
2628 if self.tail <= self.head {
2629 // single slice self.ring[self.tail..self.head]
2630 iter = self.ring[self.tail..self.head].iter();
2631 final_res = iter.try_rfold(init, &mut f);
2633 // two slices: self.ring[self.tail..], self.ring[..self.head]
2634 let (front, back) = self.ring.split_at(self.tail);
2635 let mut front_iter = front[..self.head].iter();
2636 let res = front_iter.try_rfold(init, &mut f);
2637 self.head = front_iter.len();
2639 final_res = iter.try_rfold(res?, &mut f);
2641 self.head = self.tail + iter.len();
2646 #[stable(feature = "rust1", since = "1.0.0")]
2647 impl<T> ExactSizeIterator for Iter<'_, T> {
2648 fn is_empty(&self) -> bool {
2649 self.head == self.tail
2653 #[stable(feature = "fused", since = "1.26.0")]
2654 impl<T> FusedIterator for Iter<'_, T> {}
2656 /// A mutable iterator over the elements of a `VecDeque`.
2658 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2659 /// documentation for more.
2661 /// [`iter_mut`]: VecDeque::iter_mut
2662 #[stable(feature = "rust1", since = "1.0.0")]
2663 pub struct IterMut<'a, T: 'a> {
2669 #[stable(feature = "collection_debug", since = "1.17.0")]
2670 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
2671 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2672 let (front, back) = RingSlices::ring_slices(&*self.ring, self.head, self.tail);
2673 f.debug_tuple("IterMut").field(&front).field(&back).finish()
2677 #[stable(feature = "rust1", since = "1.0.0")]
2678 impl<'a, T> Iterator for IterMut<'a, T> {
2679 type Item = &'a mut T;
2682 fn next(&mut self) -> Option<&'a mut T> {
2683 if self.tail == self.head {
2686 let tail = self.tail;
2687 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2690 let elem = self.ring.get_unchecked_mut(tail);
2691 Some(&mut *(elem as *mut _))
2696 fn size_hint(&self) -> (usize, Option<usize>) {
2697 let len = count(self.tail, self.head, self.ring.len());
2701 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2703 F: FnMut(Acc, Self::Item) -> Acc,
2705 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2706 accum = front.iter_mut().fold(accum, &mut f);
2707 back.iter_mut().fold(accum, &mut f)
2710 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2711 if n >= count(self.tail, self.head, self.ring.len()) {
2712 self.tail = self.head;
2715 self.tail = wrap_index(self.tail.wrapping_add(n), self.ring.len());
2721 fn last(mut self) -> Option<&'a mut T> {
2726 #[stable(feature = "rust1", since = "1.0.0")]
2727 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2729 fn next_back(&mut self) -> Option<&'a mut T> {
2730 if self.tail == self.head {
2733 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2736 let elem = self.ring.get_unchecked_mut(self.head);
2737 Some(&mut *(elem as *mut _))
2741 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2743 F: FnMut(Acc, Self::Item) -> Acc,
2745 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2746 accum = back.iter_mut().rfold(accum, &mut f);
2747 front.iter_mut().rfold(accum, &mut f)
2751 #[stable(feature = "rust1", since = "1.0.0")]
2752 impl<T> ExactSizeIterator for IterMut<'_, T> {
2753 fn is_empty(&self) -> bool {
2754 self.head == self.tail
2758 #[stable(feature = "fused", since = "1.26.0")]
2759 impl<T> FusedIterator for IterMut<'_, T> {}
2761 /// An owning iterator over the elements of a `VecDeque`.
2763 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`]
2764 /// (provided by the `IntoIterator` trait). See its documentation for more.
2766 /// [`into_iter`]: VecDeque::into_iter
2768 #[stable(feature = "rust1", since = "1.0.0")]
2769 pub struct IntoIter<T> {
2773 #[stable(feature = "collection_debug", since = "1.17.0")]
2774 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2775 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2776 f.debug_tuple("IntoIter").field(&self.inner).finish()
2780 #[stable(feature = "rust1", since = "1.0.0")]
2781 impl<T> Iterator for IntoIter<T> {
2785 fn next(&mut self) -> Option<T> {
2786 self.inner.pop_front()
2790 fn size_hint(&self) -> (usize, Option<usize>) {
2791 let len = self.inner.len();
2796 #[stable(feature = "rust1", since = "1.0.0")]
2797 impl<T> DoubleEndedIterator for IntoIter<T> {
2799 fn next_back(&mut self) -> Option<T> {
2800 self.inner.pop_back()
2804 #[stable(feature = "rust1", since = "1.0.0")]
2805 impl<T> ExactSizeIterator for IntoIter<T> {
2806 fn is_empty(&self) -> bool {
2807 self.inner.is_empty()
2811 #[stable(feature = "fused", since = "1.26.0")]
2812 impl<T> FusedIterator for IntoIter<T> {}
2814 #[stable(feature = "rust1", since = "1.0.0")]
2815 impl<A: PartialEq> PartialEq for VecDeque<A> {
2816 fn eq(&self, other: &VecDeque<A>) -> bool {
2817 if self.len() != other.len() {
2820 let (sa, sb) = self.as_slices();
2821 let (oa, ob) = other.as_slices();
2822 if sa.len() == oa.len() {
2823 sa == oa && sb == ob
2824 } else if sa.len() < oa.len() {
2825 // Always divisible in three sections, for example:
2826 // self: [a b c|d e f]
2827 // other: [0 1 2 3|4 5]
2828 // front = 3, mid = 1,
2829 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2830 let front = sa.len();
2831 let mid = oa.len() - front;
2833 let (oa_front, oa_mid) = oa.split_at(front);
2834 let (sb_mid, sb_back) = sb.split_at(mid);
2835 debug_assert_eq!(sa.len(), oa_front.len());
2836 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2837 debug_assert_eq!(sb_back.len(), ob.len());
2838 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2840 let front = oa.len();
2841 let mid = sa.len() - front;
2843 let (sa_front, sa_mid) = sa.split_at(front);
2844 let (ob_mid, ob_back) = ob.split_at(mid);
2845 debug_assert_eq!(sa_front.len(), oa.len());
2846 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2847 debug_assert_eq!(sb.len(), ob_back.len());
2848 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2853 #[stable(feature = "rust1", since = "1.0.0")]
2854 impl<A: Eq> Eq for VecDeque<A> {}
2856 macro_rules! __impl_slice_eq1 {
2857 ([$($vars:tt)*] $lhs:ty, $rhs:ty, $($constraints:tt)*) => {
2858 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2859 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2864 fn eq(&self, other: &$rhs) -> bool {
2865 if self.len() != other.len() {
2868 let (sa, sb) = self.as_slices();
2869 let (oa, ob) = other[..].split_at(sa.len());
2870 sa == oa && sb == ob
2876 __impl_slice_eq1! { [] VecDeque<A>, Vec<B>, }
2877 __impl_slice_eq1! { [] VecDeque<A>, &[B], }
2878 __impl_slice_eq1! { [] VecDeque<A>, &mut [B], }
2879 __impl_slice_eq1! { [const N: usize] VecDeque<A>, [B; N], }
2880 __impl_slice_eq1! { [const N: usize] VecDeque<A>, &[B; N], }
2881 __impl_slice_eq1! { [const N: usize] VecDeque<A>, &mut [B; N], }
2883 #[stable(feature = "rust1", since = "1.0.0")]
2884 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2885 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2886 self.iter().partial_cmp(other.iter())
2890 #[stable(feature = "rust1", since = "1.0.0")]
2891 impl<A: Ord> Ord for VecDeque<A> {
2893 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2894 self.iter().cmp(other.iter())
2898 #[stable(feature = "rust1", since = "1.0.0")]
2899 impl<A: Hash> Hash for VecDeque<A> {
2900 fn hash<H: Hasher>(&self, state: &mut H) {
2901 self.len().hash(state);
2902 let (a, b) = self.as_slices();
2903 Hash::hash_slice(a, state);
2904 Hash::hash_slice(b, state);
2908 #[stable(feature = "rust1", since = "1.0.0")]
2909 impl<A> Index<usize> for VecDeque<A> {
2913 fn index(&self, index: usize) -> &A {
2914 self.get(index).expect("Out of bounds access")
2918 #[stable(feature = "rust1", since = "1.0.0")]
2919 impl<A> IndexMut<usize> for VecDeque<A> {
2921 fn index_mut(&mut self, index: usize) -> &mut A {
2922 self.get_mut(index).expect("Out of bounds access")
2926 #[stable(feature = "rust1", since = "1.0.0")]
2927 impl<A> FromIterator<A> for VecDeque<A> {
2928 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2929 let iterator = iter.into_iter();
2930 let (lower, _) = iterator.size_hint();
2931 let mut deq = VecDeque::with_capacity(lower);
2932 deq.extend(iterator);
2937 #[stable(feature = "rust1", since = "1.0.0")]
2938 impl<T> IntoIterator for VecDeque<T> {
2940 type IntoIter = IntoIter<T>;
2942 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2944 fn into_iter(self) -> IntoIter<T> {
2945 IntoIter { inner: self }
2949 #[stable(feature = "rust1", since = "1.0.0")]
2950 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2952 type IntoIter = Iter<'a, T>;
2954 fn into_iter(self) -> Iter<'a, T> {
2959 #[stable(feature = "rust1", since = "1.0.0")]
2960 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2961 type Item = &'a mut T;
2962 type IntoIter = IterMut<'a, T>;
2964 fn into_iter(self) -> IterMut<'a, T> {
2969 #[stable(feature = "rust1", since = "1.0.0")]
2970 impl<A> Extend<A> for VecDeque<A> {
2971 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2972 // This function should be the moral equivalent of:
2974 // for item in iter.into_iter() {
2975 // self.push_back(item);
2977 let mut iter = iter.into_iter();
2978 while let Some(element) = iter.next() {
2979 if self.len() == self.capacity() {
2980 let (lower, _) = iter.size_hint();
2981 self.reserve(lower.saturating_add(1));
2984 let head = self.head;
2985 self.head = self.wrap_add(self.head, 1);
2987 self.buffer_write(head, element);
2993 fn extend_one(&mut self, elem: A) {
2994 self.push_back(elem);
2998 fn extend_reserve(&mut self, additional: usize) {
2999 self.reserve(additional);
3003 #[stable(feature = "extend_ref", since = "1.2.0")]
3004 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
3005 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3006 self.extend(iter.into_iter().cloned());
3010 fn extend_one(&mut self, &elem: &T) {
3011 self.push_back(elem);
3015 fn extend_reserve(&mut self, additional: usize) {
3016 self.reserve(additional);
3020 #[stable(feature = "rust1", since = "1.0.0")]
3021 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
3022 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3023 f.debug_list().entries(self).finish()
3027 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3028 impl<T> From<Vec<T>> for VecDeque<T> {
3029 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3031 /// [`Vec<T>`]: crate::vec::Vec
3032 /// [`VecDeque<T>`]: crate::collections::VecDeque
3034 /// This avoids reallocating where possible, but the conditions for that are
3035 /// strict, and subject to change, and so shouldn't be relied upon unless the
3036 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
3037 fn from(other: Vec<T>) -> Self {
3039 let mut other = ManuallyDrop::new(other);
3040 let other_buf = other.as_mut_ptr();
3041 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
3042 let len = other.len();
3044 // We need to extend the buf if it's not a power of two, too small
3045 // or doesn't have at least one free space
3046 if !buf.capacity().is_power_of_two()
3047 || (buf.capacity() < (MINIMUM_CAPACITY + 1))
3048 || (buf.capacity() == len)
3050 let cap = cmp::max(buf.capacity() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
3051 buf.reserve_exact(len, cap - len);
3054 VecDeque { tail: 0, head: len, buf }
3059 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3060 impl<T> From<VecDeque<T>> for Vec<T> {
3061 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
3063 /// [`Vec<T>`]: crate::vec::Vec
3064 /// [`VecDeque<T>`]: crate::collections::VecDeque
3066 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
3067 /// the circular buffer doesn't happen to be at the beginning of the allocation.
3072 /// use std::collections::VecDeque;
3074 /// // This one is *O*(1).
3075 /// let deque: VecDeque<_> = (1..5).collect();
3076 /// let ptr = deque.as_slices().0.as_ptr();
3077 /// let vec = Vec::from(deque);
3078 /// assert_eq!(vec, [1, 2, 3, 4]);
3079 /// assert_eq!(vec.as_ptr(), ptr);
3081 /// // This one needs data rearranging.
3082 /// let mut deque: VecDeque<_> = (1..5).collect();
3083 /// deque.push_front(9);
3084 /// deque.push_front(8);
3085 /// let ptr = deque.as_slices().1.as_ptr();
3086 /// let vec = Vec::from(deque);
3087 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
3088 /// assert_eq!(vec.as_ptr(), ptr);
3090 fn from(mut other: VecDeque<T>) -> Self {
3091 other.make_contiguous();
3094 let other = ManuallyDrop::new(other);
3095 let buf = other.buf.ptr();
3096 let len = other.len();
3097 let cap = other.cap();
3099 if other.head != 0 {
3100 ptr::copy(buf.add(other.tail), buf, len);
3102 Vec::from_raw_parts(buf, len, cap)