1 // ignore-tidy-filelength
3 //! A double-ended queue implemented with a growable ring buffer.
5 //! This queue has `O(1)` amortized inserts and removals from both ends of the
6 //! container. It also has `O(1)` indexing like a vector. The contained elements
7 //! are not required to be copyable, and the queue will be sendable if the
8 //! contained type is sendable.
10 #![stable(feature = "rust1", since = "1.0.0")]
12 use core::cmp::{self, Ordering};
14 use core::iter::{repeat_with, FromIterator, FusedIterator};
16 use core::ops::Bound::{Excluded, Included, Unbounded};
17 use core::ops::{Index, IndexMut, RangeBounds, Try};
18 use core::ptr::{self, NonNull};
20 use core::hash::{Hash, Hasher};
22 use crate::collections::CollectionAllocErr;
23 use crate::raw_vec::RawVec;
26 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
27 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
28 #[cfg(target_pointer_width = "16")]
29 const MAXIMUM_ZST_CAPACITY: usize = 1 << (16 - 1); // Largest possible power of two
30 #[cfg(target_pointer_width = "32")]
31 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
32 #[cfg(target_pointer_width = "64")]
33 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
35 /// A double-ended queue implemented with a growable ring buffer.
37 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
38 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
39 /// push onto the back in this manner, and iterating over `VecDeque` goes front
42 /// [`push_back`]: #method.push_back
43 /// [`pop_front`]: #method.pop_front
44 /// [`extend`]: #method.extend
45 /// [`append`]: #method.append
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub struct VecDeque<T> {
48 // tail and head are pointers into the buffer. Tail always points
49 // to the first element that could be read, Head always points
50 // to where data should be written.
51 // If tail == head the buffer is empty. The length of the ringbuffer
52 // is defined as the distance between the two.
58 #[stable(feature = "rust1", since = "1.0.0")]
59 impl<T: Clone> Clone for VecDeque<T> {
60 fn clone(&self) -> VecDeque<T> {
61 self.iter().cloned().collect()
65 #[stable(feature = "rust1", since = "1.0.0")]
66 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
68 let (front, back) = self.as_mut_slices();
71 ptr::drop_in_place(front);
72 ptr::drop_in_place(back);
74 // RawVec handles deallocation
78 #[stable(feature = "rust1", since = "1.0.0")]
79 impl<T> Default for VecDeque<T> {
80 /// Creates an empty `VecDeque<T>`.
82 fn default() -> VecDeque<T> {
88 /// Marginally more convenient
90 fn ptr(&self) -> *mut T {
94 /// Marginally more convenient
96 fn cap(&self) -> usize {
97 if mem::size_of::<T>() == 0 {
98 // For zero sized types, we are always at maximum capacity
105 /// Turn ptr into a slice
107 unsafe fn buffer_as_slice(&self) -> &[T] {
108 slice::from_raw_parts(self.ptr(), self.cap())
111 /// Turn ptr into a mut slice
113 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
114 slice::from_raw_parts_mut(self.ptr(), self.cap())
117 /// Moves an element out of the buffer
119 unsafe fn buffer_read(&mut self, off: usize) -> T {
120 ptr::read(self.ptr().add(off))
123 /// Writes an element into the buffer, moving it.
125 unsafe fn buffer_write(&mut self, off: usize, value: T) {
126 ptr::write(self.ptr().add(off), value);
129 /// Returns `true` if the buffer is at full capacity.
131 fn is_full(&self) -> bool {
132 self.cap() - self.len() == 1
135 /// Returns the index in the underlying buffer for a given logical element
138 fn wrap_index(&self, idx: usize) -> usize {
139 wrap_index(idx, self.cap())
142 /// Returns the index in the underlying buffer for a given logical element
145 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
146 wrap_index(idx.wrapping_add(addend), self.cap())
149 /// Returns the index in the underlying buffer for a given logical element
150 /// index - subtrahend.
152 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
153 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
156 /// Copies a contiguous block of memory len long from src to dst
158 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
159 debug_assert!(dst + len <= self.cap(),
160 "cpy dst={} src={} len={} cap={}",
165 debug_assert!(src + len <= self.cap(),
166 "cpy dst={} src={} len={} cap={}",
171 ptr::copy(self.ptr().add(src),
176 /// Copies a contiguous block of memory len long from src to dst
178 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
179 debug_assert!(dst + len <= self.cap(),
180 "cno dst={} src={} len={} cap={}",
185 debug_assert!(src + len <= self.cap(),
186 "cno dst={} src={} len={} cap={}",
191 ptr::copy_nonoverlapping(self.ptr().add(src),
196 /// Copies a potentially wrapping block of memory len long from src to dest.
197 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
198 /// most one continuous overlapping region between src and dest).
199 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
201 fn diff(a: usize, b: usize) -> usize {
202 if a <= b { b - a } else { a - b }
204 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
205 "wrc dst={} src={} len={} cap={}",
211 if src == dst || len == 0 {
215 let dst_after_src = self.wrap_sub(dst, src) < len;
217 let src_pre_wrap_len = self.cap() - src;
218 let dst_pre_wrap_len = self.cap() - dst;
219 let src_wraps = src_pre_wrap_len < len;
220 let dst_wraps = dst_pre_wrap_len < len;
222 match (dst_after_src, src_wraps, dst_wraps) {
223 (_, false, false) => {
224 // src doesn't wrap, dst doesn't wrap
227 // 1 [_ _ A A B B C C _]
228 // 2 [_ _ A A A A B B _]
231 self.copy(dst, src, len);
233 (false, false, true) => {
234 // dst before src, src doesn't wrap, dst wraps
237 // 1 [A A B B _ _ _ C C]
238 // 2 [A A B B _ _ _ A A]
239 // 3 [B B B B _ _ _ A A]
242 self.copy(dst, src, dst_pre_wrap_len);
243 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
245 (true, false, true) => {
246 // src before dst, src doesn't wrap, dst wraps
249 // 1 [C C _ _ _ A A B B]
250 // 2 [B B _ _ _ A A B B]
251 // 3 [B B _ _ _ A A A A]
254 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
255 self.copy(dst, src, dst_pre_wrap_len);
257 (false, true, false) => {
258 // dst before src, src wraps, dst doesn't wrap
261 // 1 [C C _ _ _ A A B B]
262 // 2 [C C _ _ _ B B B B]
263 // 3 [C C _ _ _ B B C C]
266 self.copy(dst, src, src_pre_wrap_len);
267 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
269 (true, true, false) => {
270 // src before dst, src wraps, dst doesn't wrap
273 // 1 [A A B B _ _ _ C C]
274 // 2 [A A A A _ _ _ C C]
275 // 3 [C C A A _ _ _ C C]
278 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
279 self.copy(dst, src, src_pre_wrap_len);
281 (false, true, true) => {
282 // dst before src, src wraps, dst wraps
285 // 1 [A B C D _ E F G H]
286 // 2 [A B C D _ E G H H]
287 // 3 [A B C D _ E G H A]
288 // 4 [B C C D _ E G H A]
291 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
292 let delta = dst_pre_wrap_len - src_pre_wrap_len;
293 self.copy(dst, src, src_pre_wrap_len);
294 self.copy(dst + src_pre_wrap_len, 0, delta);
295 self.copy(0, delta, len - dst_pre_wrap_len);
297 (true, true, true) => {
298 // src before dst, src wraps, dst wraps
301 // 1 [A B C D _ E F G H]
302 // 2 [A A B D _ E F G H]
303 // 3 [H A B D _ E F G H]
304 // 4 [H A B D _ E F F G]
307 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
308 let delta = src_pre_wrap_len - dst_pre_wrap_len;
309 self.copy(delta, 0, len - src_pre_wrap_len);
310 self.copy(0, self.cap() - delta, delta);
311 self.copy(dst, src, dst_pre_wrap_len);
316 /// Frobs the head and tail sections around to handle the fact that we
317 /// just reallocated. Unsafe because it trusts old_capacity.
319 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
320 let new_capacity = self.cap();
322 // Move the shortest contiguous section of the ring buffer
324 // [o o o o o o o . ]
326 // A [o o o o o o o . . . . . . . . . ]
328 // [o o . o o o o o ]
330 // B [. . . o o o o o o o . . . . . . ]
332 // [o o o o o . o o ]
334 // C [o o o o o . . . . . . . . . o o ]
336 if self.tail <= self.head {
339 } else if self.head < old_capacity - self.tail {
341 self.copy_nonoverlapping(old_capacity, 0, self.head);
342 self.head += old_capacity;
343 debug_assert!(self.head > self.tail);
346 let new_tail = new_capacity - (old_capacity - self.tail);
347 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
348 self.tail = new_tail;
349 debug_assert!(self.head < self.tail);
351 debug_assert!(self.head < self.cap());
352 debug_assert!(self.tail < self.cap());
353 debug_assert!(self.cap().count_ones() == 1);
357 impl<T> VecDeque<T> {
358 /// Creates an empty `VecDeque`.
363 /// use std::collections::VecDeque;
365 /// let vector: VecDeque<u32> = VecDeque::new();
367 #[stable(feature = "rust1", since = "1.0.0")]
368 pub fn new() -> VecDeque<T> {
369 VecDeque::with_capacity(INITIAL_CAPACITY)
372 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
377 /// use std::collections::VecDeque;
379 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
381 #[stable(feature = "rust1", since = "1.0.0")]
382 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
383 // +1 since the ringbuffer always leaves one space empty
384 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
385 assert!(cap > capacity, "capacity overflow");
390 buf: RawVec::with_capacity(cap),
394 /// Retrieves an element in the `VecDeque` by index.
396 /// Element at index 0 is the front of the queue.
401 /// use std::collections::VecDeque;
403 /// let mut buf = VecDeque::new();
404 /// buf.push_back(3);
405 /// buf.push_back(4);
406 /// buf.push_back(5);
407 /// assert_eq!(buf.get(1), Some(&4));
409 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn get(&self, index: usize) -> Option<&T> {
411 if index < self.len() {
412 let idx = self.wrap_add(self.tail, index);
413 unsafe { Some(&*self.ptr().add(idx)) }
419 /// Retrieves an element in the `VecDeque` mutably by index.
421 /// Element at index 0 is the front of the queue.
426 /// use std::collections::VecDeque;
428 /// let mut buf = VecDeque::new();
429 /// buf.push_back(3);
430 /// buf.push_back(4);
431 /// buf.push_back(5);
432 /// if let Some(elem) = buf.get_mut(1) {
436 /// assert_eq!(buf[1], 7);
438 #[stable(feature = "rust1", since = "1.0.0")]
439 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
440 if index < self.len() {
441 let idx = self.wrap_add(self.tail, index);
442 unsafe { Some(&mut *self.ptr().add(idx)) }
448 /// Swaps elements at indices `i` and `j`.
450 /// `i` and `j` may be equal.
452 /// Element at index 0 is the front of the queue.
456 /// Panics if either index is out of bounds.
461 /// use std::collections::VecDeque;
463 /// let mut buf = VecDeque::new();
464 /// buf.push_back(3);
465 /// buf.push_back(4);
466 /// buf.push_back(5);
467 /// assert_eq!(buf, [3, 4, 5]);
469 /// assert_eq!(buf, [5, 4, 3]);
471 #[stable(feature = "rust1", since = "1.0.0")]
472 pub fn swap(&mut self, i: usize, j: usize) {
473 assert!(i < self.len());
474 assert!(j < self.len());
475 let ri = self.wrap_add(self.tail, i);
476 let rj = self.wrap_add(self.tail, j);
478 ptr::swap(self.ptr().add(ri),
483 /// Returns the number of elements the `VecDeque` can hold without
489 /// use std::collections::VecDeque;
491 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
492 /// assert!(buf.capacity() >= 10);
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn capacity(&self) -> usize {
500 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
501 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
503 /// Note that the allocator may give the collection more space than it requests. Therefore
504 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
505 /// insertions are expected.
509 /// Panics if the new capacity overflows `usize`.
514 /// use std::collections::VecDeque;
516 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
517 /// buf.reserve_exact(10);
518 /// assert!(buf.capacity() >= 11);
521 /// [`reserve`]: #method.reserve
522 #[stable(feature = "rust1", since = "1.0.0")]
523 pub fn reserve_exact(&mut self, additional: usize) {
524 self.reserve(additional);
527 /// Reserves capacity for at least `additional` more elements to be inserted in the given
528 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
532 /// Panics if the new capacity overflows `usize`.
537 /// use std::collections::VecDeque;
539 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
541 /// assert!(buf.capacity() >= 11);
543 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn reserve(&mut self, additional: usize) {
545 let old_cap = self.cap();
546 let used_cap = self.len() + 1;
547 let new_cap = used_cap.checked_add(additional)
548 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
549 .expect("capacity overflow");
551 if new_cap > old_cap {
552 self.buf.reserve_exact(used_cap, new_cap - used_cap);
554 self.handle_capacity_increase(old_cap);
559 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
560 /// be inserted in the given `VecDeque<T>`. After calling `reserve_exact`,
561 /// capacity will be greater than or equal to `self.len() + additional`.
562 /// Does nothing if the capacity is already sufficient.
564 /// Note that the allocator may give the collection more space than it
565 /// requests. Therefore, capacity can not be relied upon to be precisely
566 /// minimal. Prefer `reserve` if future insertions are expected.
570 /// If the capacity overflows, or the allocator reports a failure, then an error
576 /// #![feature(try_reserve)]
577 /// use std::collections::CollectionAllocErr;
578 /// use std::collections::VecDeque;
580 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
581 /// let mut output = VecDeque::new();
583 /// // Pre-reserve the memory, exiting if we can't
584 /// output.try_reserve_exact(data.len())?;
586 /// // Now we know this can't OOM in the middle of our complex work
587 /// output.extend(data.iter().map(|&val| {
588 /// val * 2 + 5 // very complicated
593 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
595 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
596 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
597 self.try_reserve(additional)
600 /// Tries to reserve capacity for at least `additional` more elements to be inserted
601 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
602 /// frequent reallocations. After calling `reserve`, capacity will be
603 /// greater than or equal to `self.len() + additional`. Does nothing if
604 /// capacity is already sufficient.
608 /// If the capacity overflows, or the allocator reports a failure, then an error
614 /// #![feature(try_reserve)]
615 /// use std::collections::CollectionAllocErr;
616 /// use std::collections::VecDeque;
618 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
619 /// let mut output = VecDeque::new();
621 /// // Pre-reserve the memory, exiting if we can't
622 /// output.try_reserve(data.len())?;
624 /// // Now we know this can't OOM in the middle of our complex work
625 /// output.extend(data.iter().map(|&val| {
626 /// val * 2 + 5 // very complicated
631 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
633 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
634 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
635 let old_cap = self.cap();
636 let used_cap = self.len() + 1;
637 let new_cap = used_cap.checked_add(additional)
638 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
639 .ok_or(CollectionAllocErr::CapacityOverflow)?;
641 if new_cap > old_cap {
642 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
644 self.handle_capacity_increase(old_cap);
650 /// Shrinks the capacity of the `VecDeque` as much as possible.
652 /// It will drop down as close as possible to the length but the allocator may still inform the
653 /// `VecDeque` that there is space for a few more elements.
658 /// use std::collections::VecDeque;
660 /// let mut buf = VecDeque::with_capacity(15);
661 /// buf.extend(0..4);
662 /// assert_eq!(buf.capacity(), 15);
663 /// buf.shrink_to_fit();
664 /// assert!(buf.capacity() >= 4);
666 #[stable(feature = "deque_extras_15", since = "1.5.0")]
667 pub fn shrink_to_fit(&mut self) {
671 /// Shrinks the capacity of the `VecDeque` with a lower bound.
673 /// The capacity will remain at least as large as both the length
674 /// and the supplied value.
676 /// Panics if the current capacity is smaller than the supplied
677 /// minimum capacity.
682 /// #![feature(shrink_to)]
683 /// use std::collections::VecDeque;
685 /// let mut buf = VecDeque::with_capacity(15);
686 /// buf.extend(0..4);
687 /// assert_eq!(buf.capacity(), 15);
688 /// buf.shrink_to(6);
689 /// assert!(buf.capacity() >= 6);
690 /// buf.shrink_to(0);
691 /// assert!(buf.capacity() >= 4);
693 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
694 pub fn shrink_to(&mut self, min_capacity: usize) {
695 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
697 // +1 since the ringbuffer always leaves one space empty
698 // len + 1 can't overflow for an existing, well-formed ringbuffer.
699 let target_cap = cmp::max(
700 cmp::max(min_capacity, self.len()) + 1,
702 ).next_power_of_two();
704 if target_cap < self.cap() {
705 // There are three cases of interest:
706 // All elements are out of desired bounds
707 // Elements are contiguous, and head is out of desired bounds
708 // Elements are discontiguous, and tail is out of desired bounds
710 // At all other times, element positions are unaffected.
712 // Indicates that elements at the head should be moved.
713 let head_outside = self.head == 0 || self.head >= target_cap;
714 // Move elements from out of desired bounds (positions after target_cap)
715 if self.tail >= target_cap && head_outside {
717 // [. . . . . . . . o o o o o o o . ]
719 // [o o o o o o o . ]
721 self.copy_nonoverlapping(0, self.tail, self.len());
723 self.head = self.len();
725 } else if self.tail != 0 && self.tail < target_cap && head_outside {
727 // [. . . o o o o o o o . . . . . . ]
729 // [o o . o o o o o ]
730 let len = self.wrap_sub(self.head, target_cap);
732 self.copy_nonoverlapping(0, target_cap, len);
735 debug_assert!(self.head < self.tail);
736 } else if self.tail >= target_cap {
738 // [o o o o o . . . . . . . . . o o ]
740 // [o o o o o . o o ]
741 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
742 let len = self.cap() - self.tail;
743 let new_tail = target_cap - len;
745 self.copy_nonoverlapping(new_tail, self.tail, len);
747 self.tail = new_tail;
748 debug_assert!(self.head < self.tail);
751 self.buf.shrink_to_fit(target_cap);
753 debug_assert!(self.head < self.cap());
754 debug_assert!(self.tail < self.cap());
755 debug_assert!(self.cap().count_ones() == 1);
759 /// Shortens the `VecDeque`, dropping excess elements from the back.
761 /// If `len` is greater than the `VecDeque`'s current length, this has no
767 /// use std::collections::VecDeque;
769 /// let mut buf = VecDeque::new();
770 /// buf.push_back(5);
771 /// buf.push_back(10);
772 /// buf.push_back(15);
773 /// assert_eq!(buf, [5, 10, 15]);
775 /// assert_eq!(buf, [5]);
777 #[stable(feature = "deque_extras", since = "1.16.0")]
778 pub fn truncate(&mut self, len: usize) {
779 for _ in len..self.len() {
784 /// Returns a front-to-back iterator.
789 /// use std::collections::VecDeque;
791 /// let mut buf = VecDeque::new();
792 /// buf.push_back(5);
793 /// buf.push_back(3);
794 /// buf.push_back(4);
795 /// let b: &[_] = &[&5, &3, &4];
796 /// let c: Vec<&i32> = buf.iter().collect();
797 /// assert_eq!(&c[..], b);
799 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn iter(&self) -> Iter<'_, T> {
804 ring: unsafe { self.buffer_as_slice() },
808 /// Returns a front-to-back iterator that returns mutable references.
813 /// use std::collections::VecDeque;
815 /// let mut buf = VecDeque::new();
816 /// buf.push_back(5);
817 /// buf.push_back(3);
818 /// buf.push_back(4);
819 /// for num in buf.iter_mut() {
822 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
823 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
825 #[stable(feature = "rust1", since = "1.0.0")]
826 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
830 ring: unsafe { self.buffer_as_mut_slice() },
834 /// Returns a pair of slices which contain, in order, the contents of the
840 /// use std::collections::VecDeque;
842 /// let mut vector = VecDeque::new();
844 /// vector.push_back(0);
845 /// vector.push_back(1);
846 /// vector.push_back(2);
848 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
850 /// vector.push_front(10);
851 /// vector.push_front(9);
853 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
856 #[stable(feature = "deque_extras_15", since = "1.5.0")]
857 pub fn as_slices(&self) -> (&[T], &[T]) {
859 let buf = self.buffer_as_slice();
860 RingSlices::ring_slices(buf, self.head, self.tail)
864 /// Returns a pair of slices which contain, in order, the contents of the
870 /// use std::collections::VecDeque;
872 /// let mut vector = VecDeque::new();
874 /// vector.push_back(0);
875 /// vector.push_back(1);
877 /// vector.push_front(10);
878 /// vector.push_front(9);
880 /// vector.as_mut_slices().0[0] = 42;
881 /// vector.as_mut_slices().1[0] = 24;
882 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
885 #[stable(feature = "deque_extras_15", since = "1.5.0")]
886 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
888 let head = self.head;
889 let tail = self.tail;
890 let buf = self.buffer_as_mut_slice();
891 RingSlices::ring_slices(buf, head, tail)
895 /// Returns the number of elements in the `VecDeque`.
900 /// use std::collections::VecDeque;
902 /// let mut v = VecDeque::new();
903 /// assert_eq!(v.len(), 0);
905 /// assert_eq!(v.len(), 1);
907 #[stable(feature = "rust1", since = "1.0.0")]
908 pub fn len(&self) -> usize {
909 count(self.tail, self.head, self.cap())
912 /// Returns `true` if the `VecDeque` is empty.
917 /// use std::collections::VecDeque;
919 /// let mut v = VecDeque::new();
920 /// assert!(v.is_empty());
922 /// assert!(!v.is_empty());
924 #[stable(feature = "rust1", since = "1.0.0")]
925 pub fn is_empty(&self) -> bool {
926 self.tail == self.head
929 /// Creates a draining iterator that removes the specified range in the
930 /// `VecDeque` and yields the removed items.
932 /// Note 1: The element range is removed even if the iterator is not
933 /// consumed until the end.
935 /// Note 2: It is unspecified how many elements are removed from the deque,
936 /// if the `Drain` value is not dropped, but the borrow it holds expires
937 /// (e.g., due to `mem::forget`).
941 /// Panics if the starting point is greater than the end point or if
942 /// the end point is greater than the length of the vector.
947 /// use std::collections::VecDeque;
949 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
950 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
951 /// assert_eq!(drained, [3]);
952 /// assert_eq!(v, [1, 2]);
954 /// // A full range clears all contents
956 /// assert!(v.is_empty());
959 #[stable(feature = "drain", since = "1.6.0")]
960 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
961 where R: RangeBounds<usize>
965 // When the Drain is first created, the source deque is shortened to
966 // make sure no uninitialized or moved-from elements are accessible at
967 // all if the Drain's destructor never gets to run.
969 // Drain will ptr::read out the values to remove.
970 // When finished, the remaining data will be copied back to cover the hole,
971 // and the head/tail values will be restored correctly.
973 let len = self.len();
974 let start = match range.start_bound() {
976 Excluded(&n) => n + 1,
979 let end = match range.end_bound() {
980 Included(&n) => n + 1,
984 assert!(start <= end, "drain lower bound was too large");
985 assert!(end <= len, "drain upper bound was too large");
987 // The deque's elements are parted into three segments:
988 // * self.tail -> drain_tail
989 // * drain_tail -> drain_head
990 // * drain_head -> self.head
992 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
994 // We store drain_tail as self.head, and drain_head and self.head as
995 // after_tail and after_head respectively on the Drain. This also
996 // truncates the effective array such that if the Drain is leaked, we
997 // have forgotten about the potentially moved values after the start of
1001 // [. . . o o x x o o . . .]
1003 let drain_tail = self.wrap_add(self.tail, start);
1004 let drain_head = self.wrap_add(self.tail, end);
1005 let head = self.head;
1007 // "forget" about the values after the start of the drain until after
1008 // the drain is complete and the Drain destructor is run.
1009 self.head = drain_tail;
1012 deque: NonNull::from(&mut *self),
1013 after_tail: drain_head,
1018 // Crucially, we only create shared references from `self` here and read from
1019 // it. We do not write to `self` nor reborrow to a mutable reference.
1020 // Hence the raw pointer we created above, for `deque`, remains valid.
1021 ring: unsafe { self.buffer_as_slice() },
1026 /// Clears the `VecDeque`, removing all values.
1031 /// use std::collections::VecDeque;
1033 /// let mut v = VecDeque::new();
1036 /// assert!(v.is_empty());
1038 #[stable(feature = "rust1", since = "1.0.0")]
1040 pub fn clear(&mut self) {
1044 /// Returns `true` if the `VecDeque` contains an element equal to the
1050 /// use std::collections::VecDeque;
1052 /// let mut vector: VecDeque<u32> = VecDeque::new();
1054 /// vector.push_back(0);
1055 /// vector.push_back(1);
1057 /// assert_eq!(vector.contains(&1), true);
1058 /// assert_eq!(vector.contains(&10), false);
1060 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1061 pub fn contains(&self, x: &T) -> bool
1062 where T: PartialEq<T>
1064 let (a, b) = self.as_slices();
1065 a.contains(x) || b.contains(x)
1068 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1074 /// use std::collections::VecDeque;
1076 /// let mut d = VecDeque::new();
1077 /// assert_eq!(d.front(), None);
1081 /// assert_eq!(d.front(), Some(&1));
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 pub fn front(&self) -> Option<&T> {
1085 if !self.is_empty() {
1092 /// Provides a mutable reference to the front element, or `None` if the
1093 /// `VecDeque` is empty.
1098 /// use std::collections::VecDeque;
1100 /// let mut d = VecDeque::new();
1101 /// assert_eq!(d.front_mut(), None);
1105 /// match d.front_mut() {
1106 /// Some(x) => *x = 9,
1109 /// assert_eq!(d.front(), Some(&9));
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 pub fn front_mut(&mut self) -> Option<&mut T> {
1113 if !self.is_empty() {
1120 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1126 /// use std::collections::VecDeque;
1128 /// let mut d = VecDeque::new();
1129 /// assert_eq!(d.back(), None);
1133 /// assert_eq!(d.back(), Some(&2));
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 pub fn back(&self) -> Option<&T> {
1137 if !self.is_empty() {
1138 Some(&self[self.len() - 1])
1144 /// Provides a mutable reference to the back element, or `None` if the
1145 /// `VecDeque` is empty.
1150 /// use std::collections::VecDeque;
1152 /// let mut d = VecDeque::new();
1153 /// assert_eq!(d.back(), None);
1157 /// match d.back_mut() {
1158 /// Some(x) => *x = 9,
1161 /// assert_eq!(d.back(), Some(&9));
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 pub fn back_mut(&mut self) -> Option<&mut T> {
1165 let len = self.len();
1166 if !self.is_empty() {
1167 Some(&mut self[len - 1])
1173 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1179 /// use std::collections::VecDeque;
1181 /// let mut d = VecDeque::new();
1185 /// assert_eq!(d.pop_front(), Some(1));
1186 /// assert_eq!(d.pop_front(), Some(2));
1187 /// assert_eq!(d.pop_front(), None);
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 pub fn pop_front(&mut self) -> Option<T> {
1191 if self.is_empty() {
1194 let tail = self.tail;
1195 self.tail = self.wrap_add(self.tail, 1);
1196 unsafe { Some(self.buffer_read(tail)) }
1200 /// Prepends an element to the `VecDeque`.
1205 /// use std::collections::VecDeque;
1207 /// let mut d = VecDeque::new();
1208 /// d.push_front(1);
1209 /// d.push_front(2);
1210 /// assert_eq!(d.front(), Some(&2));
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 pub fn push_front(&mut self, value: T) {
1214 self.grow_if_necessary();
1216 self.tail = self.wrap_sub(self.tail, 1);
1217 let tail = self.tail;
1219 self.buffer_write(tail, value);
1223 /// Appends an element to the back of the `VecDeque`.
1228 /// use std::collections::VecDeque;
1230 /// let mut buf = VecDeque::new();
1231 /// buf.push_back(1);
1232 /// buf.push_back(3);
1233 /// assert_eq!(3, *buf.back().unwrap());
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 pub fn push_back(&mut self, value: T) {
1237 self.grow_if_necessary();
1239 let head = self.head;
1240 self.head = self.wrap_add(self.head, 1);
1241 unsafe { self.buffer_write(head, value) }
1244 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1250 /// use std::collections::VecDeque;
1252 /// let mut buf = VecDeque::new();
1253 /// assert_eq!(buf.pop_back(), None);
1254 /// buf.push_back(1);
1255 /// buf.push_back(3);
1256 /// assert_eq!(buf.pop_back(), Some(3));
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 pub fn pop_back(&mut self) -> Option<T> {
1260 if self.is_empty() {
1263 self.head = self.wrap_sub(self.head, 1);
1264 let head = self.head;
1265 unsafe { Some(self.buffer_read(head)) }
1270 fn is_contiguous(&self) -> bool {
1271 self.tail <= self.head
1274 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1277 /// This does not preserve ordering, but is O(1).
1279 /// Returns `None` if `index` is out of bounds.
1281 /// Element at index 0 is the front of the queue.
1286 /// use std::collections::VecDeque;
1288 /// let mut buf = VecDeque::new();
1289 /// assert_eq!(buf.swap_remove_back(0), None);
1290 /// buf.push_back(1);
1291 /// buf.push_back(2);
1292 /// buf.push_back(3);
1293 /// assert_eq!(buf, [1, 2, 3]);
1295 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1296 /// assert_eq!(buf, [3, 2]);
1298 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1299 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1300 let length = self.len();
1301 if length > 0 && index < length - 1 {
1302 self.swap(index, length - 1);
1303 } else if index >= length {
1309 /// Removes an element from anywhere in the `VecDeque` and returns it,
1310 /// replacing it with the first element.
1312 /// This does not preserve ordering, but is O(1).
1314 /// Returns `None` if `index` is out of bounds.
1316 /// Element at index 0 is the front of the queue.
1321 /// use std::collections::VecDeque;
1323 /// let mut buf = VecDeque::new();
1324 /// assert_eq!(buf.swap_remove_front(0), None);
1325 /// buf.push_back(1);
1326 /// buf.push_back(2);
1327 /// buf.push_back(3);
1328 /// assert_eq!(buf, [1, 2, 3]);
1330 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1331 /// assert_eq!(buf, [2, 1]);
1333 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1334 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1335 let length = self.len();
1336 if length > 0 && index < length && index != 0 {
1337 self.swap(index, 0);
1338 } else if index >= length {
1344 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1345 /// greater than or equal to `index` towards the back.
1347 /// Element at index 0 is the front of the queue.
1351 /// Panics if `index` is greater than `VecDeque`'s length
1356 /// use std::collections::VecDeque;
1358 /// let mut vec_deque = VecDeque::new();
1359 /// vec_deque.push_back('a');
1360 /// vec_deque.push_back('b');
1361 /// vec_deque.push_back('c');
1362 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1364 /// vec_deque.insert(1, 'd');
1365 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1367 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1368 pub fn insert(&mut self, index: usize, value: T) {
1369 assert!(index <= self.len(), "index out of bounds");
1370 self.grow_if_necessary();
1372 // Move the least number of elements in the ring buffer and insert
1375 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1377 // There are three main cases:
1378 // Elements are contiguous
1379 // - special case when tail is 0
1380 // Elements are discontiguous and the insert is in the tail section
1381 // Elements are discontiguous and the insert is in the head section
1383 // For each of those there are two more cases:
1384 // Insert is closer to tail
1385 // Insert is closer to head
1387 // Key: H - self.head
1389 // o - Valid element
1390 // I - Insertion element
1391 // A - The element that should be after the insertion point
1392 // M - Indicates element was moved
1394 let idx = self.wrap_add(self.tail, index);
1396 let distance_to_tail = index;
1397 let distance_to_head = self.len() - index;
1399 let contiguous = self.is_contiguous();
1401 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1402 (true, true, _) if index == 0 => {
1407 // [A o o o o o o . . . . . . . . .]
1410 // [A o o o o o o o . . . . . I]
1413 self.tail = self.wrap_sub(self.tail, 1);
1415 (true, true, _) => {
1417 // contiguous, insert closer to tail:
1420 // [. . . o o A o o o o . . . . . .]
1423 // [. . o o I A o o o o . . . . . .]
1426 // contiguous, insert closer to tail and tail is 0:
1430 // [o o A o o o o . . . . . . . . .]
1433 // [o I A o o o o o . . . . . . . o]
1436 let new_tail = self.wrap_sub(self.tail, 1);
1438 self.copy(new_tail, self.tail, 1);
1439 // Already moved the tail, so we only copy `index - 1` elements.
1440 self.copy(self.tail, self.tail + 1, index - 1);
1442 self.tail = new_tail;
1445 (true, false, _) => {
1447 // contiguous, insert closer to head:
1450 // [. . . o o o o A o o . . . . . .]
1453 // [. . . o o o o I A o o . . . . .]
1456 self.copy(idx + 1, idx, self.head - idx);
1457 self.head = self.wrap_add(self.head, 1);
1460 (false, true, true) => {
1462 // discontiguous, insert closer to tail, tail section:
1465 // [o o o o o o . . . . . o o A o o]
1468 // [o o o o o o . . . . o o I A o o]
1471 self.copy(self.tail - 1, self.tail, index);
1475 (false, false, true) => {
1477 // discontiguous, insert closer to head, tail section:
1480 // [o o . . . . . . . o o o o o A o]
1483 // [o o o . . . . . . o o o o o I A]
1486 // copy elements up to new head
1487 self.copy(1, 0, self.head);
1489 // copy last element into empty spot at bottom of buffer
1490 self.copy(0, self.cap() - 1, 1);
1492 // move elements from idx to end forward not including ^ element
1493 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1498 (false, true, false) if idx == 0 => {
1500 // discontiguous, insert is closer to tail, head section,
1501 // and is at index zero in the internal buffer:
1504 // [A o o o o o o o o o . . . o o o]
1507 // [A o o o o o o o o o . . o o o I]
1510 // copy elements up to new tail
1511 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1513 // copy last element into empty spot at bottom of buffer
1514 self.copy(self.cap() - 1, 0, 1);
1519 (false, true, false) => {
1521 // discontiguous, insert closer to tail, head section:
1524 // [o o o A o o o o o o . . . o o o]
1527 // [o o I A o o o o o o . . o o o o]
1530 // copy elements up to new tail
1531 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1533 // copy last element into empty spot at bottom of buffer
1534 self.copy(self.cap() - 1, 0, 1);
1536 // move elements from idx-1 to end forward not including ^ element
1537 self.copy(0, 1, idx - 1);
1542 (false, false, false) => {
1544 // discontiguous, insert closer to head, head section:
1547 // [o o o o A o o . . . . . . o o o]
1550 // [o o o o I A o o . . . . . o o o]
1553 self.copy(idx + 1, idx, self.head - idx);
1559 // tail might've been changed so we need to recalculate
1560 let new_idx = self.wrap_add(self.tail, index);
1562 self.buffer_write(new_idx, value);
1566 /// Removes and returns the element at `index` from the `VecDeque`.
1567 /// Whichever end is closer to the removal point will be moved to make
1568 /// room, and all the affected elements will be moved to new positions.
1569 /// Returns `None` if `index` is out of bounds.
1571 /// Element at index 0 is the front of the queue.
1576 /// use std::collections::VecDeque;
1578 /// let mut buf = VecDeque::new();
1579 /// buf.push_back(1);
1580 /// buf.push_back(2);
1581 /// buf.push_back(3);
1582 /// assert_eq!(buf, [1, 2, 3]);
1584 /// assert_eq!(buf.remove(1), Some(2));
1585 /// assert_eq!(buf, [1, 3]);
1587 #[stable(feature = "rust1", since = "1.0.0")]
1588 pub fn remove(&mut self, index: usize) -> Option<T> {
1589 if self.is_empty() || self.len() <= index {
1593 // There are three main cases:
1594 // Elements are contiguous
1595 // Elements are discontiguous and the removal is in the tail section
1596 // Elements are discontiguous and the removal is in the head section
1597 // - special case when elements are technically contiguous,
1598 // but self.head = 0
1600 // For each of those there are two more cases:
1601 // Insert is closer to tail
1602 // Insert is closer to head
1604 // Key: H - self.head
1606 // o - Valid element
1607 // x - Element marked for removal
1608 // R - Indicates element that is being removed
1609 // M - Indicates element was moved
1611 let idx = self.wrap_add(self.tail, index);
1613 let elem = unsafe { Some(self.buffer_read(idx)) };
1615 let distance_to_tail = index;
1616 let distance_to_head = self.len() - index;
1618 let contiguous = self.is_contiguous();
1620 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1621 (true, true, _) => {
1623 // contiguous, remove closer to tail:
1626 // [. . . o o x o o o o . . . . . .]
1629 // [. . . . o o o o o o . . . . . .]
1632 self.copy(self.tail + 1, self.tail, index);
1636 (true, false, _) => {
1638 // contiguous, remove closer to head:
1641 // [. . . o o o o x o o . . . . . .]
1644 // [. . . o o o o o o . . . . . . .]
1647 self.copy(idx, idx + 1, self.head - idx - 1);
1651 (false, true, true) => {
1653 // discontiguous, remove closer to tail, tail section:
1656 // [o o o o o o . . . . . o o x o o]
1659 // [o o o o o o . . . . . . o o o o]
1662 self.copy(self.tail + 1, self.tail, index);
1663 self.tail = self.wrap_add(self.tail, 1);
1666 (false, false, false) => {
1668 // discontiguous, remove closer to head, head section:
1671 // [o o o o x o o . . . . . . o o o]
1674 // [o o o o o o . . . . . . . o o o]
1677 self.copy(idx, idx + 1, self.head - idx - 1);
1681 (false, false, true) => {
1683 // discontiguous, remove closer to head, tail section:
1686 // [o o o . . . . . . o o o o o x o]
1689 // [o o . . . . . . . o o o o o o o]
1692 // or quasi-discontiguous, remove next to head, tail section:
1695 // [. . . . . . . . . o o o o o x o]
1698 // [. . . . . . . . . o o o o o o .]
1701 // draw in elements in the tail section
1702 self.copy(idx, idx + 1, self.cap() - idx - 1);
1704 // Prevents underflow.
1706 // copy first element into empty spot
1707 self.copy(self.cap() - 1, 0, 1);
1709 // move elements in the head section backwards
1710 self.copy(0, 1, self.head - 1);
1713 self.head = self.wrap_sub(self.head, 1);
1716 (false, true, false) => {
1718 // discontiguous, remove closer to tail, head section:
1721 // [o o x o o o o o o o . . . o o o]
1724 // [o o o o o o o o o o . . . . o o]
1727 // draw in elements up to idx
1728 self.copy(1, 0, idx);
1730 // copy last element into empty spot
1731 self.copy(0, self.cap() - 1, 1);
1733 // move elements from tail to end forward, excluding the last one
1734 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1736 self.tail = self.wrap_add(self.tail, 1);
1744 /// Splits the `VecDeque` into two at the given index.
1746 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1747 /// and the returned `VecDeque` contains elements `[at, len)`.
1749 /// Note that the capacity of `self` does not change.
1751 /// Element at index 0 is the front of the queue.
1755 /// Panics if `at > len`.
1760 /// use std::collections::VecDeque;
1762 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1763 /// let buf2 = buf.split_off(1);
1764 /// assert_eq!(buf, [1]);
1765 /// assert_eq!(buf2, [2, 3]);
1768 #[stable(feature = "split_off", since = "1.4.0")]
1769 pub fn split_off(&mut self, at: usize) -> Self {
1770 let len = self.len();
1771 assert!(at <= len, "`at` out of bounds");
1773 let other_len = len - at;
1774 let mut other = VecDeque::with_capacity(other_len);
1777 let (first_half, second_half) = self.as_slices();
1779 let first_len = first_half.len();
1780 let second_len = second_half.len();
1782 // `at` lies in the first half.
1783 let amount_in_first = first_len - at;
1785 ptr::copy_nonoverlapping(first_half.as_ptr().add(at),
1789 // just take all of the second half.
1790 ptr::copy_nonoverlapping(second_half.as_ptr(),
1791 other.ptr().add(amount_in_first),
1794 // `at` lies in the second half, need to factor in the elements we skipped
1795 // in the first half.
1796 let offset = at - first_len;
1797 let amount_in_second = second_len - offset;
1798 ptr::copy_nonoverlapping(second_half.as_ptr().add(offset),
1804 // Cleanup where the ends of the buffers are
1805 self.head = self.wrap_sub(self.head, other_len);
1806 other.head = other.wrap_index(other_len);
1811 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1815 /// Panics if the new number of elements in self overflows a `usize`.
1820 /// use std::collections::VecDeque;
1822 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1823 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1824 /// buf.append(&mut buf2);
1825 /// assert_eq!(buf, [1, 2, 3, 4]);
1826 /// assert_eq!(buf2, []);
1829 #[stable(feature = "append", since = "1.4.0")]
1830 pub fn append(&mut self, other: &mut Self) {
1832 self.extend(other.drain(..));
1835 /// Retains only the elements specified by the predicate.
1837 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1838 /// This method operates in place, visiting each element exactly once in the
1839 /// original order, and preserves the order of the retained elements.
1844 /// use std::collections::VecDeque;
1846 /// let mut buf = VecDeque::new();
1847 /// buf.extend(1..5);
1848 /// buf.retain(|&x| x%2 == 0);
1849 /// assert_eq!(buf, [2, 4]);
1852 /// The exact order may be useful for tracking external state, like an index.
1855 /// use std::collections::VecDeque;
1857 /// let mut buf = VecDeque::new();
1858 /// buf.extend(1..6);
1860 /// let keep = [false, true, true, false, true];
1862 /// buf.retain(|_| (keep[i], i += 1).0);
1863 /// assert_eq!(buf, [2, 3, 5]);
1865 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1866 pub fn retain<F>(&mut self, mut f: F)
1867 where F: FnMut(&T) -> bool
1869 let len = self.len();
1875 self.swap(i - del, i);
1879 self.truncate(len - del);
1883 // This may panic or abort
1885 fn grow_if_necessary(&mut self) {
1887 let old_cap = self.cap();
1890 self.handle_capacity_increase(old_cap);
1892 debug_assert!(!self.is_full());
1896 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
1897 /// either by removing excess elements from the back or by appending
1898 /// elements generated by calling `generator` to the back.
1903 /// use std::collections::VecDeque;
1905 /// let mut buf = VecDeque::new();
1906 /// buf.push_back(5);
1907 /// buf.push_back(10);
1908 /// buf.push_back(15);
1909 /// assert_eq!(buf, [5, 10, 15]);
1911 /// buf.resize_with(5, Default::default);
1912 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
1914 /// buf.resize_with(2, || unreachable!());
1915 /// assert_eq!(buf, [5, 10]);
1917 /// let mut state = 100;
1918 /// buf.resize_with(5, || { state += 1; state });
1919 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
1921 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1922 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut()->T) {
1923 let len = self.len();
1926 self.extend(repeat_with(generator).take(new_len - len))
1928 self.truncate(new_len);
1932 /// Rotates the double-ended queue `mid` places to the left.
1935 /// - Rotates item `mid` into the first position.
1936 /// - Pops the first `mid` items and pushes them to the end.
1937 /// - Rotates `len() - mid` places to the right.
1941 /// If `mid` is greater than `len()`. Note that `mid == len()`
1942 /// does _not_ panic and is a no-op rotation.
1946 /// Takes `O(min(mid, len() - mid))` time and no extra space.
1951 /// use std::collections::VecDeque;
1953 /// let mut buf: VecDeque<_> = (0..10).collect();
1955 /// buf.rotate_left(3);
1956 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
1958 /// for i in 1..10 {
1959 /// assert_eq!(i * 3 % 10, buf[0]);
1960 /// buf.rotate_left(3);
1962 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1964 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
1965 pub fn rotate_left(&mut self, mid: usize) {
1966 assert!(mid <= self.len());
1967 let k = self.len() - mid;
1969 unsafe { self.rotate_left_inner(mid) }
1971 unsafe { self.rotate_right_inner(k) }
1975 /// Rotates the double-ended queue `k` places to the right.
1978 /// - Rotates the first item into position `k`.
1979 /// - Pops the last `k` items and pushes them to the front.
1980 /// - Rotates `len() - k` places to the left.
1984 /// If `k` is greater than `len()`. Note that `k == len()`
1985 /// does _not_ panic and is a no-op rotation.
1989 /// Takes `O(min(k, len() - k))` time and no extra space.
1994 /// use std::collections::VecDeque;
1996 /// let mut buf: VecDeque<_> = (0..10).collect();
1998 /// buf.rotate_right(3);
1999 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2001 /// for i in 1..10 {
2002 /// assert_eq!(0, buf[i * 3 % 10]);
2003 /// buf.rotate_right(3);
2005 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2007 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2008 pub fn rotate_right(&mut self, k: usize) {
2009 assert!(k <= self.len());
2010 let mid = self.len() - k;
2012 unsafe { self.rotate_right_inner(k) }
2014 unsafe { self.rotate_left_inner(mid) }
2018 // Safety: the following two methods require that the rotation amount
2019 // be less than half the length of the deque.
2021 // `wrap_copy` requres that `min(x, cap() - x) + copy_len <= cap()`,
2022 // but than `min` is never more than half the capacity, regardless of x,
2023 // so it's sound to call here because we're calling with something
2024 // less than half the length, which is never above half the capacity.
2026 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2027 debug_assert!(mid * 2 <= self.len());
2028 self.wrap_copy(self.head, self.tail, mid);
2029 self.head = self.wrap_add(self.head, mid);
2030 self.tail = self.wrap_add(self.tail, mid);
2033 unsafe fn rotate_right_inner(&mut self, k: usize) {
2034 debug_assert!(k * 2 <= self.len());
2035 self.head = self.wrap_sub(self.head, k);
2036 self.tail = self.wrap_sub(self.tail, k);
2037 self.wrap_copy(self.tail, self.head, k);
2041 impl<T: Clone> VecDeque<T> {
2042 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2043 /// either by removing excess elements from the back or by appending clones of `value`
2049 /// use std::collections::VecDeque;
2051 /// let mut buf = VecDeque::new();
2052 /// buf.push_back(5);
2053 /// buf.push_back(10);
2054 /// buf.push_back(15);
2055 /// assert_eq!(buf, [5, 10, 15]);
2057 /// buf.resize(2, 0);
2058 /// assert_eq!(buf, [5, 10]);
2060 /// buf.resize(5, 20);
2061 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2063 #[stable(feature = "deque_extras", since = "1.16.0")]
2064 pub fn resize(&mut self, new_len: usize, value: T) {
2065 self.resize_with(new_len, || value.clone());
2069 /// Returns the index in the underlying buffer for a given logical element index.
2071 fn wrap_index(index: usize, size: usize) -> usize {
2072 // size is always a power of 2
2073 debug_assert!(size.is_power_of_two());
2077 /// Returns the two slices that cover the `VecDeque`'s valid range
2078 trait RingSlices: Sized {
2079 fn slice(self, from: usize, to: usize) -> Self;
2080 fn split_at(self, i: usize) -> (Self, Self);
2082 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
2083 let contiguous = tail <= head;
2085 let (empty, buf) = buf.split_at(0);
2086 (buf.slice(tail, head), empty)
2088 let (mid, right) = buf.split_at(tail);
2089 let (left, _) = mid.split_at(head);
2095 impl<T> RingSlices for &[T] {
2096 fn slice(self, from: usize, to: usize) -> Self {
2099 fn split_at(self, i: usize) -> (Self, Self) {
2104 impl<T> RingSlices for &mut [T] {
2105 fn slice(self, from: usize, to: usize) -> Self {
2108 fn split_at(self, i: usize) -> (Self, Self) {
2109 (*self).split_at_mut(i)
2113 /// Calculate the number of elements left to be read in the buffer
2115 fn count(tail: usize, head: usize, size: usize) -> usize {
2116 // size is always a power of 2
2117 (head.wrapping_sub(tail)) & (size - 1)
2120 /// An iterator over the elements of a `VecDeque`.
2122 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
2123 /// documentation for more.
2125 /// [`iter`]: struct.VecDeque.html#method.iter
2126 /// [`VecDeque`]: struct.VecDeque.html
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 pub struct Iter<'a, T: 'a> {
2134 #[stable(feature = "collection_debug", since = "1.17.0")]
2135 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
2136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2137 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2138 f.debug_tuple("Iter")
2145 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 impl<T> Clone for Iter<'_, T> {
2148 fn clone(&self) -> Self {
2157 #[stable(feature = "rust1", since = "1.0.0")]
2158 impl<'a, T> Iterator for Iter<'a, T> {
2162 fn next(&mut self) -> Option<&'a T> {
2163 if self.tail == self.head {
2166 let tail = self.tail;
2167 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2168 unsafe { Some(self.ring.get_unchecked(tail)) }
2172 fn size_hint(&self) -> (usize, Option<usize>) {
2173 let len = count(self.tail, self.head, self.ring.len());
2177 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2178 where F: FnMut(Acc, Self::Item) -> Acc
2180 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2181 accum = front.iter().fold(accum, &mut f);
2182 back.iter().fold(accum, &mut f)
2185 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2188 F: FnMut(B, Self::Item) -> R,
2191 let (mut iter, final_res);
2192 if self.tail <= self.head {
2193 // single slice self.ring[self.tail..self.head]
2194 iter = self.ring[self.tail..self.head].iter();
2195 final_res = iter.try_fold(init, &mut f);
2197 // two slices: self.ring[self.tail..], self.ring[..self.head]
2198 let (front, back) = self.ring.split_at(self.tail);
2199 let mut back_iter = back.iter();
2200 let res = back_iter.try_fold(init, &mut f);
2201 let len = self.ring.len();
2202 self.tail = (self.ring.len() - back_iter.len()) & (len - 1);
2203 iter = front[..self.head].iter();
2204 final_res = iter.try_fold(res?, &mut f);
2206 self.tail = self.head - iter.len();
2211 fn last(mut self) -> Option<&'a T> {
2216 #[stable(feature = "rust1", since = "1.0.0")]
2217 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2219 fn next_back(&mut self) -> Option<&'a T> {
2220 if self.tail == self.head {
2223 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2224 unsafe { Some(self.ring.get_unchecked(self.head)) }
2227 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2228 where F: FnMut(Acc, Self::Item) -> Acc
2230 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2231 accum = back.iter().rfold(accum, &mut f);
2232 front.iter().rfold(accum, &mut f)
2235 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
2238 F: FnMut(B, Self::Item) -> R,
2241 let (mut iter, final_res);
2242 if self.tail <= self.head {
2243 // single slice self.ring[self.tail..self.head]
2244 iter = self.ring[self.tail..self.head].iter();
2245 final_res = iter.try_rfold(init, &mut f);
2247 // two slices: self.ring[self.tail..], self.ring[..self.head]
2248 let (front, back) = self.ring.split_at(self.tail);
2249 let mut front_iter = front[..self.head].iter();
2250 let res = front_iter.try_rfold(init, &mut f);
2251 self.head = front_iter.len();
2253 final_res = iter.try_rfold(res?, &mut f);
2255 self.head = self.tail + iter.len();
2260 #[stable(feature = "rust1", since = "1.0.0")]
2261 impl<T> ExactSizeIterator for Iter<'_, T> {
2262 fn is_empty(&self) -> bool {
2263 self.head == self.tail
2267 #[stable(feature = "fused", since = "1.26.0")]
2268 impl<T> FusedIterator for Iter<'_, T> {}
2271 /// A mutable iterator over the elements of a `VecDeque`.
2273 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2274 /// documentation for more.
2276 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2277 /// [`VecDeque`]: struct.VecDeque.html
2278 #[stable(feature = "rust1", since = "1.0.0")]
2279 pub struct IterMut<'a, T: 'a> {
2285 #[stable(feature = "collection_debug", since = "1.17.0")]
2286 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
2287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2288 let (front, back) = RingSlices::ring_slices(&*self.ring, self.head, self.tail);
2289 f.debug_tuple("IterMut")
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 impl<'a, T> Iterator for IterMut<'a, T> {
2298 type Item = &'a mut T;
2301 fn next(&mut self) -> Option<&'a mut T> {
2302 if self.tail == self.head {
2305 let tail = self.tail;
2306 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2309 let elem = self.ring.get_unchecked_mut(tail);
2310 Some(&mut *(elem as *mut _))
2315 fn size_hint(&self) -> (usize, Option<usize>) {
2316 let len = count(self.tail, self.head, self.ring.len());
2320 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2321 where F: FnMut(Acc, Self::Item) -> Acc
2323 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2324 accum = front.iter_mut().fold(accum, &mut f);
2325 back.iter_mut().fold(accum, &mut f)
2329 fn last(mut self) -> Option<&'a mut T> {
2334 #[stable(feature = "rust1", since = "1.0.0")]
2335 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2337 fn next_back(&mut self) -> Option<&'a mut T> {
2338 if self.tail == self.head {
2341 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2344 let elem = self.ring.get_unchecked_mut(self.head);
2345 Some(&mut *(elem as *mut _))
2349 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2350 where F: FnMut(Acc, Self::Item) -> Acc
2352 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2353 accum = back.iter_mut().rfold(accum, &mut f);
2354 front.iter_mut().rfold(accum, &mut f)
2358 #[stable(feature = "rust1", since = "1.0.0")]
2359 impl<T> ExactSizeIterator for IterMut<'_, T> {
2360 fn is_empty(&self) -> bool {
2361 self.head == self.tail
2365 #[stable(feature = "fused", since = "1.26.0")]
2366 impl<T> FusedIterator for IterMut<'_, T> {}
2368 /// An owning iterator over the elements of a `VecDeque`.
2370 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`][`VecDeque`]
2371 /// (provided by the `IntoIterator` trait). See its documentation for more.
2373 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2374 /// [`VecDeque`]: struct.VecDeque.html
2376 #[stable(feature = "rust1", since = "1.0.0")]
2377 pub struct IntoIter<T> {
2381 #[stable(feature = "collection_debug", since = "1.17.0")]
2382 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2384 f.debug_tuple("IntoIter")
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 impl<T> Iterator for IntoIter<T> {
2395 fn next(&mut self) -> Option<T> {
2396 self.inner.pop_front()
2400 fn size_hint(&self) -> (usize, Option<usize>) {
2401 let len = self.inner.len();
2406 #[stable(feature = "rust1", since = "1.0.0")]
2407 impl<T> DoubleEndedIterator for IntoIter<T> {
2409 fn next_back(&mut self) -> Option<T> {
2410 self.inner.pop_back()
2414 #[stable(feature = "rust1", since = "1.0.0")]
2415 impl<T> ExactSizeIterator for IntoIter<T> {
2416 fn is_empty(&self) -> bool {
2417 self.inner.is_empty()
2421 #[stable(feature = "fused", since = "1.26.0")]
2422 impl<T> FusedIterator for IntoIter<T> {}
2424 /// A draining iterator over the elements of a `VecDeque`.
2426 /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its
2427 /// documentation for more.
2429 /// [`drain`]: struct.VecDeque.html#method.drain
2430 /// [`VecDeque`]: struct.VecDeque.html
2431 #[stable(feature = "drain", since = "1.6.0")]
2432 pub struct Drain<'a, T: 'a> {
2436 deque: NonNull<VecDeque<T>>,
2439 #[stable(feature = "collection_debug", since = "1.17.0")]
2440 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2442 f.debug_tuple("Drain")
2443 .field(&self.after_tail)
2444 .field(&self.after_head)
2450 #[stable(feature = "drain", since = "1.6.0")]
2451 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2452 #[stable(feature = "drain", since = "1.6.0")]
2453 unsafe impl<T: Send> Send for Drain<'_, T> {}
2455 #[stable(feature = "drain", since = "1.6.0")]
2456 impl<T> Drop for Drain<'_, T> {
2457 fn drop(&mut self) {
2458 self.for_each(drop);
2460 let source_deque = unsafe { self.deque.as_mut() };
2462 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2465 // [. . . o o x x o o . . .]
2467 let orig_tail = source_deque.tail;
2468 let drain_tail = source_deque.head;
2469 let drain_head = self.after_tail;
2470 let orig_head = self.after_head;
2472 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2473 let head_len = count(drain_head, orig_head, source_deque.cap());
2475 // Restore the original head value
2476 source_deque.head = orig_head;
2478 match (tail_len, head_len) {
2480 source_deque.head = 0;
2481 source_deque.tail = 0;
2484 source_deque.tail = drain_head;
2487 source_deque.head = drain_tail;
2490 if tail_len <= head_len {
2491 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2492 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2494 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2495 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2502 #[stable(feature = "drain", since = "1.6.0")]
2503 impl<T> Iterator for Drain<'_, T> {
2507 fn next(&mut self) -> Option<T> {
2508 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2512 fn size_hint(&self) -> (usize, Option<usize>) {
2513 self.iter.size_hint()
2517 #[stable(feature = "drain", since = "1.6.0")]
2518 impl<T> DoubleEndedIterator for Drain<'_, T> {
2520 fn next_back(&mut self) -> Option<T> {
2521 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2525 #[stable(feature = "drain", since = "1.6.0")]
2526 impl<T> ExactSizeIterator for Drain<'_, T> {}
2528 #[stable(feature = "fused", since = "1.26.0")]
2529 impl<T> FusedIterator for Drain<'_, T> {}
2531 #[stable(feature = "rust1", since = "1.0.0")]
2532 impl<A: PartialEq> PartialEq for VecDeque<A> {
2533 fn eq(&self, other: &VecDeque<A>) -> bool {
2534 if self.len() != other.len() {
2537 let (sa, sb) = self.as_slices();
2538 let (oa, ob) = other.as_slices();
2539 if sa.len() == oa.len() {
2540 sa == oa && sb == ob
2541 } else if sa.len() < oa.len() {
2542 // Always divisible in three sections, for example:
2543 // self: [a b c|d e f]
2544 // other: [0 1 2 3|4 5]
2545 // front = 3, mid = 1,
2546 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2547 let front = sa.len();
2548 let mid = oa.len() - front;
2550 let (oa_front, oa_mid) = oa.split_at(front);
2551 let (sb_mid, sb_back) = sb.split_at(mid);
2552 debug_assert_eq!(sa.len(), oa_front.len());
2553 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2554 debug_assert_eq!(sb_back.len(), ob.len());
2555 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2557 let front = oa.len();
2558 let mid = sa.len() - front;
2560 let (sa_front, sa_mid) = sa.split_at(front);
2561 let (ob_mid, ob_back) = ob.split_at(mid);
2562 debug_assert_eq!(sa_front.len(), oa.len());
2563 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2564 debug_assert_eq!(sb.len(), ob_back.len());
2565 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2570 #[stable(feature = "rust1", since = "1.0.0")]
2571 impl<A: Eq> Eq for VecDeque<A> {}
2573 macro_rules! __impl_slice_eq1 {
2574 ($Lhs: ty, $Rhs: ty) => {
2575 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2577 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2578 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2579 impl<A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2580 fn eq(&self, other: &$Rhs) -> bool {
2581 if self.len() != other.len() {
2584 let (sa, sb) = self.as_slices();
2585 let (oa, ob) = other[..].split_at(sa.len());
2586 sa == oa && sb == ob
2592 __impl_slice_eq1! { VecDeque<A>, Vec<B> }
2593 __impl_slice_eq1! { VecDeque<A>, &[B] }
2594 __impl_slice_eq1! { VecDeque<A>, &mut [B] }
2596 macro_rules! array_impls {
2599 __impl_slice_eq1! { VecDeque<A>, [B; $N] }
2600 __impl_slice_eq1! { VecDeque<A>, &[B; $N] }
2601 __impl_slice_eq1! { VecDeque<A>, &mut [B; $N] }
2608 10 11 12 13 14 15 16 17 18 19
2609 20 21 22 23 24 25 26 27 28 29
2613 #[stable(feature = "rust1", since = "1.0.0")]
2614 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2615 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2616 self.iter().partial_cmp(other.iter())
2620 #[stable(feature = "rust1", since = "1.0.0")]
2621 impl<A: Ord> Ord for VecDeque<A> {
2623 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2624 self.iter().cmp(other.iter())
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 impl<A: Hash> Hash for VecDeque<A> {
2630 fn hash<H: Hasher>(&self, state: &mut H) {
2631 self.len().hash(state);
2632 let (a, b) = self.as_slices();
2633 Hash::hash_slice(a, state);
2634 Hash::hash_slice(b, state);
2638 #[stable(feature = "rust1", since = "1.0.0")]
2639 impl<A> Index<usize> for VecDeque<A> {
2643 fn index(&self, index: usize) -> &A {
2644 self.get(index).expect("Out of bounds access")
2648 #[stable(feature = "rust1", since = "1.0.0")]
2649 impl<A> IndexMut<usize> for VecDeque<A> {
2651 fn index_mut(&mut self, index: usize) -> &mut A {
2652 self.get_mut(index).expect("Out of bounds access")
2656 #[stable(feature = "rust1", since = "1.0.0")]
2657 impl<A> FromIterator<A> for VecDeque<A> {
2658 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2659 let iterator = iter.into_iter();
2660 let (lower, _) = iterator.size_hint();
2661 let mut deq = VecDeque::with_capacity(lower);
2662 deq.extend(iterator);
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 impl<T> IntoIterator for VecDeque<T> {
2670 type IntoIter = IntoIter<T>;
2672 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2674 fn into_iter(self) -> IntoIter<T> {
2675 IntoIter { inner: self }
2679 #[stable(feature = "rust1", since = "1.0.0")]
2680 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2682 type IntoIter = Iter<'a, T>;
2684 fn into_iter(self) -> Iter<'a, T> {
2689 #[stable(feature = "rust1", since = "1.0.0")]
2690 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2691 type Item = &'a mut T;
2692 type IntoIter = IterMut<'a, T>;
2694 fn into_iter(self) -> IterMut<'a, T> {
2699 #[stable(feature = "rust1", since = "1.0.0")]
2700 impl<A> Extend<A> for VecDeque<A> {
2701 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2702 iter.into_iter().for_each(move |elt| self.push_back(elt));
2706 #[stable(feature = "extend_ref", since = "1.2.0")]
2707 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2708 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2709 self.extend(iter.into_iter().cloned());
2713 #[stable(feature = "rust1", since = "1.0.0")]
2714 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2716 f.debug_list().entries(self).finish()
2720 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2721 impl<T> From<Vec<T>> for VecDeque<T> {
2722 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2724 /// [`Vec<T>`]: crate::vec::Vec
2725 /// [`VecDeque<T>`]: crate::collections::VecDeque
2727 /// This avoids reallocating where possible, but the conditions for that are
2728 /// strict, and subject to change, and so shouldn't be relied upon unless the
2729 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
2730 fn from(mut other: Vec<T>) -> Self {
2732 let other_buf = other.as_mut_ptr();
2733 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2734 let len = other.len();
2737 // We need to extend the buf if it's not a power of two, too small
2738 // or doesn't have at least one free space
2739 if !buf.capacity().is_power_of_two() || (buf.capacity() < (MINIMUM_CAPACITY + 1)) ||
2740 (buf.capacity() == len) {
2741 let cap = cmp::max(buf.capacity() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2742 buf.reserve_exact(len, cap - len);
2754 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2755 impl<T> From<VecDeque<T>> for Vec<T> {
2756 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2758 /// [`Vec<T>`]: crate::vec::Vec
2759 /// [`VecDeque<T>`]: crate::collections::VecDeque
2761 /// This never needs to re-allocate, but does need to do O(n) data movement if
2762 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2767 /// use std::collections::VecDeque;
2769 /// // This one is O(1).
2770 /// let deque: VecDeque<_> = (1..5).collect();
2771 /// let ptr = deque.as_slices().0.as_ptr();
2772 /// let vec = Vec::from(deque);
2773 /// assert_eq!(vec, [1, 2, 3, 4]);
2774 /// assert_eq!(vec.as_ptr(), ptr);
2776 /// // This one needs data rearranging.
2777 /// let mut deque: VecDeque<_> = (1..5).collect();
2778 /// deque.push_front(9);
2779 /// deque.push_front(8);
2780 /// let ptr = deque.as_slices().1.as_ptr();
2781 /// let vec = Vec::from(deque);
2782 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2783 /// assert_eq!(vec.as_ptr(), ptr);
2785 fn from(other: VecDeque<T>) -> Self {
2787 let buf = other.buf.ptr();
2788 let len = other.len();
2789 let tail = other.tail;
2790 let head = other.head;
2791 let cap = other.cap();
2793 // Need to move the ring to the front of the buffer, as vec will expect this.
2794 if other.is_contiguous() {
2795 ptr::copy(buf.add(tail), buf, len);
2797 if (tail - head) >= cmp::min(cap - tail, head) {
2798 // There is enough free space in the centre for the shortest block so we can
2799 // do this in at most three copy moves.
2800 if (cap - tail) > head {
2801 // right hand block is the long one; move that enough for the left
2802 ptr::copy(buf.add(tail),
2803 buf.add(tail - head),
2805 // copy left in the end
2806 ptr::copy(buf, buf.add(cap - head), head);
2807 // shift the new thing to the start
2808 ptr::copy(buf.add(tail - head), buf, len);
2810 // left hand block is the long one, we can do it in two!
2811 ptr::copy(buf, buf.add(cap - tail), head);
2812 ptr::copy(buf.add(tail), buf, cap - tail);
2815 // Need to use N swaps to move the ring
2816 // We can use the space at the end of the ring as a temp store
2818 let mut left_edge: usize = 0;
2819 let mut right_edge: usize = tail;
2821 // The general problem looks like this
2822 // GHIJKLM...ABCDEF - before any swaps
2823 // ABCDEFM...GHIJKL - after 1 pass of swaps
2824 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2825 // - then restart the algorithm with a new (smaller) store
2826 // Sometimes the temp store is reached when the right edge is at the end
2827 // of the buffer - this means we've hit the right order with fewer swaps!
2830 // ABCDEF.. - after four only swaps we've finished
2832 while left_edge < len && right_edge != cap {
2833 let mut right_offset = 0;
2834 for i in left_edge..right_edge {
2835 right_offset = (i - left_edge) % (cap - right_edge);
2836 let src: isize = (right_edge + right_offset) as isize;
2837 ptr::swap(buf.add(i), buf.offset(src));
2839 let n_ops = right_edge - left_edge;
2841 right_edge += right_offset + 1;
2847 let out = Vec::from_raw_parts(buf, len, cap);
2858 use super::VecDeque;
2861 #[cfg(not(miri))] // Miri does not support benchmarks
2862 fn bench_push_back_100(b: &mut test::Bencher) {
2863 let mut deq = VecDeque::with_capacity(101);
2874 #[cfg(not(miri))] // Miri does not support benchmarks
2875 fn bench_push_front_100(b: &mut test::Bencher) {
2876 let mut deq = VecDeque::with_capacity(101);
2887 #[cfg(not(miri))] // Miri does not support benchmarks
2888 fn bench_pop_back_100(b: &mut test::Bencher) {
2889 let mut deq = VecDeque::<i32>::with_capacity(101);
2894 while !deq.is_empty() {
2895 test::black_box(deq.pop_back());
2901 #[cfg(not(miri))] // Miri does not support benchmarks
2902 fn bench_pop_front_100(b: &mut test::Bencher) {
2903 let mut deq = VecDeque::<i32>::with_capacity(101);
2908 while !deq.is_empty() {
2909 test::black_box(deq.pop_front());
2915 fn test_swap_front_back_remove() {
2916 fn test(back: bool) {
2917 // This test checks that every single combination of tail position and length is tested.
2918 // Capacity 15 should be large enough to cover every case.
2919 let mut tester = VecDeque::with_capacity(15);
2920 let usable_cap = tester.capacity();
2921 let final_len = usable_cap / 2;
2923 for len in 0..final_len {
2924 let expected: VecDeque<_> = if back {
2927 (0..len).rev().collect()
2929 for tail_pos in 0..usable_cap {
2930 tester.tail = tail_pos;
2931 tester.head = tail_pos;
2933 for i in 0..len * 2 {
2934 tester.push_front(i);
2937 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2940 for i in 0..len * 2 {
2941 tester.push_back(i);
2944 let idx = tester.len() - 1 - i;
2945 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2948 assert!(tester.tail < tester.cap());
2949 assert!(tester.head < tester.cap());
2950 assert_eq!(tester, expected);
2960 // This test checks that every single combination of tail position, length, and
2961 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2963 let mut tester = VecDeque::with_capacity(15);
2964 // can't guarantee we got 15, so have to get what we got.
2965 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2966 // this test isn't covering what it wants to
2967 let cap = tester.capacity();
2970 // len is the length *after* insertion
2972 // 0, 1, 2, .., len - 1
2973 let expected = (0..).take(len).collect::<VecDeque<_>>();
2974 for tail_pos in 0..cap {
2975 for to_insert in 0..len {
2976 tester.tail = tail_pos;
2977 tester.head = tail_pos;
2980 tester.push_back(i);
2983 tester.insert(to_insert, to_insert);
2984 assert!(tester.tail < tester.cap());
2985 assert!(tester.head < tester.cap());
2986 assert_eq!(tester, expected);
2994 // This test checks that every single combination of tail position, length, and
2995 // removal position is tested. Capacity 15 should be large enough to cover every case.
2997 let mut tester = VecDeque::with_capacity(15);
2998 // can't guarantee we got 15, so have to get what we got.
2999 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
3000 // this test isn't covering what it wants to
3001 let cap = tester.capacity();
3003 // len is the length *after* removal
3004 for len in 0..cap - 1 {
3005 // 0, 1, 2, .., len - 1
3006 let expected = (0..).take(len).collect::<VecDeque<_>>();
3007 for tail_pos in 0..cap {
3008 for to_remove in 0..=len {
3009 tester.tail = tail_pos;
3010 tester.head = tail_pos;
3013 tester.push_back(1234);
3015 tester.push_back(i);
3017 if to_remove == len {
3018 tester.push_back(1234);
3020 tester.remove(to_remove);
3021 assert!(tester.tail < tester.cap());
3022 assert!(tester.head < tester.cap());
3023 assert_eq!(tester, expected);
3031 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
3033 let cap = tester.capacity();
3034 for len in 0..=cap {
3035 for tail in 0..=cap {
3036 for drain_start in 0..=len {
3037 for drain_end in drain_start..=len {
3041 tester.push_back(i);
3044 // Check that we drain the correct values
3045 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
3046 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
3047 assert_eq!(drained, drained_expected);
3049 // We shouldn't have changed the capacity or made the
3050 // head or tail out of bounds
3051 assert_eq!(tester.capacity(), cap);
3052 assert!(tester.tail < tester.cap());
3053 assert!(tester.head < tester.cap());
3055 // We should see the correct values in the VecDeque
3056 let expected: VecDeque<_> = (0..drain_start)
3057 .chain(drain_end..len)
3059 assert_eq!(expected, tester);
3067 fn test_shrink_to_fit() {
3068 // This test checks that every single combination of head and tail position,
3069 // is tested. Capacity 15 should be large enough to cover every case.
3071 let mut tester = VecDeque::with_capacity(15);
3072 // can't guarantee we got 15, so have to get what we got.
3073 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
3074 // this test isn't covering what it wants to
3075 let cap = tester.capacity();
3077 let max_cap = tester.capacity();
3079 for len in 0..=cap {
3080 // 0, 1, 2, .., len - 1
3081 let expected = (0..).take(len).collect::<VecDeque<_>>();
3082 for tail_pos in 0..=max_cap {
3083 tester.tail = tail_pos;
3084 tester.head = tail_pos;
3087 tester.push_back(i);
3089 tester.shrink_to_fit();
3090 assert!(tester.capacity() <= cap);
3091 assert!(tester.tail < tester.cap());
3092 assert!(tester.head < tester.cap());
3093 assert_eq!(tester, expected);
3099 fn test_split_off() {
3100 // This test checks that every single combination of tail position, length, and
3101 // split position is tested. Capacity 15 should be large enough to cover every case.
3103 let mut tester = VecDeque::with_capacity(15);
3104 // can't guarantee we got 15, so have to get what we got.
3105 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
3106 // this test isn't covering what it wants to
3107 let cap = tester.capacity();
3109 // len is the length *before* splitting
3111 // index to split at
3113 // 0, 1, 2, .., at - 1 (may be empty)
3114 let expected_self = (0..).take(at).collect::<VecDeque<_>>();
3115 // at, at + 1, .., len - 1 (may be empty)
3116 let expected_other = (at..).take(len - at).collect::<VecDeque<_>>();
3118 for tail_pos in 0..cap {
3119 tester.tail = tail_pos;
3120 tester.head = tail_pos;
3122 tester.push_back(i);
3124 let result = tester.split_off(at);
3125 assert!(tester.tail < tester.cap());
3126 assert!(tester.head < tester.cap());
3127 assert!(result.tail < result.cap());
3128 assert!(result.head < result.cap());
3129 assert_eq!(tester, expected_self);
3130 assert_eq!(result, expected_other);
3137 fn test_from_vec() {
3138 use crate::vec::Vec;
3140 for len in 0..=cap {
3141 let mut vec = Vec::with_capacity(cap);
3144 let vd = VecDeque::from(vec.clone());
3145 assert!(vd.cap().is_power_of_two());
3146 assert_eq!(vd.len(), vec.len());
3147 assert!(vd.into_iter().eq(vec));
3153 fn test_vec_from_vecdeque() {
3154 use crate::vec::Vec;
3156 fn create_vec_and_test_convert(capacity: usize, offset: usize, len: usize) {
3157 let mut vd = VecDeque::with_capacity(capacity);
3158 for _ in 0..offset {
3164 let vec: Vec<_> = Vec::from(vd.clone());
3165 assert_eq!(vec.len(), vd.len());
3166 assert!(vec.into_iter().eq(vd));
3169 #[cfg(not(miri))] // Miri is too slow
3174 for cap_pwr in 0..max_pwr {
3175 // Make capacity as a (2^x)-1, so that the ring size is 2^x
3176 let cap = (2i32.pow(cap_pwr) - 1) as usize;
3178 // In these cases there is enough free space to solve it with copies
3179 for len in 0..((cap + 1) / 2) {
3180 // Test contiguous cases
3181 for offset in 0..(cap - len) {
3182 create_vec_and_test_convert(cap, offset, len)
3185 // Test cases where block at end of buffer is bigger than block at start
3186 for offset in (cap - len)..(cap - (len / 2)) {
3187 create_vec_and_test_convert(cap, offset, len)
3190 // Test cases where block at start of buffer is bigger than block at end
3191 for offset in (cap - (len / 2))..cap {
3192 create_vec_and_test_convert(cap, offset, len)
3196 // Now there's not (necessarily) space to straighten the ring with simple copies,
3197 // the ring will use swapping when:
3198 // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
3199 // right block size > free space && left block size > free space
3200 for len in ((cap + 1) / 2)..cap {
3201 // Test contiguous cases
3202 for offset in 0..(cap - len) {
3203 create_vec_and_test_convert(cap, offset, len)
3206 // Test cases where block at end of buffer is bigger than block at start
3207 for offset in (cap - len)..(cap - (len / 2)) {
3208 create_vec_and_test_convert(cap, offset, len)
3211 // Test cases where block at start of buffer is bigger than block at end
3212 for offset in (cap - (len / 2))..cap {
3213 create_vec_and_test_convert(cap, offset, len)
3221 use crate::boxed::Box;
3223 let mut dst = VecDeque::new();
3224 dst.push_front(Box::new(1));
3225 dst.push_front(Box::new(2));
3226 assert_eq!(*dst.pop_back().unwrap(), 1);
3228 let mut src = VecDeque::new();
3229 src.push_front(Box::new(2));
3230 dst.append(&mut src);