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::array::LengthAtMost32;
13 use core::cmp::{self, Ordering};
15 use core::iter::{repeat_with, FromIterator, FusedIterator};
17 use core::ops::Bound::{Excluded, Included, Unbounded};
18 use core::ops::{Index, IndexMut, RangeBounds, Try};
19 use core::ptr::{self, NonNull};
21 use core::hash::{Hash, Hasher};
23 use crate::collections::CollectionAllocErr;
24 use crate::raw_vec::RawVec;
27 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
28 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
29 #[cfg(target_pointer_width = "16")]
30 const MAXIMUM_ZST_CAPACITY: usize = 1 << (16 - 1); // Largest possible power of two
31 #[cfg(target_pointer_width = "32")]
32 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
33 #[cfg(target_pointer_width = "64")]
34 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
36 /// A double-ended queue implemented with a growable ring buffer.
38 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
39 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
40 /// push onto the back in this manner, and iterating over `VecDeque` goes front
43 /// [`push_back`]: #method.push_back
44 /// [`pop_front`]: #method.pop_front
45 /// [`extend`]: #method.extend
46 /// [`append`]: #method.append
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub struct VecDeque<T> {
49 // tail and head are pointers into the buffer. Tail always points
50 // to the first element that could be read, Head always points
51 // to where data should be written.
52 // If tail == head the buffer is empty. The length of the ringbuffer
53 // is defined as the distance between the two.
59 #[stable(feature = "rust1", since = "1.0.0")]
60 impl<T: Clone> Clone for VecDeque<T> {
61 fn clone(&self) -> VecDeque<T> {
62 self.iter().cloned().collect()
66 #[stable(feature = "rust1", since = "1.0.0")]
67 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
69 let (front, back) = self.as_mut_slices();
72 ptr::drop_in_place(front);
73 ptr::drop_in_place(back);
75 // RawVec handles deallocation
79 #[stable(feature = "rust1", since = "1.0.0")]
80 impl<T> Default for VecDeque<T> {
81 /// Creates an empty `VecDeque<T>`.
83 fn default() -> VecDeque<T> {
89 /// Marginally more convenient
91 fn ptr(&self) -> *mut T {
95 /// Marginally more convenient
97 fn cap(&self) -> usize {
98 if mem::size_of::<T>() == 0 {
99 // For zero sized types, we are always at maximum capacity
106 /// Turn ptr into a slice
108 unsafe fn buffer_as_slice(&self) -> &[T] {
109 slice::from_raw_parts(self.ptr(), self.cap())
112 /// Turn ptr into a mut slice
114 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
115 slice::from_raw_parts_mut(self.ptr(), self.cap())
118 /// Moves an element out of the buffer
120 unsafe fn buffer_read(&mut self, off: usize) -> T {
121 ptr::read(self.ptr().add(off))
124 /// Writes an element into the buffer, moving it.
126 unsafe fn buffer_write(&mut self, off: usize, value: T) {
127 ptr::write(self.ptr().add(off), value);
130 /// Returns `true` if the buffer is at full capacity.
132 fn is_full(&self) -> bool {
133 self.cap() - self.len() == 1
136 /// Returns the index in the underlying buffer for a given logical element
139 fn wrap_index(&self, idx: usize) -> usize {
140 wrap_index(idx, self.cap())
143 /// Returns the index in the underlying buffer for a given logical element
146 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
147 wrap_index(idx.wrapping_add(addend), self.cap())
150 /// Returns the index in the underlying buffer for a given logical element
151 /// index - subtrahend.
153 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
154 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
157 /// Copies a contiguous block of memory len long from src to dst
159 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
160 debug_assert!(dst + len <= self.cap(),
161 "cpy dst={} src={} len={} cap={}",
166 debug_assert!(src + len <= self.cap(),
167 "cpy dst={} src={} len={} cap={}",
172 ptr::copy(self.ptr().add(src),
177 /// Copies a contiguous block of memory len long from src to dst
179 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
180 debug_assert!(dst + len <= self.cap(),
181 "cno dst={} src={} len={} cap={}",
186 debug_assert!(src + len <= self.cap(),
187 "cno dst={} src={} len={} cap={}",
192 ptr::copy_nonoverlapping(self.ptr().add(src),
197 /// Copies a potentially wrapping block of memory len long from src to dest.
198 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
199 /// most one continuous overlapping region between src and dest).
200 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
202 fn diff(a: usize, b: usize) -> usize {
203 if a <= b { b - a } else { a - b }
205 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
206 "wrc dst={} src={} len={} cap={}",
212 if src == dst || len == 0 {
216 let dst_after_src = self.wrap_sub(dst, src) < len;
218 let src_pre_wrap_len = self.cap() - src;
219 let dst_pre_wrap_len = self.cap() - dst;
220 let src_wraps = src_pre_wrap_len < len;
221 let dst_wraps = dst_pre_wrap_len < len;
223 match (dst_after_src, src_wraps, dst_wraps) {
224 (_, false, false) => {
225 // src doesn't wrap, dst doesn't wrap
228 // 1 [_ _ A A B B C C _]
229 // 2 [_ _ A A A A B B _]
232 self.copy(dst, src, len);
234 (false, false, true) => {
235 // dst before src, src doesn't wrap, dst wraps
238 // 1 [A A B B _ _ _ C C]
239 // 2 [A A B B _ _ _ A A]
240 // 3 [B B B B _ _ _ A A]
243 self.copy(dst, src, dst_pre_wrap_len);
244 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
246 (true, false, true) => {
247 // src before dst, src doesn't wrap, dst wraps
250 // 1 [C C _ _ _ A A B B]
251 // 2 [B B _ _ _ A A B B]
252 // 3 [B B _ _ _ A A A A]
255 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
256 self.copy(dst, src, dst_pre_wrap_len);
258 (false, true, false) => {
259 // dst before src, src wraps, dst doesn't wrap
262 // 1 [C C _ _ _ A A B B]
263 // 2 [C C _ _ _ B B B B]
264 // 3 [C C _ _ _ B B C C]
267 self.copy(dst, src, src_pre_wrap_len);
268 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
270 (true, true, false) => {
271 // src before dst, src wraps, dst doesn't wrap
274 // 1 [A A B B _ _ _ C C]
275 // 2 [A A A A _ _ _ C C]
276 // 3 [C C A A _ _ _ C C]
279 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
280 self.copy(dst, src, src_pre_wrap_len);
282 (false, true, true) => {
283 // dst before src, src wraps, dst wraps
286 // 1 [A B C D _ E F G H]
287 // 2 [A B C D _ E G H H]
288 // 3 [A B C D _ E G H A]
289 // 4 [B C C D _ E G H A]
292 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
293 let delta = dst_pre_wrap_len - src_pre_wrap_len;
294 self.copy(dst, src, src_pre_wrap_len);
295 self.copy(dst + src_pre_wrap_len, 0, delta);
296 self.copy(0, delta, len - dst_pre_wrap_len);
298 (true, true, true) => {
299 // src before dst, src wraps, dst wraps
302 // 1 [A B C D _ E F G H]
303 // 2 [A A B D _ E F G H]
304 // 3 [H A B D _ E F G H]
305 // 4 [H A B D _ E F F G]
308 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
309 let delta = src_pre_wrap_len - dst_pre_wrap_len;
310 self.copy(delta, 0, len - src_pre_wrap_len);
311 self.copy(0, self.cap() - delta, delta);
312 self.copy(dst, src, dst_pre_wrap_len);
317 /// Frobs the head and tail sections around to handle the fact that we
318 /// just reallocated. Unsafe because it trusts old_capacity.
320 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
321 let new_capacity = self.cap();
323 // Move the shortest contiguous section of the ring buffer
325 // [o o o o o o o . ]
327 // A [o o o o o o o . . . . . . . . . ]
329 // [o o . o o o o o ]
331 // B [. . . o o o o o o o . . . . . . ]
333 // [o o o o o . o o ]
335 // C [o o o o o . . . . . . . . . o o ]
337 if self.tail <= self.head {
340 } else if self.head < old_capacity - self.tail {
342 self.copy_nonoverlapping(old_capacity, 0, self.head);
343 self.head += old_capacity;
344 debug_assert!(self.head > self.tail);
347 let new_tail = new_capacity - (old_capacity - self.tail);
348 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
349 self.tail = new_tail;
350 debug_assert!(self.head < self.tail);
352 debug_assert!(self.head < self.cap());
353 debug_assert!(self.tail < self.cap());
354 debug_assert!(self.cap().count_ones() == 1);
358 impl<T> VecDeque<T> {
359 /// Creates an empty `VecDeque`.
364 /// use std::collections::VecDeque;
366 /// let vector: VecDeque<u32> = VecDeque::new();
368 #[stable(feature = "rust1", since = "1.0.0")]
369 pub fn new() -> VecDeque<T> {
370 VecDeque::with_capacity(INITIAL_CAPACITY)
373 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
378 /// use std::collections::VecDeque;
380 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
382 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
384 // +1 since the ringbuffer always leaves one space empty
385 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
386 assert!(cap > capacity, "capacity overflow");
391 buf: RawVec::with_capacity(cap),
395 /// Retrieves an element in the `VecDeque` by index.
397 /// Element at index 0 is the front of the queue.
402 /// use std::collections::VecDeque;
404 /// let mut buf = VecDeque::new();
405 /// buf.push_back(3);
406 /// buf.push_back(4);
407 /// buf.push_back(5);
408 /// assert_eq!(buf.get(1), Some(&4));
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn get(&self, index: usize) -> Option<&T> {
412 if index < self.len() {
413 let idx = self.wrap_add(self.tail, index);
414 unsafe { Some(&*self.ptr().add(idx)) }
420 /// Retrieves an element in the `VecDeque` mutably by index.
422 /// Element at index 0 is the front of the queue.
427 /// use std::collections::VecDeque;
429 /// let mut buf = VecDeque::new();
430 /// buf.push_back(3);
431 /// buf.push_back(4);
432 /// buf.push_back(5);
433 /// if let Some(elem) = buf.get_mut(1) {
437 /// assert_eq!(buf[1], 7);
439 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
441 if index < self.len() {
442 let idx = self.wrap_add(self.tail, index);
443 unsafe { Some(&mut *self.ptr().add(idx)) }
449 /// Swaps elements at indices `i` and `j`.
451 /// `i` and `j` may be equal.
453 /// Element at index 0 is the front of the queue.
457 /// Panics if either index is out of bounds.
462 /// use std::collections::VecDeque;
464 /// let mut buf = VecDeque::new();
465 /// buf.push_back(3);
466 /// buf.push_back(4);
467 /// buf.push_back(5);
468 /// assert_eq!(buf, [3, 4, 5]);
470 /// assert_eq!(buf, [5, 4, 3]);
472 #[stable(feature = "rust1", since = "1.0.0")]
473 pub fn swap(&mut self, i: usize, j: usize) {
474 assert!(i < self.len());
475 assert!(j < self.len());
476 let ri = self.wrap_add(self.tail, i);
477 let rj = self.wrap_add(self.tail, j);
479 ptr::swap(self.ptr().add(ri),
484 /// Returns the number of elements the `VecDeque` can hold without
490 /// use std::collections::VecDeque;
492 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
493 /// assert!(buf.capacity() >= 10);
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub fn capacity(&self) -> usize {
501 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
502 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
504 /// Note that the allocator may give the collection more space than it requests. Therefore
505 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
506 /// insertions are expected.
510 /// Panics if the new capacity overflows `usize`.
515 /// use std::collections::VecDeque;
517 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
518 /// buf.reserve_exact(10);
519 /// assert!(buf.capacity() >= 11);
522 /// [`reserve`]: #method.reserve
523 #[stable(feature = "rust1", since = "1.0.0")]
524 pub fn reserve_exact(&mut self, additional: usize) {
525 self.reserve(additional);
528 /// Reserves capacity for at least `additional` more elements to be inserted in the given
529 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
533 /// Panics if the new capacity overflows `usize`.
538 /// use std::collections::VecDeque;
540 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
542 /// assert!(buf.capacity() >= 11);
544 #[stable(feature = "rust1", since = "1.0.0")]
545 pub fn reserve(&mut self, additional: usize) {
546 let old_cap = self.cap();
547 let used_cap = self.len() + 1;
548 let new_cap = used_cap.checked_add(additional)
549 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
550 .expect("capacity overflow");
552 if new_cap > old_cap {
553 self.buf.reserve_exact(used_cap, new_cap - used_cap);
555 self.handle_capacity_increase(old_cap);
560 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
561 /// be inserted in the given `VecDeque<T>`. After calling `reserve_exact`,
562 /// capacity will be greater than or equal to `self.len() + additional`.
563 /// Does nothing if the capacity is already sufficient.
565 /// Note that the allocator may give the collection more space than it
566 /// requests. Therefore, capacity can not be relied upon to be precisely
567 /// minimal. Prefer `reserve` if future insertions are expected.
571 /// If the capacity overflows, or the allocator reports a failure, then an error
577 /// #![feature(try_reserve)]
578 /// use std::collections::CollectionAllocErr;
579 /// use std::collections::VecDeque;
581 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
582 /// let mut output = VecDeque::new();
584 /// // Pre-reserve the memory, exiting if we can't
585 /// output.try_reserve_exact(data.len())?;
587 /// // Now we know this can't OOM in the middle of our complex work
588 /// output.extend(data.iter().map(|&val| {
589 /// val * 2 + 5 // very complicated
594 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
596 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
597 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
598 self.try_reserve(additional)
601 /// Tries to reserve capacity for at least `additional` more elements to be inserted
602 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
603 /// frequent reallocations. After calling `reserve`, capacity will be
604 /// greater than or equal to `self.len() + additional`. Does nothing if
605 /// capacity is already sufficient.
609 /// If the capacity overflows, or the allocator reports a failure, then an error
615 /// #![feature(try_reserve)]
616 /// use std::collections::CollectionAllocErr;
617 /// use std::collections::VecDeque;
619 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
620 /// let mut output = VecDeque::new();
622 /// // Pre-reserve the memory, exiting if we can't
623 /// output.try_reserve(data.len())?;
625 /// // Now we know this can't OOM in the middle of our complex work
626 /// output.extend(data.iter().map(|&val| {
627 /// val * 2 + 5 // very complicated
632 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
634 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
635 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
636 let old_cap = self.cap();
637 let used_cap = self.len() + 1;
638 let new_cap = used_cap.checked_add(additional)
639 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
640 .ok_or(CollectionAllocErr::CapacityOverflow)?;
642 if new_cap > old_cap {
643 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
645 self.handle_capacity_increase(old_cap);
651 /// Shrinks the capacity of the `VecDeque` as much as possible.
653 /// It will drop down as close as possible to the length but the allocator may still inform the
654 /// `VecDeque` that there is space for a few more elements.
659 /// use std::collections::VecDeque;
661 /// let mut buf = VecDeque::with_capacity(15);
662 /// buf.extend(0..4);
663 /// assert_eq!(buf.capacity(), 15);
664 /// buf.shrink_to_fit();
665 /// assert!(buf.capacity() >= 4);
667 #[stable(feature = "deque_extras_15", since = "1.5.0")]
668 pub fn shrink_to_fit(&mut self) {
672 /// Shrinks the capacity of the `VecDeque` with a lower bound.
674 /// The capacity will remain at least as large as both the length
675 /// and the supplied value.
677 /// Panics if the current capacity is smaller than the supplied
678 /// minimum capacity.
683 /// #![feature(shrink_to)]
684 /// use std::collections::VecDeque;
686 /// let mut buf = VecDeque::with_capacity(15);
687 /// buf.extend(0..4);
688 /// assert_eq!(buf.capacity(), 15);
689 /// buf.shrink_to(6);
690 /// assert!(buf.capacity() >= 6);
691 /// buf.shrink_to(0);
692 /// assert!(buf.capacity() >= 4);
694 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
695 pub fn shrink_to(&mut self, min_capacity: usize) {
696 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
698 // +1 since the ringbuffer always leaves one space empty
699 // len + 1 can't overflow for an existing, well-formed ringbuffer.
700 let target_cap = cmp::max(
701 cmp::max(min_capacity, self.len()) + 1,
703 ).next_power_of_two();
705 if target_cap < self.cap() {
706 // There are three cases of interest:
707 // All elements are out of desired bounds
708 // Elements are contiguous, and head is out of desired bounds
709 // Elements are discontiguous, and tail is out of desired bounds
711 // At all other times, element positions are unaffected.
713 // Indicates that elements at the head should be moved.
714 let head_outside = self.head == 0 || self.head >= target_cap;
715 // Move elements from out of desired bounds (positions after target_cap)
716 if self.tail >= target_cap && head_outside {
718 // [. . . . . . . . o o o o o o o . ]
720 // [o o o o o o o . ]
722 self.copy_nonoverlapping(0, self.tail, self.len());
724 self.head = self.len();
726 } else if self.tail != 0 && self.tail < target_cap && head_outside {
728 // [. . . o o o o o o o . . . . . . ]
730 // [o o . o o o o o ]
731 let len = self.wrap_sub(self.head, target_cap);
733 self.copy_nonoverlapping(0, target_cap, len);
736 debug_assert!(self.head < self.tail);
737 } else if self.tail >= target_cap {
739 // [o o o o o . . . . . . . . . o o ]
741 // [o o o o o . o o ]
742 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
743 let len = self.cap() - self.tail;
744 let new_tail = target_cap - len;
746 self.copy_nonoverlapping(new_tail, self.tail, len);
748 self.tail = new_tail;
749 debug_assert!(self.head < self.tail);
752 self.buf.shrink_to_fit(target_cap);
754 debug_assert!(self.head < self.cap());
755 debug_assert!(self.tail < self.cap());
756 debug_assert!(self.cap().count_ones() == 1);
760 /// Shortens the `VecDeque`, dropping excess elements from the back.
762 /// If `len` is greater than the `VecDeque`'s current length, this has no
768 /// use std::collections::VecDeque;
770 /// let mut buf = VecDeque::new();
771 /// buf.push_back(5);
772 /// buf.push_back(10);
773 /// buf.push_back(15);
774 /// assert_eq!(buf, [5, 10, 15]);
776 /// assert_eq!(buf, [5]);
778 #[stable(feature = "deque_extras", since = "1.16.0")]
779 pub fn truncate(&mut self, len: usize) {
780 for _ in len..self.len() {
785 /// Returns a front-to-back iterator.
790 /// use std::collections::VecDeque;
792 /// let mut buf = VecDeque::new();
793 /// buf.push_back(5);
794 /// buf.push_back(3);
795 /// buf.push_back(4);
796 /// let b: &[_] = &[&5, &3, &4];
797 /// let c: Vec<&i32> = buf.iter().collect();
798 /// assert_eq!(&c[..], b);
800 #[stable(feature = "rust1", since = "1.0.0")]
801 pub fn iter(&self) -> Iter<'_, T> {
805 ring: unsafe { self.buffer_as_slice() },
809 /// Returns a front-to-back iterator that returns mutable references.
814 /// use std::collections::VecDeque;
816 /// let mut buf = VecDeque::new();
817 /// buf.push_back(5);
818 /// buf.push_back(3);
819 /// buf.push_back(4);
820 /// for num in buf.iter_mut() {
823 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
824 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
826 #[stable(feature = "rust1", since = "1.0.0")]
827 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
831 ring: unsafe { self.buffer_as_mut_slice() },
835 /// Returns a pair of slices which contain, in order, the contents of the
841 /// use std::collections::VecDeque;
843 /// let mut vector = VecDeque::new();
845 /// vector.push_back(0);
846 /// vector.push_back(1);
847 /// vector.push_back(2);
849 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
851 /// vector.push_front(10);
852 /// vector.push_front(9);
854 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
857 #[stable(feature = "deque_extras_15", since = "1.5.0")]
858 pub fn as_slices(&self) -> (&[T], &[T]) {
860 let buf = self.buffer_as_slice();
861 RingSlices::ring_slices(buf, self.head, self.tail)
865 /// Returns a pair of slices which contain, in order, the contents of the
871 /// use std::collections::VecDeque;
873 /// let mut vector = VecDeque::new();
875 /// vector.push_back(0);
876 /// vector.push_back(1);
878 /// vector.push_front(10);
879 /// vector.push_front(9);
881 /// vector.as_mut_slices().0[0] = 42;
882 /// vector.as_mut_slices().1[0] = 24;
883 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
886 #[stable(feature = "deque_extras_15", since = "1.5.0")]
887 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
889 let head = self.head;
890 let tail = self.tail;
891 let buf = self.buffer_as_mut_slice();
892 RingSlices::ring_slices(buf, head, tail)
896 /// Returns the number of elements in the `VecDeque`.
901 /// use std::collections::VecDeque;
903 /// let mut v = VecDeque::new();
904 /// assert_eq!(v.len(), 0);
906 /// assert_eq!(v.len(), 1);
908 #[stable(feature = "rust1", since = "1.0.0")]
909 pub fn len(&self) -> usize {
910 count(self.tail, self.head, self.cap())
913 /// Returns `true` if the `VecDeque` is empty.
918 /// use std::collections::VecDeque;
920 /// let mut v = VecDeque::new();
921 /// assert!(v.is_empty());
923 /// assert!(!v.is_empty());
925 #[stable(feature = "rust1", since = "1.0.0")]
926 pub fn is_empty(&self) -> bool {
927 self.tail == self.head
930 /// Creates a draining iterator that removes the specified range in the
931 /// `VecDeque` and yields the removed items.
933 /// Note 1: The element range is removed even if the iterator is not
934 /// consumed until the end.
936 /// Note 2: It is unspecified how many elements are removed from the deque,
937 /// if the `Drain` value is not dropped, but the borrow it holds expires
938 /// (e.g., due to `mem::forget`).
942 /// Panics if the starting point is greater than the end point or if
943 /// the end point is greater than the length of the vector.
948 /// use std::collections::VecDeque;
950 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
951 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
952 /// assert_eq!(drained, [3]);
953 /// assert_eq!(v, [1, 2]);
955 /// // A full range clears all contents
957 /// assert!(v.is_empty());
960 #[stable(feature = "drain", since = "1.6.0")]
961 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
962 where R: RangeBounds<usize>
966 // When the Drain is first created, the source deque is shortened to
967 // make sure no uninitialized or moved-from elements are accessible at
968 // all if the Drain's destructor never gets to run.
970 // Drain will ptr::read out the values to remove.
971 // When finished, the remaining data will be copied back to cover the hole,
972 // and the head/tail values will be restored correctly.
974 let len = self.len();
975 let start = match range.start_bound() {
977 Excluded(&n) => n + 1,
980 let end = match range.end_bound() {
981 Included(&n) => n + 1,
985 assert!(start <= end, "drain lower bound was too large");
986 assert!(end <= len, "drain upper bound was too large");
988 // The deque's elements are parted into three segments:
989 // * self.tail -> drain_tail
990 // * drain_tail -> drain_head
991 // * drain_head -> self.head
993 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
995 // We store drain_tail as self.head, and drain_head and self.head as
996 // after_tail and after_head respectively on the Drain. This also
997 // truncates the effective array such that if the Drain is leaked, we
998 // have forgotten about the potentially moved values after the start of
1002 // [. . . o o x x o o . . .]
1004 let drain_tail = self.wrap_add(self.tail, start);
1005 let drain_head = self.wrap_add(self.tail, end);
1006 let head = self.head;
1008 // "forget" about the values after the start of the drain until after
1009 // the drain is complete and the Drain destructor is run.
1010 self.head = drain_tail;
1013 deque: NonNull::from(&mut *self),
1014 after_tail: drain_head,
1019 // Crucially, we only create shared references from `self` here and read from
1020 // it. We do not write to `self` nor reborrow to a mutable reference.
1021 // Hence the raw pointer we created above, for `deque`, remains valid.
1022 ring: unsafe { self.buffer_as_slice() },
1027 /// Clears the `VecDeque`, removing all values.
1032 /// use std::collections::VecDeque;
1034 /// let mut v = VecDeque::new();
1037 /// assert!(v.is_empty());
1039 #[stable(feature = "rust1", since = "1.0.0")]
1041 pub fn clear(&mut self) {
1045 /// Returns `true` if the `VecDeque` contains an element equal to the
1051 /// use std::collections::VecDeque;
1053 /// let mut vector: VecDeque<u32> = VecDeque::new();
1055 /// vector.push_back(0);
1056 /// vector.push_back(1);
1058 /// assert_eq!(vector.contains(&1), true);
1059 /// assert_eq!(vector.contains(&10), false);
1061 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1062 pub fn contains(&self, x: &T) -> bool
1063 where T: PartialEq<T>
1065 let (a, b) = self.as_slices();
1066 a.contains(x) || b.contains(x)
1069 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1075 /// use std::collections::VecDeque;
1077 /// let mut d = VecDeque::new();
1078 /// assert_eq!(d.front(), None);
1082 /// assert_eq!(d.front(), Some(&1));
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 pub fn front(&self) -> Option<&T> {
1086 if !self.is_empty() {
1093 /// Provides a mutable reference to the front element, or `None` if the
1094 /// `VecDeque` is empty.
1099 /// use std::collections::VecDeque;
1101 /// let mut d = VecDeque::new();
1102 /// assert_eq!(d.front_mut(), None);
1106 /// match d.front_mut() {
1107 /// Some(x) => *x = 9,
1110 /// assert_eq!(d.front(), Some(&9));
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn front_mut(&mut self) -> Option<&mut T> {
1114 if !self.is_empty() {
1121 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1127 /// use std::collections::VecDeque;
1129 /// let mut d = VecDeque::new();
1130 /// assert_eq!(d.back(), None);
1134 /// assert_eq!(d.back(), Some(&2));
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn back(&self) -> Option<&T> {
1138 if !self.is_empty() {
1139 Some(&self[self.len() - 1])
1145 /// Provides a mutable reference to the back element, or `None` if the
1146 /// `VecDeque` is empty.
1151 /// use std::collections::VecDeque;
1153 /// let mut d = VecDeque::new();
1154 /// assert_eq!(d.back(), None);
1158 /// match d.back_mut() {
1159 /// Some(x) => *x = 9,
1162 /// assert_eq!(d.back(), Some(&9));
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 pub fn back_mut(&mut self) -> Option<&mut T> {
1166 let len = self.len();
1167 if !self.is_empty() {
1168 Some(&mut self[len - 1])
1174 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1180 /// use std::collections::VecDeque;
1182 /// let mut d = VecDeque::new();
1186 /// assert_eq!(d.pop_front(), Some(1));
1187 /// assert_eq!(d.pop_front(), Some(2));
1188 /// assert_eq!(d.pop_front(), None);
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 pub fn pop_front(&mut self) -> Option<T> {
1192 if self.is_empty() {
1195 let tail = self.tail;
1196 self.tail = self.wrap_add(self.tail, 1);
1197 unsafe { Some(self.buffer_read(tail)) }
1201 /// Prepends an element to the `VecDeque`.
1206 /// use std::collections::VecDeque;
1208 /// let mut d = VecDeque::new();
1209 /// d.push_front(1);
1210 /// d.push_front(2);
1211 /// assert_eq!(d.front(), Some(&2));
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 pub fn push_front(&mut self, value: T) {
1215 self.grow_if_necessary();
1217 self.tail = self.wrap_sub(self.tail, 1);
1218 let tail = self.tail;
1220 self.buffer_write(tail, value);
1224 /// Appends an element to the back of the `VecDeque`.
1229 /// use std::collections::VecDeque;
1231 /// let mut buf = VecDeque::new();
1232 /// buf.push_back(1);
1233 /// buf.push_back(3);
1234 /// assert_eq!(3, *buf.back().unwrap());
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 pub fn push_back(&mut self, value: T) {
1238 self.grow_if_necessary();
1240 let head = self.head;
1241 self.head = self.wrap_add(self.head, 1);
1242 unsafe { self.buffer_write(head, value) }
1245 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1251 /// use std::collections::VecDeque;
1253 /// let mut buf = VecDeque::new();
1254 /// assert_eq!(buf.pop_back(), None);
1255 /// buf.push_back(1);
1256 /// buf.push_back(3);
1257 /// assert_eq!(buf.pop_back(), Some(3));
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 pub fn pop_back(&mut self) -> Option<T> {
1261 if self.is_empty() {
1264 self.head = self.wrap_sub(self.head, 1);
1265 let head = self.head;
1266 unsafe { Some(self.buffer_read(head)) }
1271 fn is_contiguous(&self) -> bool {
1272 self.tail <= self.head
1275 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1278 /// This does not preserve ordering, but is O(1).
1280 /// Returns `None` if `index` is out of bounds.
1282 /// Element at index 0 is the front of the queue.
1287 /// use std::collections::VecDeque;
1289 /// let mut buf = VecDeque::new();
1290 /// assert_eq!(buf.swap_remove_back(0), None);
1291 /// buf.push_back(1);
1292 /// buf.push_back(2);
1293 /// buf.push_back(3);
1294 /// assert_eq!(buf, [1, 2, 3]);
1296 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1297 /// assert_eq!(buf, [3, 2]);
1299 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1300 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1301 let length = self.len();
1302 if length > 0 && index < length - 1 {
1303 self.swap(index, length - 1);
1304 } else if index >= length {
1310 /// Removes an element from anywhere in the `VecDeque` and returns it,
1311 /// replacing it with the first element.
1313 /// This does not preserve ordering, but is O(1).
1315 /// Returns `None` if `index` is out of bounds.
1317 /// Element at index 0 is the front of the queue.
1322 /// use std::collections::VecDeque;
1324 /// let mut buf = VecDeque::new();
1325 /// assert_eq!(buf.swap_remove_front(0), None);
1326 /// buf.push_back(1);
1327 /// buf.push_back(2);
1328 /// buf.push_back(3);
1329 /// assert_eq!(buf, [1, 2, 3]);
1331 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1332 /// assert_eq!(buf, [2, 1]);
1334 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1335 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1336 let length = self.len();
1337 if length > 0 && index < length && index != 0 {
1338 self.swap(index, 0);
1339 } else if index >= length {
1345 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1346 /// greater than or equal to `index` towards the back.
1348 /// Element at index 0 is the front of the queue.
1352 /// Panics if `index` is greater than `VecDeque`'s length
1357 /// use std::collections::VecDeque;
1359 /// let mut vec_deque = VecDeque::new();
1360 /// vec_deque.push_back('a');
1361 /// vec_deque.push_back('b');
1362 /// vec_deque.push_back('c');
1363 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1365 /// vec_deque.insert(1, 'd');
1366 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1368 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1369 pub fn insert(&mut self, index: usize, value: T) {
1370 assert!(index <= self.len(), "index out of bounds");
1371 self.grow_if_necessary();
1373 // Move the least number of elements in the ring buffer and insert
1376 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1378 // There are three main cases:
1379 // Elements are contiguous
1380 // - special case when tail is 0
1381 // Elements are discontiguous and the insert is in the tail section
1382 // Elements are discontiguous and the insert is in the head section
1384 // For each of those there are two more cases:
1385 // Insert is closer to tail
1386 // Insert is closer to head
1388 // Key: H - self.head
1390 // o - Valid element
1391 // I - Insertion element
1392 // A - The element that should be after the insertion point
1393 // M - Indicates element was moved
1395 let idx = self.wrap_add(self.tail, index);
1397 let distance_to_tail = index;
1398 let distance_to_head = self.len() - index;
1400 let contiguous = self.is_contiguous();
1402 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1403 (true, true, _) if index == 0 => {
1408 // [A o o o o o o . . . . . . . . .]
1411 // [A o o o o o o o . . . . . I]
1414 self.tail = self.wrap_sub(self.tail, 1);
1416 (true, true, _) => {
1418 // contiguous, insert closer to tail:
1421 // [. . . o o A o o o o . . . . . .]
1424 // [. . o o I A o o o o . . . . . .]
1427 // contiguous, insert closer to tail and tail is 0:
1431 // [o o A o o o o . . . . . . . . .]
1434 // [o I A o o o o o . . . . . . . o]
1437 let new_tail = self.wrap_sub(self.tail, 1);
1439 self.copy(new_tail, self.tail, 1);
1440 // Already moved the tail, so we only copy `index - 1` elements.
1441 self.copy(self.tail, self.tail + 1, index - 1);
1443 self.tail = new_tail;
1446 (true, false, _) => {
1448 // contiguous, insert closer to head:
1451 // [. . . o o o o A o o . . . . . .]
1454 // [. . . o o o o I A o o . . . . .]
1457 self.copy(idx + 1, idx, self.head - idx);
1458 self.head = self.wrap_add(self.head, 1);
1461 (false, true, true) => {
1463 // discontiguous, insert closer to tail, tail section:
1466 // [o o o o o o . . . . . o o A o o]
1469 // [o o o o o o . . . . o o I A o o]
1472 self.copy(self.tail - 1, self.tail, index);
1476 (false, false, true) => {
1478 // discontiguous, insert closer to head, tail section:
1481 // [o o . . . . . . . o o o o o A o]
1484 // [o o o . . . . . . o o o o o I A]
1487 // copy elements up to new head
1488 self.copy(1, 0, self.head);
1490 // copy last element into empty spot at bottom of buffer
1491 self.copy(0, self.cap() - 1, 1);
1493 // move elements from idx to end forward not including ^ element
1494 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1499 (false, true, false) if idx == 0 => {
1501 // discontiguous, insert is closer to tail, head section,
1502 // and is at index zero in the internal buffer:
1505 // [A o o o o o o o o o . . . o o o]
1508 // [A o o o o o o o o o . . o o o I]
1511 // copy elements up to new tail
1512 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1514 // copy last element into empty spot at bottom of buffer
1515 self.copy(self.cap() - 1, 0, 1);
1520 (false, true, false) => {
1522 // discontiguous, insert closer to tail, head section:
1525 // [o o o A o o o o o o . . . o o o]
1528 // [o o I A o o o o o o . . o o o o]
1531 // copy elements up to new tail
1532 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1534 // copy last element into empty spot at bottom of buffer
1535 self.copy(self.cap() - 1, 0, 1);
1537 // move elements from idx-1 to end forward not including ^ element
1538 self.copy(0, 1, idx - 1);
1543 (false, false, false) => {
1545 // discontiguous, insert closer to head, head section:
1548 // [o o o o A o o . . . . . . o o o]
1551 // [o o o o I A o o . . . . . o o o]
1554 self.copy(idx + 1, idx, self.head - idx);
1560 // tail might've been changed so we need to recalculate
1561 let new_idx = self.wrap_add(self.tail, index);
1563 self.buffer_write(new_idx, value);
1567 /// Removes and returns the element at `index` from the `VecDeque`.
1568 /// Whichever end is closer to the removal point will be moved to make
1569 /// room, and all the affected elements will be moved to new positions.
1570 /// Returns `None` if `index` is out of bounds.
1572 /// Element at index 0 is the front of the queue.
1577 /// use std::collections::VecDeque;
1579 /// let mut buf = VecDeque::new();
1580 /// buf.push_back(1);
1581 /// buf.push_back(2);
1582 /// buf.push_back(3);
1583 /// assert_eq!(buf, [1, 2, 3]);
1585 /// assert_eq!(buf.remove(1), Some(2));
1586 /// assert_eq!(buf, [1, 3]);
1588 #[stable(feature = "rust1", since = "1.0.0")]
1589 pub fn remove(&mut self, index: usize) -> Option<T> {
1590 if self.is_empty() || self.len() <= index {
1594 // There are three main cases:
1595 // Elements are contiguous
1596 // Elements are discontiguous and the removal is in the tail section
1597 // Elements are discontiguous and the removal is in the head section
1598 // - special case when elements are technically contiguous,
1599 // but self.head = 0
1601 // For each of those there are two more cases:
1602 // Insert is closer to tail
1603 // Insert is closer to head
1605 // Key: H - self.head
1607 // o - Valid element
1608 // x - Element marked for removal
1609 // R - Indicates element that is being removed
1610 // M - Indicates element was moved
1612 let idx = self.wrap_add(self.tail, index);
1614 let elem = unsafe { Some(self.buffer_read(idx)) };
1616 let distance_to_tail = index;
1617 let distance_to_head = self.len() - index;
1619 let contiguous = self.is_contiguous();
1621 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1622 (true, true, _) => {
1624 // contiguous, remove closer to tail:
1627 // [. . . o o x o o o o . . . . . .]
1630 // [. . . . o o o o o o . . . . . .]
1633 self.copy(self.tail + 1, self.tail, index);
1637 (true, false, _) => {
1639 // contiguous, remove closer to head:
1642 // [. . . o o o o x o o . . . . . .]
1645 // [. . . o o o o o o . . . . . . .]
1648 self.copy(idx, idx + 1, self.head - idx - 1);
1652 (false, true, true) => {
1654 // discontiguous, remove closer to tail, tail section:
1657 // [o o o o o o . . . . . o o x o o]
1660 // [o o o o o o . . . . . . o o o o]
1663 self.copy(self.tail + 1, self.tail, index);
1664 self.tail = self.wrap_add(self.tail, 1);
1667 (false, false, false) => {
1669 // discontiguous, remove closer to head, head section:
1672 // [o o o o x o o . . . . . . o o o]
1675 // [o o o o o o . . . . . . . o o o]
1678 self.copy(idx, idx + 1, self.head - idx - 1);
1682 (false, false, true) => {
1684 // discontiguous, remove closer to head, tail section:
1687 // [o o o . . . . . . o o o o o x o]
1690 // [o o . . . . . . . o o o o o o o]
1693 // or quasi-discontiguous, remove next to head, tail section:
1696 // [. . . . . . . . . o o o o o x o]
1699 // [. . . . . . . . . o o o o o o .]
1702 // draw in elements in the tail section
1703 self.copy(idx, idx + 1, self.cap() - idx - 1);
1705 // Prevents underflow.
1707 // copy first element into empty spot
1708 self.copy(self.cap() - 1, 0, 1);
1710 // move elements in the head section backwards
1711 self.copy(0, 1, self.head - 1);
1714 self.head = self.wrap_sub(self.head, 1);
1717 (false, true, false) => {
1719 // discontiguous, remove closer to tail, head section:
1722 // [o o x o o o o o o o . . . o o o]
1725 // [o o o o o o o o o o . . . . o o]
1728 // draw in elements up to idx
1729 self.copy(1, 0, idx);
1731 // copy last element into empty spot
1732 self.copy(0, self.cap() - 1, 1);
1734 // move elements from tail to end forward, excluding the last one
1735 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1737 self.tail = self.wrap_add(self.tail, 1);
1745 /// Splits the `VecDeque` into two at the given index.
1747 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1748 /// and the returned `VecDeque` contains elements `[at, len)`.
1750 /// Note that the capacity of `self` does not change.
1752 /// Element at index 0 is the front of the queue.
1756 /// Panics if `at > len`.
1761 /// use std::collections::VecDeque;
1763 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1764 /// let buf2 = buf.split_off(1);
1765 /// assert_eq!(buf, [1]);
1766 /// assert_eq!(buf2, [2, 3]);
1769 #[stable(feature = "split_off", since = "1.4.0")]
1770 pub fn split_off(&mut self, at: usize) -> Self {
1771 let len = self.len();
1772 assert!(at <= len, "`at` out of bounds");
1774 let other_len = len - at;
1775 let mut other = VecDeque::with_capacity(other_len);
1778 let (first_half, second_half) = self.as_slices();
1780 let first_len = first_half.len();
1781 let second_len = second_half.len();
1783 // `at` lies in the first half.
1784 let amount_in_first = first_len - at;
1786 ptr::copy_nonoverlapping(first_half.as_ptr().add(at),
1790 // just take all of the second half.
1791 ptr::copy_nonoverlapping(second_half.as_ptr(),
1792 other.ptr().add(amount_in_first),
1795 // `at` lies in the second half, need to factor in the elements we skipped
1796 // in the first half.
1797 let offset = at - first_len;
1798 let amount_in_second = second_len - offset;
1799 ptr::copy_nonoverlapping(second_half.as_ptr().add(offset),
1805 // Cleanup where the ends of the buffers are
1806 self.head = self.wrap_sub(self.head, other_len);
1807 other.head = other.wrap_index(other_len);
1812 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1816 /// Panics if the new number of elements in self overflows a `usize`.
1821 /// use std::collections::VecDeque;
1823 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1824 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1825 /// buf.append(&mut buf2);
1826 /// assert_eq!(buf, [1, 2, 3, 4]);
1827 /// assert_eq!(buf2, []);
1830 #[stable(feature = "append", since = "1.4.0")]
1831 pub fn append(&mut self, other: &mut Self) {
1833 self.extend(other.drain(..));
1836 /// Retains only the elements specified by the predicate.
1838 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1839 /// This method operates in place, visiting each element exactly once in the
1840 /// original order, and preserves the order of the retained elements.
1845 /// use std::collections::VecDeque;
1847 /// let mut buf = VecDeque::new();
1848 /// buf.extend(1..5);
1849 /// buf.retain(|&x| x%2 == 0);
1850 /// assert_eq!(buf, [2, 4]);
1853 /// The exact order may be useful for tracking external state, like an index.
1856 /// use std::collections::VecDeque;
1858 /// let mut buf = VecDeque::new();
1859 /// buf.extend(1..6);
1861 /// let keep = [false, true, true, false, true];
1863 /// buf.retain(|_| (keep[i], i += 1).0);
1864 /// assert_eq!(buf, [2, 3, 5]);
1866 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1867 pub fn retain<F>(&mut self, mut f: F)
1868 where F: FnMut(&T) -> bool
1870 let len = self.len();
1876 self.swap(i - del, i);
1880 self.truncate(len - del);
1884 // This may panic or abort
1886 fn grow_if_necessary(&mut self) {
1888 let old_cap = self.cap();
1891 self.handle_capacity_increase(old_cap);
1893 debug_assert!(!self.is_full());
1897 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
1898 /// either by removing excess elements from the back or by appending
1899 /// elements generated by calling `generator` to the back.
1904 /// use std::collections::VecDeque;
1906 /// let mut buf = VecDeque::new();
1907 /// buf.push_back(5);
1908 /// buf.push_back(10);
1909 /// buf.push_back(15);
1910 /// assert_eq!(buf, [5, 10, 15]);
1912 /// buf.resize_with(5, Default::default);
1913 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
1915 /// buf.resize_with(2, || unreachable!());
1916 /// assert_eq!(buf, [5, 10]);
1918 /// let mut state = 100;
1919 /// buf.resize_with(5, || { state += 1; state });
1920 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
1922 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1923 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut()->T) {
1924 let len = self.len();
1927 self.extend(repeat_with(generator).take(new_len - len))
1929 self.truncate(new_len);
1933 /// Rotates the double-ended queue `mid` places to the left.
1936 /// - Rotates item `mid` into the first position.
1937 /// - Pops the first `mid` items and pushes them to the end.
1938 /// - Rotates `len() - mid` places to the right.
1942 /// If `mid` is greater than `len()`. Note that `mid == len()`
1943 /// does _not_ panic and is a no-op rotation.
1947 /// Takes `O(min(mid, len() - mid))` time and no extra space.
1952 /// use std::collections::VecDeque;
1954 /// let mut buf: VecDeque<_> = (0..10).collect();
1956 /// buf.rotate_left(3);
1957 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
1959 /// for i in 1..10 {
1960 /// assert_eq!(i * 3 % 10, buf[0]);
1961 /// buf.rotate_left(3);
1963 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1965 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
1966 pub fn rotate_left(&mut self, mid: usize) {
1967 assert!(mid <= self.len());
1968 let k = self.len() - mid;
1970 unsafe { self.rotate_left_inner(mid) }
1972 unsafe { self.rotate_right_inner(k) }
1976 /// Rotates the double-ended queue `k` places to the right.
1979 /// - Rotates the first item into position `k`.
1980 /// - Pops the last `k` items and pushes them to the front.
1981 /// - Rotates `len() - k` places to the left.
1985 /// If `k` is greater than `len()`. Note that `k == len()`
1986 /// does _not_ panic and is a no-op rotation.
1990 /// Takes `O(min(k, len() - k))` time and no extra space.
1995 /// use std::collections::VecDeque;
1997 /// let mut buf: VecDeque<_> = (0..10).collect();
1999 /// buf.rotate_right(3);
2000 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2002 /// for i in 1..10 {
2003 /// assert_eq!(0, buf[i * 3 % 10]);
2004 /// buf.rotate_right(3);
2006 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2008 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2009 pub fn rotate_right(&mut self, k: usize) {
2010 assert!(k <= self.len());
2011 let mid = self.len() - k;
2013 unsafe { self.rotate_right_inner(k) }
2015 unsafe { self.rotate_left_inner(mid) }
2019 // Safety: the following two methods require that the rotation amount
2020 // be less than half the length of the deque.
2022 // `wrap_copy` requres that `min(x, cap() - x) + copy_len <= cap()`,
2023 // but than `min` is never more than half the capacity, regardless of x,
2024 // so it's sound to call here because we're calling with something
2025 // less than half the length, which is never above half the capacity.
2027 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2028 debug_assert!(mid * 2 <= self.len());
2029 self.wrap_copy(self.head, self.tail, mid);
2030 self.head = self.wrap_add(self.head, mid);
2031 self.tail = self.wrap_add(self.tail, mid);
2034 unsafe fn rotate_right_inner(&mut self, k: usize) {
2035 debug_assert!(k * 2 <= self.len());
2036 self.head = self.wrap_sub(self.head, k);
2037 self.tail = self.wrap_sub(self.tail, k);
2038 self.wrap_copy(self.tail, self.head, k);
2042 impl<T: Clone> VecDeque<T> {
2043 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2044 /// either by removing excess elements from the back or by appending clones of `value`
2050 /// use std::collections::VecDeque;
2052 /// let mut buf = VecDeque::new();
2053 /// buf.push_back(5);
2054 /// buf.push_back(10);
2055 /// buf.push_back(15);
2056 /// assert_eq!(buf, [5, 10, 15]);
2058 /// buf.resize(2, 0);
2059 /// assert_eq!(buf, [5, 10]);
2061 /// buf.resize(5, 20);
2062 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2064 #[stable(feature = "deque_extras", since = "1.16.0")]
2065 pub fn resize(&mut self, new_len: usize, value: T) {
2066 self.resize_with(new_len, || value.clone());
2070 /// Returns the index in the underlying buffer for a given logical element index.
2072 fn wrap_index(index: usize, size: usize) -> usize {
2073 // size is always a power of 2
2074 debug_assert!(size.is_power_of_two());
2078 /// Returns the two slices that cover the `VecDeque`'s valid range
2079 trait RingSlices: Sized {
2080 fn slice(self, from: usize, to: usize) -> Self;
2081 fn split_at(self, i: usize) -> (Self, Self);
2083 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
2084 let contiguous = tail <= head;
2086 let (empty, buf) = buf.split_at(0);
2087 (buf.slice(tail, head), empty)
2089 let (mid, right) = buf.split_at(tail);
2090 let (left, _) = mid.split_at(head);
2096 impl<T> RingSlices for &[T] {
2097 fn slice(self, from: usize, to: usize) -> Self {
2100 fn split_at(self, i: usize) -> (Self, Self) {
2105 impl<T> RingSlices for &mut [T] {
2106 fn slice(self, from: usize, to: usize) -> Self {
2109 fn split_at(self, i: usize) -> (Self, Self) {
2110 (*self).split_at_mut(i)
2114 /// Calculate the number of elements left to be read in the buffer
2116 fn count(tail: usize, head: usize, size: usize) -> usize {
2117 // size is always a power of 2
2118 (head.wrapping_sub(tail)) & (size - 1)
2121 /// An iterator over the elements of a `VecDeque`.
2123 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
2124 /// documentation for more.
2126 /// [`iter`]: struct.VecDeque.html#method.iter
2127 /// [`VecDeque`]: struct.VecDeque.html
2128 #[stable(feature = "rust1", since = "1.0.0")]
2129 pub struct Iter<'a, T: 'a> {
2135 #[stable(feature = "collection_debug", since = "1.17.0")]
2136 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
2137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2138 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2139 f.debug_tuple("Iter")
2146 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2147 #[stable(feature = "rust1", since = "1.0.0")]
2148 impl<T> Clone for Iter<'_, T> {
2149 fn clone(&self) -> Self {
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 impl<'a, T> Iterator for Iter<'a, T> {
2163 fn next(&mut self) -> Option<&'a T> {
2164 if self.tail == self.head {
2167 let tail = self.tail;
2168 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2169 unsafe { Some(self.ring.get_unchecked(tail)) }
2173 fn size_hint(&self) -> (usize, Option<usize>) {
2174 let len = count(self.tail, self.head, self.ring.len());
2178 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2179 where F: FnMut(Acc, Self::Item) -> Acc
2181 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2182 accum = front.iter().fold(accum, &mut f);
2183 back.iter().fold(accum, &mut f)
2186 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2189 F: FnMut(B, Self::Item) -> R,
2192 let (mut iter, final_res);
2193 if self.tail <= self.head {
2194 // single slice self.ring[self.tail..self.head]
2195 iter = self.ring[self.tail..self.head].iter();
2196 final_res = iter.try_fold(init, &mut f);
2198 // two slices: self.ring[self.tail..], self.ring[..self.head]
2199 let (front, back) = self.ring.split_at(self.tail);
2200 let mut back_iter = back.iter();
2201 let res = back_iter.try_fold(init, &mut f);
2202 let len = self.ring.len();
2203 self.tail = (self.ring.len() - back_iter.len()) & (len - 1);
2204 iter = front[..self.head].iter();
2205 final_res = iter.try_fold(res?, &mut f);
2207 self.tail = self.head - iter.len();
2212 fn last(mut self) -> Option<&'a T> {
2217 #[stable(feature = "rust1", since = "1.0.0")]
2218 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2220 fn next_back(&mut self) -> Option<&'a T> {
2221 if self.tail == self.head {
2224 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2225 unsafe { Some(self.ring.get_unchecked(self.head)) }
2228 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2229 where F: FnMut(Acc, Self::Item) -> Acc
2231 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2232 accum = back.iter().rfold(accum, &mut f);
2233 front.iter().rfold(accum, &mut f)
2236 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
2239 F: FnMut(B, Self::Item) -> R,
2242 let (mut iter, final_res);
2243 if self.tail <= self.head {
2244 // single slice self.ring[self.tail..self.head]
2245 iter = self.ring[self.tail..self.head].iter();
2246 final_res = iter.try_rfold(init, &mut f);
2248 // two slices: self.ring[self.tail..], self.ring[..self.head]
2249 let (front, back) = self.ring.split_at(self.tail);
2250 let mut front_iter = front[..self.head].iter();
2251 let res = front_iter.try_rfold(init, &mut f);
2252 self.head = front_iter.len();
2254 final_res = iter.try_rfold(res?, &mut f);
2256 self.head = self.tail + iter.len();
2261 #[stable(feature = "rust1", since = "1.0.0")]
2262 impl<T> ExactSizeIterator for Iter<'_, T> {
2263 fn is_empty(&self) -> bool {
2264 self.head == self.tail
2268 #[stable(feature = "fused", since = "1.26.0")]
2269 impl<T> FusedIterator for Iter<'_, T> {}
2272 /// A mutable iterator over the elements of a `VecDeque`.
2274 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2275 /// documentation for more.
2277 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2278 /// [`VecDeque`]: struct.VecDeque.html
2279 #[stable(feature = "rust1", since = "1.0.0")]
2280 pub struct IterMut<'a, T: 'a> {
2286 #[stable(feature = "collection_debug", since = "1.17.0")]
2287 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
2288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2289 let (front, back) = RingSlices::ring_slices(&*self.ring, self.head, self.tail);
2290 f.debug_tuple("IterMut")
2297 #[stable(feature = "rust1", since = "1.0.0")]
2298 impl<'a, T> Iterator for IterMut<'a, T> {
2299 type Item = &'a mut T;
2302 fn next(&mut self) -> Option<&'a mut T> {
2303 if self.tail == self.head {
2306 let tail = self.tail;
2307 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2310 let elem = self.ring.get_unchecked_mut(tail);
2311 Some(&mut *(elem as *mut _))
2316 fn size_hint(&self) -> (usize, Option<usize>) {
2317 let len = count(self.tail, self.head, self.ring.len());
2321 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2322 where F: FnMut(Acc, Self::Item) -> Acc
2324 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2325 accum = front.iter_mut().fold(accum, &mut f);
2326 back.iter_mut().fold(accum, &mut f)
2330 fn last(mut self) -> Option<&'a mut T> {
2335 #[stable(feature = "rust1", since = "1.0.0")]
2336 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2338 fn next_back(&mut self) -> Option<&'a mut T> {
2339 if self.tail == self.head {
2342 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2345 let elem = self.ring.get_unchecked_mut(self.head);
2346 Some(&mut *(elem as *mut _))
2350 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2351 where F: FnMut(Acc, Self::Item) -> Acc
2353 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2354 accum = back.iter_mut().rfold(accum, &mut f);
2355 front.iter_mut().rfold(accum, &mut f)
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 impl<T> ExactSizeIterator for IterMut<'_, T> {
2361 fn is_empty(&self) -> bool {
2362 self.head == self.tail
2366 #[stable(feature = "fused", since = "1.26.0")]
2367 impl<T> FusedIterator for IterMut<'_, T> {}
2369 /// An owning iterator over the elements of a `VecDeque`.
2371 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`][`VecDeque`]
2372 /// (provided by the `IntoIterator` trait). See its documentation for more.
2374 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2375 /// [`VecDeque`]: struct.VecDeque.html
2377 #[stable(feature = "rust1", since = "1.0.0")]
2378 pub struct IntoIter<T> {
2382 #[stable(feature = "collection_debug", since = "1.17.0")]
2383 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2384 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2385 f.debug_tuple("IntoIter")
2391 #[stable(feature = "rust1", since = "1.0.0")]
2392 impl<T> Iterator for IntoIter<T> {
2396 fn next(&mut self) -> Option<T> {
2397 self.inner.pop_front()
2401 fn size_hint(&self) -> (usize, Option<usize>) {
2402 let len = self.inner.len();
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 impl<T> DoubleEndedIterator for IntoIter<T> {
2410 fn next_back(&mut self) -> Option<T> {
2411 self.inner.pop_back()
2415 #[stable(feature = "rust1", since = "1.0.0")]
2416 impl<T> ExactSizeIterator for IntoIter<T> {
2417 fn is_empty(&self) -> bool {
2418 self.inner.is_empty()
2422 #[stable(feature = "fused", since = "1.26.0")]
2423 impl<T> FusedIterator for IntoIter<T> {}
2425 /// A draining iterator over the elements of a `VecDeque`.
2427 /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its
2428 /// documentation for more.
2430 /// [`drain`]: struct.VecDeque.html#method.drain
2431 /// [`VecDeque`]: struct.VecDeque.html
2432 #[stable(feature = "drain", since = "1.6.0")]
2433 pub struct Drain<'a, T: 'a> {
2437 deque: NonNull<VecDeque<T>>,
2440 #[stable(feature = "collection_debug", since = "1.17.0")]
2441 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2442 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2443 f.debug_tuple("Drain")
2444 .field(&self.after_tail)
2445 .field(&self.after_head)
2451 #[stable(feature = "drain", since = "1.6.0")]
2452 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2453 #[stable(feature = "drain", since = "1.6.0")]
2454 unsafe impl<T: Send> Send for Drain<'_, T> {}
2456 #[stable(feature = "drain", since = "1.6.0")]
2457 impl<T> Drop for Drain<'_, T> {
2458 fn drop(&mut self) {
2459 self.for_each(drop);
2461 let source_deque = unsafe { self.deque.as_mut() };
2463 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2466 // [. . . o o x x o o . . .]
2468 let orig_tail = source_deque.tail;
2469 let drain_tail = source_deque.head;
2470 let drain_head = self.after_tail;
2471 let orig_head = self.after_head;
2473 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2474 let head_len = count(drain_head, orig_head, source_deque.cap());
2476 // Restore the original head value
2477 source_deque.head = orig_head;
2479 match (tail_len, head_len) {
2481 source_deque.head = 0;
2482 source_deque.tail = 0;
2485 source_deque.tail = drain_head;
2488 source_deque.head = drain_tail;
2491 if tail_len <= head_len {
2492 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2493 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2495 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2496 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2503 #[stable(feature = "drain", since = "1.6.0")]
2504 impl<T> Iterator for Drain<'_, T> {
2508 fn next(&mut self) -> Option<T> {
2509 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2513 fn size_hint(&self) -> (usize, Option<usize>) {
2514 self.iter.size_hint()
2518 #[stable(feature = "drain", since = "1.6.0")]
2519 impl<T> DoubleEndedIterator for Drain<'_, T> {
2521 fn next_back(&mut self) -> Option<T> {
2522 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2526 #[stable(feature = "drain", since = "1.6.0")]
2527 impl<T> ExactSizeIterator for Drain<'_, T> {}
2529 #[stable(feature = "fused", since = "1.26.0")]
2530 impl<T> FusedIterator for Drain<'_, T> {}
2532 #[stable(feature = "rust1", since = "1.0.0")]
2533 impl<A: PartialEq> PartialEq for VecDeque<A> {
2534 fn eq(&self, other: &VecDeque<A>) -> bool {
2535 if self.len() != other.len() {
2538 let (sa, sb) = self.as_slices();
2539 let (oa, ob) = other.as_slices();
2540 if sa.len() == oa.len() {
2541 sa == oa && sb == ob
2542 } else if sa.len() < oa.len() {
2543 // Always divisible in three sections, for example:
2544 // self: [a b c|d e f]
2545 // other: [0 1 2 3|4 5]
2546 // front = 3, mid = 1,
2547 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2548 let front = sa.len();
2549 let mid = oa.len() - front;
2551 let (oa_front, oa_mid) = oa.split_at(front);
2552 let (sb_mid, sb_back) = sb.split_at(mid);
2553 debug_assert_eq!(sa.len(), oa_front.len());
2554 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2555 debug_assert_eq!(sb_back.len(), ob.len());
2556 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2558 let front = oa.len();
2559 let mid = sa.len() - front;
2561 let (sa_front, sa_mid) = sa.split_at(front);
2562 let (ob_mid, ob_back) = ob.split_at(mid);
2563 debug_assert_eq!(sa_front.len(), oa.len());
2564 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2565 debug_assert_eq!(sb.len(), ob_back.len());
2566 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2571 #[stable(feature = "rust1", since = "1.0.0")]
2572 impl<A: Eq> Eq for VecDeque<A> {}
2574 macro_rules! __impl_slice_eq1 {
2575 ([$($vars:tt)*] $lhs:ty, $rhs:ty, $($constraints:tt)*) => {
2576 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2577 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2582 fn eq(&self, other: &$rhs) -> bool {
2583 if self.len() != other.len() {
2586 let (sa, sb) = self.as_slices();
2587 let (oa, ob) = other[..].split_at(sa.len());
2588 sa == oa && sb == ob
2594 __impl_slice_eq1! { [] VecDeque<A>, Vec<B>, }
2595 __impl_slice_eq1! { [] VecDeque<A>, &[B], }
2596 __impl_slice_eq1! { [] VecDeque<A>, &mut [B], }
2597 __impl_slice_eq1! { [const N: usize] VecDeque<A>, [B; N], [B; N]: LengthAtMost32 }
2598 __impl_slice_eq1! { [const N: usize] VecDeque<A>, &[B; N], [B; N]: LengthAtMost32 }
2599 __impl_slice_eq1! { [const N: usize] VecDeque<A>, &mut [B; N], [B; N]: LengthAtMost32 }
2601 #[stable(feature = "rust1", since = "1.0.0")]
2602 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2603 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2604 self.iter().partial_cmp(other.iter())
2608 #[stable(feature = "rust1", since = "1.0.0")]
2609 impl<A: Ord> Ord for VecDeque<A> {
2611 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2612 self.iter().cmp(other.iter())
2616 #[stable(feature = "rust1", since = "1.0.0")]
2617 impl<A: Hash> Hash for VecDeque<A> {
2618 fn hash<H: Hasher>(&self, state: &mut H) {
2619 self.len().hash(state);
2620 let (a, b) = self.as_slices();
2621 Hash::hash_slice(a, state);
2622 Hash::hash_slice(b, state);
2626 #[stable(feature = "rust1", since = "1.0.0")]
2627 impl<A> Index<usize> for VecDeque<A> {
2631 fn index(&self, index: usize) -> &A {
2632 self.get(index).expect("Out of bounds access")
2636 #[stable(feature = "rust1", since = "1.0.0")]
2637 impl<A> IndexMut<usize> for VecDeque<A> {
2639 fn index_mut(&mut self, index: usize) -> &mut A {
2640 self.get_mut(index).expect("Out of bounds access")
2644 #[stable(feature = "rust1", since = "1.0.0")]
2645 impl<A> FromIterator<A> for VecDeque<A> {
2646 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2647 let iterator = iter.into_iter();
2648 let (lower, _) = iterator.size_hint();
2649 let mut deq = VecDeque::with_capacity(lower);
2650 deq.extend(iterator);
2655 #[stable(feature = "rust1", since = "1.0.0")]
2656 impl<T> IntoIterator for VecDeque<T> {
2658 type IntoIter = IntoIter<T>;
2660 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2662 fn into_iter(self) -> IntoIter<T> {
2663 IntoIter { inner: self }
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2670 type IntoIter = Iter<'a, T>;
2672 fn into_iter(self) -> Iter<'a, T> {
2677 #[stable(feature = "rust1", since = "1.0.0")]
2678 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2679 type Item = &'a mut T;
2680 type IntoIter = IterMut<'a, T>;
2682 fn into_iter(self) -> IterMut<'a, T> {
2687 #[stable(feature = "rust1", since = "1.0.0")]
2688 impl<A> Extend<A> for VecDeque<A> {
2689 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2690 iter.into_iter().for_each(move |elt| self.push_back(elt));
2694 #[stable(feature = "extend_ref", since = "1.2.0")]
2695 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2696 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2697 self.extend(iter.into_iter().cloned());
2701 #[stable(feature = "rust1", since = "1.0.0")]
2702 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2704 f.debug_list().entries(self).finish()
2708 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2709 impl<T> From<Vec<T>> for VecDeque<T> {
2710 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2712 /// [`Vec<T>`]: crate::vec::Vec
2713 /// [`VecDeque<T>`]: crate::collections::VecDeque
2715 /// This avoids reallocating where possible, but the conditions for that are
2716 /// strict, and subject to change, and so shouldn't be relied upon unless the
2717 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
2718 fn from(mut other: Vec<T>) -> Self {
2720 let other_buf = other.as_mut_ptr();
2721 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2722 let len = other.len();
2725 // We need to extend the buf if it's not a power of two, too small
2726 // or doesn't have at least one free space
2727 if !buf.capacity().is_power_of_two() || (buf.capacity() < (MINIMUM_CAPACITY + 1)) ||
2728 (buf.capacity() == len) {
2729 let cap = cmp::max(buf.capacity() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2730 buf.reserve_exact(len, cap - len);
2742 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2743 impl<T> From<VecDeque<T>> for Vec<T> {
2744 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2746 /// [`Vec<T>`]: crate::vec::Vec
2747 /// [`VecDeque<T>`]: crate::collections::VecDeque
2749 /// This never needs to re-allocate, but does need to do O(n) data movement if
2750 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2755 /// use std::collections::VecDeque;
2757 /// // This one is O(1).
2758 /// let deque: VecDeque<_> = (1..5).collect();
2759 /// let ptr = deque.as_slices().0.as_ptr();
2760 /// let vec = Vec::from(deque);
2761 /// assert_eq!(vec, [1, 2, 3, 4]);
2762 /// assert_eq!(vec.as_ptr(), ptr);
2764 /// // This one needs data rearranging.
2765 /// let mut deque: VecDeque<_> = (1..5).collect();
2766 /// deque.push_front(9);
2767 /// deque.push_front(8);
2768 /// let ptr = deque.as_slices().1.as_ptr();
2769 /// let vec = Vec::from(deque);
2770 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2771 /// assert_eq!(vec.as_ptr(), ptr);
2773 fn from(other: VecDeque<T>) -> Self {
2775 let buf = other.buf.ptr();
2776 let len = other.len();
2777 let tail = other.tail;
2778 let head = other.head;
2779 let cap = other.cap();
2781 // Need to move the ring to the front of the buffer, as vec will expect this.
2782 if other.is_contiguous() {
2783 ptr::copy(buf.add(tail), buf, len);
2785 if (tail - head) >= cmp::min(cap - tail, head) {
2786 // There is enough free space in the centre for the shortest block so we can
2787 // do this in at most three copy moves.
2788 if (cap - tail) > head {
2789 // right hand block is the long one; move that enough for the left
2790 ptr::copy(buf.add(tail),
2791 buf.add(tail - head),
2793 // copy left in the end
2794 ptr::copy(buf, buf.add(cap - head), head);
2795 // shift the new thing to the start
2796 ptr::copy(buf.add(tail - head), buf, len);
2798 // left hand block is the long one, we can do it in two!
2799 ptr::copy(buf, buf.add(cap - tail), head);
2800 ptr::copy(buf.add(tail), buf, cap - tail);
2803 // Need to use N swaps to move the ring
2804 // We can use the space at the end of the ring as a temp store
2806 let mut left_edge: usize = 0;
2807 let mut right_edge: usize = tail;
2809 // The general problem looks like this
2810 // GHIJKLM...ABCDEF - before any swaps
2811 // ABCDEFM...GHIJKL - after 1 pass of swaps
2812 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2813 // - then restart the algorithm with a new (smaller) store
2814 // Sometimes the temp store is reached when the right edge is at the end
2815 // of the buffer - this means we've hit the right order with fewer swaps!
2818 // ABCDEF.. - after four only swaps we've finished
2820 while left_edge < len && right_edge != cap {
2821 let mut right_offset = 0;
2822 for i in left_edge..right_edge {
2823 right_offset = (i - left_edge) % (cap - right_edge);
2824 let src: isize = (right_edge + right_offset) as isize;
2825 ptr::swap(buf.add(i), buf.offset(src));
2827 let n_ops = right_edge - left_edge;
2829 right_edge += right_offset + 1;
2835 let out = Vec::from_raw_parts(buf, len, cap);
2846 use super::VecDeque;
2849 #[cfg(not(miri))] // Miri does not support benchmarks
2850 fn bench_push_back_100(b: &mut test::Bencher) {
2851 let mut deq = VecDeque::with_capacity(101);
2862 #[cfg(not(miri))] // Miri does not support benchmarks
2863 fn bench_push_front_100(b: &mut test::Bencher) {
2864 let mut deq = VecDeque::with_capacity(101);
2875 #[cfg(not(miri))] // Miri does not support benchmarks
2876 fn bench_pop_back_100(b: &mut test::Bencher) {
2877 let mut deq = VecDeque::<i32>::with_capacity(101);
2882 while !deq.is_empty() {
2883 test::black_box(deq.pop_back());
2889 #[cfg(not(miri))] // Miri does not support benchmarks
2890 fn bench_pop_front_100(b: &mut test::Bencher) {
2891 let mut deq = VecDeque::<i32>::with_capacity(101);
2896 while !deq.is_empty() {
2897 test::black_box(deq.pop_front());
2903 fn test_swap_front_back_remove() {
2904 fn test(back: bool) {
2905 // This test checks that every single combination of tail position and length is tested.
2906 // Capacity 15 should be large enough to cover every case.
2907 let mut tester = VecDeque::with_capacity(15);
2908 let usable_cap = tester.capacity();
2909 let final_len = usable_cap / 2;
2911 for len in 0..final_len {
2912 let expected: VecDeque<_> = if back {
2915 (0..len).rev().collect()
2917 for tail_pos in 0..usable_cap {
2918 tester.tail = tail_pos;
2919 tester.head = tail_pos;
2921 for i in 0..len * 2 {
2922 tester.push_front(i);
2925 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2928 for i in 0..len * 2 {
2929 tester.push_back(i);
2932 let idx = tester.len() - 1 - i;
2933 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2936 assert!(tester.tail < tester.cap());
2937 assert!(tester.head < tester.cap());
2938 assert_eq!(tester, expected);
2948 // This test checks that every single combination of tail position, length, and
2949 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2951 let mut tester = VecDeque::with_capacity(15);
2952 // can't guarantee we got 15, so have to get what we got.
2953 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2954 // this test isn't covering what it wants to
2955 let cap = tester.capacity();
2958 // len is the length *after* insertion
2960 // 0, 1, 2, .., len - 1
2961 let expected = (0..).take(len).collect::<VecDeque<_>>();
2962 for tail_pos in 0..cap {
2963 for to_insert in 0..len {
2964 tester.tail = tail_pos;
2965 tester.head = tail_pos;
2968 tester.push_back(i);
2971 tester.insert(to_insert, to_insert);
2972 assert!(tester.tail < tester.cap());
2973 assert!(tester.head < tester.cap());
2974 assert_eq!(tester, expected);
2982 // This test checks that every single combination of tail position, length, and
2983 // removal position is tested. Capacity 15 should be large enough to cover every case.
2985 let mut tester = VecDeque::with_capacity(15);
2986 // can't guarantee we got 15, so have to get what we got.
2987 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2988 // this test isn't covering what it wants to
2989 let cap = tester.capacity();
2991 // len is the length *after* removal
2992 for len in 0..cap - 1 {
2993 // 0, 1, 2, .., len - 1
2994 let expected = (0..).take(len).collect::<VecDeque<_>>();
2995 for tail_pos in 0..cap {
2996 for to_remove in 0..=len {
2997 tester.tail = tail_pos;
2998 tester.head = tail_pos;
3001 tester.push_back(1234);
3003 tester.push_back(i);
3005 if to_remove == len {
3006 tester.push_back(1234);
3008 tester.remove(to_remove);
3009 assert!(tester.tail < tester.cap());
3010 assert!(tester.head < tester.cap());
3011 assert_eq!(tester, expected);
3019 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
3021 let cap = tester.capacity();
3022 for len in 0..=cap {
3023 for tail in 0..=cap {
3024 for drain_start in 0..=len {
3025 for drain_end in drain_start..=len {
3029 tester.push_back(i);
3032 // Check that we drain the correct values
3033 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
3034 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
3035 assert_eq!(drained, drained_expected);
3037 // We shouldn't have changed the capacity or made the
3038 // head or tail out of bounds
3039 assert_eq!(tester.capacity(), cap);
3040 assert!(tester.tail < tester.cap());
3041 assert!(tester.head < tester.cap());
3043 // We should see the correct values in the VecDeque
3044 let expected: VecDeque<_> = (0..drain_start)
3045 .chain(drain_end..len)
3047 assert_eq!(expected, tester);
3055 fn test_shrink_to_fit() {
3056 // This test checks that every single combination of head and tail position,
3057 // is tested. Capacity 15 should be large enough to cover every case.
3059 let mut tester = VecDeque::with_capacity(15);
3060 // can't guarantee we got 15, so have to get what we got.
3061 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
3062 // this test isn't covering what it wants to
3063 let cap = tester.capacity();
3065 let max_cap = tester.capacity();
3067 for len in 0..=cap {
3068 // 0, 1, 2, .., len - 1
3069 let expected = (0..).take(len).collect::<VecDeque<_>>();
3070 for tail_pos in 0..=max_cap {
3071 tester.tail = tail_pos;
3072 tester.head = tail_pos;
3075 tester.push_back(i);
3077 tester.shrink_to_fit();
3078 assert!(tester.capacity() <= cap);
3079 assert!(tester.tail < tester.cap());
3080 assert!(tester.head < tester.cap());
3081 assert_eq!(tester, expected);
3087 fn test_split_off() {
3088 // This test checks that every single combination of tail position, length, and
3089 // split position is tested. Capacity 15 should be large enough to cover every case.
3091 let mut tester = VecDeque::with_capacity(15);
3092 // can't guarantee we got 15, so have to get what we got.
3093 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
3094 // this test isn't covering what it wants to
3095 let cap = tester.capacity();
3097 // len is the length *before* splitting
3099 // index to split at
3101 // 0, 1, 2, .., at - 1 (may be empty)
3102 let expected_self = (0..).take(at).collect::<VecDeque<_>>();
3103 // at, at + 1, .., len - 1 (may be empty)
3104 let expected_other = (at..).take(len - at).collect::<VecDeque<_>>();
3106 for tail_pos in 0..cap {
3107 tester.tail = tail_pos;
3108 tester.head = tail_pos;
3110 tester.push_back(i);
3112 let result = tester.split_off(at);
3113 assert!(tester.tail < tester.cap());
3114 assert!(tester.head < tester.cap());
3115 assert!(result.tail < result.cap());
3116 assert!(result.head < result.cap());
3117 assert_eq!(tester, expected_self);
3118 assert_eq!(result, expected_other);
3125 fn test_from_vec() {
3126 use crate::vec::Vec;
3128 for len in 0..=cap {
3129 let mut vec = Vec::with_capacity(cap);
3132 let vd = VecDeque::from(vec.clone());
3133 assert!(vd.cap().is_power_of_two());
3134 assert_eq!(vd.len(), vec.len());
3135 assert!(vd.into_iter().eq(vec));
3141 fn test_vec_from_vecdeque() {
3142 use crate::vec::Vec;
3144 fn create_vec_and_test_convert(capacity: usize, offset: usize, len: usize) {
3145 let mut vd = VecDeque::with_capacity(capacity);
3146 for _ in 0..offset {
3152 let vec: Vec<_> = Vec::from(vd.clone());
3153 assert_eq!(vec.len(), vd.len());
3154 assert!(vec.into_iter().eq(vd));
3157 #[cfg(not(miri))] // Miri is too slow
3162 for cap_pwr in 0..max_pwr {
3163 // Make capacity as a (2^x)-1, so that the ring size is 2^x
3164 let cap = (2i32.pow(cap_pwr) - 1) as usize;
3166 // In these cases there is enough free space to solve it with copies
3167 for len in 0..((cap + 1) / 2) {
3168 // Test contiguous cases
3169 for offset in 0..(cap - len) {
3170 create_vec_and_test_convert(cap, offset, len)
3173 // Test cases where block at end of buffer is bigger than block at start
3174 for offset in (cap - len)..(cap - (len / 2)) {
3175 create_vec_and_test_convert(cap, offset, len)
3178 // Test cases where block at start of buffer is bigger than block at end
3179 for offset in (cap - (len / 2))..cap {
3180 create_vec_and_test_convert(cap, offset, len)
3184 // Now there's not (necessarily) space to straighten the ring with simple copies,
3185 // the ring will use swapping when:
3186 // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
3187 // right block size > free space && left block size > free space
3188 for len in ((cap + 1) / 2)..cap {
3189 // Test contiguous cases
3190 for offset in 0..(cap - len) {
3191 create_vec_and_test_convert(cap, offset, len)
3194 // Test cases where block at end of buffer is bigger than block at start
3195 for offset in (cap - len)..(cap - (len / 2)) {
3196 create_vec_and_test_convert(cap, offset, len)
3199 // Test cases where block at start of buffer is bigger than block at end
3200 for offset in (cap - (len / 2))..cap {
3201 create_vec_and_test_convert(cap, offset, len)
3209 use crate::boxed::Box;
3211 let mut dst = VecDeque::new();
3212 dst.push_front(Box::new(1));
3213 dst.push_front(Box::new(2));
3214 assert_eq!(*dst.pop_back().unwrap(), 1);
3216 let mut src = VecDeque::new();
3217 src.push_front(Box::new(2));
3218 dst.append(&mut src);