1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A double-ended queue implemented with a growable ring buffer.
13 //! This queue has `O(1)` amortized inserts and removals from both ends of the
14 //! container. It also has `O(1)` indexing like a vector. The contained elements
15 //! are not required to be copyable, and the queue will be sendable if the
16 //! contained type is sendable.
18 #![stable(feature = "rust1", since = "1.0.0")]
20 use core::cmp::Ordering;
22 use core::iter::{repeat, FromIterator, FusedIterator};
24 use core::ops::Bound::{Excluded, Included, Unbounded};
25 use core::ops::{Index, IndexMut, RangeBounds};
27 use core::ptr::NonNull;
30 use core::hash::{Hash, Hasher};
33 use collections::CollectionAllocErr;
37 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
38 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
39 #[cfg(target_pointer_width = "16")]
40 const MAXIMUM_ZST_CAPACITY: usize = 1 << (16 - 1); // Largest possible power of two
41 #[cfg(target_pointer_width = "32")]
42 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
43 #[cfg(target_pointer_width = "64")]
44 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
46 /// A double-ended queue implemented with a growable ring buffer.
48 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
49 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
50 /// push onto the back in this manner, and iterating over `VecDeque` goes front
53 /// [`push_back`]: #method.push_back
54 /// [`pop_front`]: #method.pop_front
55 /// [`extend`]: #method.extend
56 /// [`append`]: #method.append
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub struct VecDeque<T> {
59 // tail and head are pointers into the buffer. Tail always points
60 // to the first element that could be read, Head always points
61 // to where data should be written.
62 // If tail == head the buffer is empty. The length of the ringbuffer
63 // is defined as the distance between the two.
69 #[stable(feature = "rust1", since = "1.0.0")]
70 impl<T: Clone> Clone for VecDeque<T> {
71 fn clone(&self) -> VecDeque<T> {
72 self.iter().cloned().collect()
76 #[stable(feature = "rust1", since = "1.0.0")]
77 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
79 let (front, back) = self.as_mut_slices();
82 ptr::drop_in_place(front);
83 ptr::drop_in_place(back);
85 // RawVec handles deallocation
89 #[stable(feature = "rust1", since = "1.0.0")]
90 impl<T> Default for VecDeque<T> {
91 /// Creates an empty `VecDeque<T>`.
93 fn default() -> VecDeque<T> {
99 /// Marginally more convenient
101 fn ptr(&self) -> *mut T {
105 /// Marginally more convenient
107 fn cap(&self) -> usize {
108 if mem::size_of::<T>() == 0 {
109 // For zero sized types, we are always at maximum capacity
116 /// Turn ptr into a slice
118 unsafe fn buffer_as_slice(&self) -> &[T] {
119 slice::from_raw_parts(self.ptr(), self.cap())
122 /// Turn ptr into a mut slice
124 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
125 slice::from_raw_parts_mut(self.ptr(), self.cap())
128 /// Moves an element out of the buffer
130 unsafe fn buffer_read(&mut self, off: usize) -> T {
131 ptr::read(self.ptr().add(off))
134 /// Writes an element into the buffer, moving it.
136 unsafe fn buffer_write(&mut self, off: usize, value: T) {
137 ptr::write(self.ptr().add(off), value);
140 /// Returns `true` if and only if the buffer is at full capacity.
142 fn is_full(&self) -> bool {
143 self.cap() - self.len() == 1
146 /// Returns the index in the underlying buffer for a given logical element
149 fn wrap_index(&self, idx: usize) -> usize {
150 wrap_index(idx, self.cap())
153 /// Returns the index in the underlying buffer for a given logical element
156 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
157 wrap_index(idx.wrapping_add(addend), self.cap())
160 /// Returns the index in the underlying buffer for a given logical element
161 /// index - subtrahend.
163 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
164 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
167 /// Copies a contiguous block of memory len long from src to dst
169 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
170 debug_assert!(dst + len <= self.cap(),
171 "cpy dst={} src={} len={} cap={}",
176 debug_assert!(src + len <= self.cap(),
177 "cpy dst={} src={} len={} cap={}",
182 ptr::copy(self.ptr().add(src),
187 /// Copies a contiguous block of memory len long from src to dst
189 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
190 debug_assert!(dst + len <= self.cap(),
191 "cno dst={} src={} len={} cap={}",
196 debug_assert!(src + len <= self.cap(),
197 "cno dst={} src={} len={} cap={}",
202 ptr::copy_nonoverlapping(self.ptr().add(src),
207 /// Copies a potentially wrapping block of memory len long from src to dest.
208 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
209 /// most one continuous overlapping region between src and dest).
210 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
212 fn diff(a: usize, b: usize) -> usize {
213 if a <= b { b - a } else { a - b }
215 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
216 "wrc dst={} src={} len={} cap={}",
222 if src == dst || len == 0 {
226 let dst_after_src = self.wrap_sub(dst, src) < len;
228 let src_pre_wrap_len = self.cap() - src;
229 let dst_pre_wrap_len = self.cap() - dst;
230 let src_wraps = src_pre_wrap_len < len;
231 let dst_wraps = dst_pre_wrap_len < len;
233 match (dst_after_src, src_wraps, dst_wraps) {
234 (_, false, false) => {
235 // src doesn't wrap, dst doesn't wrap
238 // 1 [_ _ A A B B C C _]
239 // 2 [_ _ A A A A B B _]
242 self.copy(dst, src, len);
244 (false, false, true) => {
245 // dst before src, src doesn't wrap, dst wraps
248 // 1 [A A B B _ _ _ C C]
249 // 2 [A A B B _ _ _ A A]
250 // 3 [B B B B _ _ _ A A]
253 self.copy(dst, src, dst_pre_wrap_len);
254 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
256 (true, false, true) => {
257 // src before dst, src doesn't wrap, dst wraps
260 // 1 [C C _ _ _ A A B B]
261 // 2 [B B _ _ _ A A B B]
262 // 3 [B B _ _ _ A A A A]
265 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
266 self.copy(dst, src, dst_pre_wrap_len);
268 (false, true, false) => {
269 // dst before src, src wraps, dst doesn't wrap
272 // 1 [C C _ _ _ A A B B]
273 // 2 [C C _ _ _ B B B B]
274 // 3 [C C _ _ _ B B C C]
277 self.copy(dst, src, src_pre_wrap_len);
278 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
280 (true, true, false) => {
281 // src before dst, src wraps, dst doesn't wrap
284 // 1 [A A B B _ _ _ C C]
285 // 2 [A A A A _ _ _ C C]
286 // 3 [C C A A _ _ _ C C]
289 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
290 self.copy(dst, src, src_pre_wrap_len);
292 (false, true, true) => {
293 // dst before src, src wraps, dst wraps
296 // 1 [A B C D _ E F G H]
297 // 2 [A B C D _ E G H H]
298 // 3 [A B C D _ E G H A]
299 // 4 [B C C D _ E G H A]
302 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
303 let delta = dst_pre_wrap_len - src_pre_wrap_len;
304 self.copy(dst, src, src_pre_wrap_len);
305 self.copy(dst + src_pre_wrap_len, 0, delta);
306 self.copy(0, delta, len - dst_pre_wrap_len);
308 (true, true, true) => {
309 // src before dst, src wraps, dst wraps
312 // 1 [A B C D _ E F G H]
313 // 2 [A A B D _ E F G H]
314 // 3 [H A B D _ E F G H]
315 // 4 [H A B D _ E F F G]
318 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
319 let delta = src_pre_wrap_len - dst_pre_wrap_len;
320 self.copy(delta, 0, len - src_pre_wrap_len);
321 self.copy(0, self.cap() - delta, delta);
322 self.copy(dst, src, dst_pre_wrap_len);
327 /// Frobs the head and tail sections around to handle the fact that we
328 /// just reallocated. Unsafe because it trusts old_cap.
330 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
331 let new_cap = self.cap();
333 // Move the shortest contiguous section of the ring buffer
335 // [o o o o o o o . ]
337 // A [o o o o o o o . . . . . . . . . ]
339 // [o o . o o o o o ]
341 // B [. . . o o o o o o o . . . . . . ]
343 // [o o o o o . o o ]
345 // C [o o o o o . . . . . . . . . o o ]
347 if self.tail <= self.head {
350 } else if self.head < old_cap - self.tail {
352 self.copy_nonoverlapping(old_cap, 0, self.head);
353 self.head += old_cap;
354 debug_assert!(self.head > self.tail);
357 let new_tail = new_cap - (old_cap - self.tail);
358 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
359 self.tail = new_tail;
360 debug_assert!(self.head < self.tail);
362 debug_assert!(self.head < self.cap());
363 debug_assert!(self.tail < self.cap());
364 debug_assert!(self.cap().count_ones() == 1);
368 impl<T> VecDeque<T> {
369 /// Creates an empty `VecDeque`.
374 /// use std::collections::VecDeque;
376 /// let vector: VecDeque<u32> = VecDeque::new();
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub fn new() -> VecDeque<T> {
380 VecDeque::with_capacity(INITIAL_CAPACITY)
383 /// Creates an empty `VecDeque` with space for at least `n` elements.
388 /// use std::collections::VecDeque;
390 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub fn with_capacity(n: usize) -> VecDeque<T> {
394 // +1 since the ringbuffer always leaves one space empty
395 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
396 assert!(cap > n, "capacity overflow");
401 buf: RawVec::with_capacity(cap),
405 /// Retrieves an element in the `VecDeque` by index.
407 /// Element at index 0 is the front of the queue.
412 /// use std::collections::VecDeque;
414 /// let mut buf = VecDeque::new();
415 /// buf.push_back(3);
416 /// buf.push_back(4);
417 /// buf.push_back(5);
418 /// assert_eq!(buf.get(1), Some(&4));
420 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn get(&self, index: usize) -> Option<&T> {
422 if index < self.len() {
423 let idx = self.wrap_add(self.tail, index);
424 unsafe { Some(&*self.ptr().add(idx)) }
430 /// Retrieves an element in the `VecDeque` mutably by index.
432 /// Element at index 0 is the front of the queue.
437 /// use std::collections::VecDeque;
439 /// let mut buf = VecDeque::new();
440 /// buf.push_back(3);
441 /// buf.push_back(4);
442 /// buf.push_back(5);
443 /// if let Some(elem) = buf.get_mut(1) {
447 /// assert_eq!(buf[1], 7);
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
451 if index < self.len() {
452 let idx = self.wrap_add(self.tail, index);
453 unsafe { Some(&mut *self.ptr().add(idx)) }
459 /// Swaps elements at indices `i` and `j`.
461 /// `i` and `j` may be equal.
463 /// Element at index 0 is the front of the queue.
467 /// Panics if either index is out of bounds.
472 /// use std::collections::VecDeque;
474 /// let mut buf = VecDeque::new();
475 /// buf.push_back(3);
476 /// buf.push_back(4);
477 /// buf.push_back(5);
478 /// assert_eq!(buf, [3, 4, 5]);
480 /// assert_eq!(buf, [5, 4, 3]);
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn swap(&mut self, i: usize, j: usize) {
484 assert!(i < self.len());
485 assert!(j < self.len());
486 let ri = self.wrap_add(self.tail, i);
487 let rj = self.wrap_add(self.tail, j);
489 ptr::swap(self.ptr().add(ri),
494 /// Returns the number of elements the `VecDeque` can hold without
500 /// use std::collections::VecDeque;
502 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
503 /// assert!(buf.capacity() >= 10);
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub fn capacity(&self) -> usize {
511 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
512 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
514 /// Note that the allocator may give the collection more space than it requests. Therefore
515 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
516 /// insertions are expected.
520 /// Panics if the new capacity overflows `usize`.
525 /// use std::collections::VecDeque;
527 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
528 /// buf.reserve_exact(10);
529 /// assert!(buf.capacity() >= 11);
532 /// [`reserve`]: #method.reserve
533 #[stable(feature = "rust1", since = "1.0.0")]
534 pub fn reserve_exact(&mut self, additional: usize) {
535 self.reserve(additional);
538 /// Reserves capacity for at least `additional` more elements to be inserted in the given
539 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
543 /// Panics if the new capacity overflows `usize`.
548 /// use std::collections::VecDeque;
550 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
552 /// assert!(buf.capacity() >= 11);
554 #[stable(feature = "rust1", since = "1.0.0")]
555 pub fn reserve(&mut self, additional: usize) {
556 let old_cap = self.cap();
557 let used_cap = self.len() + 1;
558 let new_cap = used_cap.checked_add(additional)
559 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
560 .expect("capacity overflow");
562 if new_cap > old_cap {
563 self.buf.reserve_exact(used_cap, new_cap - used_cap);
565 self.handle_cap_increase(old_cap);
570 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
571 /// be inserted in the given `VecDeque<T>`. After calling `reserve_exact`,
572 /// capacity will be greater than or equal to `self.len() + additional`.
573 /// Does nothing if the capacity is already sufficient.
575 /// Note that the allocator may give the collection more space than it
576 /// requests. Therefore capacity can not be relied upon to be precisely
577 /// minimal. Prefer `reserve` if future insertions are expected.
581 /// If the capacity overflows, or the allocator reports a failure, then an error
587 /// #![feature(try_reserve)]
588 /// use std::collections::CollectionAllocErr;
589 /// use std::collections::VecDeque;
591 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
592 /// let mut output = VecDeque::new();
594 /// // Pre-reserve the memory, exiting if we can't
595 /// output.try_reserve_exact(data.len())?;
597 /// // Now we know this can't OOM in the middle of our complex work
598 /// output.extend(data.iter().map(|&val| {
599 /// val * 2 + 5 // very complicated
604 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
606 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
607 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
608 self.try_reserve(additional)
611 /// Tries to reserve capacity for at least `additional` more elements to be inserted
612 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
613 /// frequent reallocations. After calling `reserve`, capacity will be
614 /// greater than or equal to `self.len() + additional`. Does nothing if
615 /// capacity is already sufficient.
619 /// If the capacity overflows, or the allocator reports a failure, then an error
625 /// #![feature(try_reserve)]
626 /// use std::collections::CollectionAllocErr;
627 /// use std::collections::VecDeque;
629 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
630 /// let mut output = VecDeque::new();
632 /// // Pre-reserve the memory, exiting if we can't
633 /// output.try_reserve(data.len())?;
635 /// // Now we know this can't OOM in the middle of our complex work
636 /// output.extend(data.iter().map(|&val| {
637 /// val * 2 + 5 // very complicated
642 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
644 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
645 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
646 let old_cap = self.cap();
647 let used_cap = self.len() + 1;
648 let new_cap = used_cap.checked_add(additional)
649 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
650 .ok_or(CollectionAllocErr::CapacityOverflow)?;
652 if new_cap > old_cap {
653 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
655 self.handle_cap_increase(old_cap);
661 /// Shrinks the capacity of the `VecDeque` as much as possible.
663 /// It will drop down as close as possible to the length but the allocator may still inform the
664 /// `VecDeque` that there is space for a few more elements.
669 /// use std::collections::VecDeque;
671 /// let mut buf = VecDeque::with_capacity(15);
672 /// buf.extend(0..4);
673 /// assert_eq!(buf.capacity(), 15);
674 /// buf.shrink_to_fit();
675 /// assert!(buf.capacity() >= 4);
677 #[stable(feature = "deque_extras_15", since = "1.5.0")]
678 pub fn shrink_to_fit(&mut self) {
682 /// Shrinks the capacity of the `VecDeque` with a lower bound.
684 /// The capacity will remain at least as large as both the length
685 /// and the supplied value.
687 /// Panics if the current capacity is smaller than the supplied
688 /// minimum capacity.
693 /// #![feature(shrink_to)]
694 /// use std::collections::VecDeque;
696 /// let mut buf = VecDeque::with_capacity(15);
697 /// buf.extend(0..4);
698 /// assert_eq!(buf.capacity(), 15);
699 /// buf.shrink_to(6);
700 /// assert!(buf.capacity() >= 6);
701 /// buf.shrink_to(0);
702 /// assert!(buf.capacity() >= 4);
704 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
705 pub fn shrink_to(&mut self, min_capacity: usize) {
706 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
708 // +1 since the ringbuffer always leaves one space empty
709 // len + 1 can't overflow for an existing, well-formed ringbuffer.
710 let target_cap = cmp::max(
711 cmp::max(min_capacity, self.len()) + 1,
713 ).next_power_of_two();
715 if target_cap < self.cap() {
716 // There are three cases of interest:
717 // All elements are out of desired bounds
718 // Elements are contiguous, and head is out of desired bounds
719 // Elements are discontiguous, and tail is out of desired bounds
721 // At all other times, element positions are unaffected.
723 // Indicates that elements at the head should be moved.
724 let head_outside = self.head == 0 || self.head >= target_cap;
725 // Move elements from out of desired bounds (positions after target_cap)
726 if self.tail >= target_cap && head_outside {
728 // [. . . . . . . . o o o o o o o . ]
730 // [o o o o o o o . ]
732 self.copy_nonoverlapping(0, self.tail, self.len());
734 self.head = self.len();
736 } else if self.tail != 0 && self.tail < target_cap && head_outside {
738 // [. . . o o o o o o o . . . . . . ]
740 // [o o . o o o o o ]
741 let len = self.wrap_sub(self.head, target_cap);
743 self.copy_nonoverlapping(0, target_cap, len);
746 debug_assert!(self.head < self.tail);
747 } else if self.tail >= target_cap {
749 // [o o o o o . . . . . . . . . o o ]
751 // [o o o o o . o o ]
752 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
753 let len = self.cap() - self.tail;
754 let new_tail = target_cap - len;
756 self.copy_nonoverlapping(new_tail, self.tail, len);
758 self.tail = new_tail;
759 debug_assert!(self.head < self.tail);
762 self.buf.shrink_to_fit(target_cap);
764 debug_assert!(self.head < self.cap());
765 debug_assert!(self.tail < self.cap());
766 debug_assert!(self.cap().count_ones() == 1);
770 /// Shortens the `VecDeque`, dropping excess elements from the back.
772 /// If `len` is greater than the `VecDeque`'s current length, this has no
778 /// use std::collections::VecDeque;
780 /// let mut buf = VecDeque::new();
781 /// buf.push_back(5);
782 /// buf.push_back(10);
783 /// buf.push_back(15);
784 /// assert_eq!(buf, [5, 10, 15]);
786 /// assert_eq!(buf, [5]);
788 #[stable(feature = "deque_extras", since = "1.16.0")]
789 pub fn truncate(&mut self, len: usize) {
790 for _ in len..self.len() {
795 /// Returns a front-to-back iterator.
800 /// use std::collections::VecDeque;
802 /// let mut buf = VecDeque::new();
803 /// buf.push_back(5);
804 /// buf.push_back(3);
805 /// buf.push_back(4);
806 /// let b: &[_] = &[&5, &3, &4];
807 /// let c: Vec<&i32> = buf.iter().collect();
808 /// assert_eq!(&c[..], b);
810 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn iter(&self) -> Iter<T> {
815 ring: unsafe { self.buffer_as_slice() },
819 /// Returns a front-to-back iterator that returns mutable references.
824 /// use std::collections::VecDeque;
826 /// let mut buf = VecDeque::new();
827 /// buf.push_back(5);
828 /// buf.push_back(3);
829 /// buf.push_back(4);
830 /// for num in buf.iter_mut() {
833 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
834 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
836 #[stable(feature = "rust1", since = "1.0.0")]
837 pub fn iter_mut(&mut self) -> IterMut<T> {
841 ring: unsafe { self.buffer_as_mut_slice() },
845 /// Returns a pair of slices which contain, in order, the contents of the
851 /// use std::collections::VecDeque;
853 /// let mut vector = VecDeque::new();
855 /// vector.push_back(0);
856 /// vector.push_back(1);
857 /// vector.push_back(2);
859 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
861 /// vector.push_front(10);
862 /// vector.push_front(9);
864 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
867 #[stable(feature = "deque_extras_15", since = "1.5.0")]
868 pub fn as_slices(&self) -> (&[T], &[T]) {
870 let buf = self.buffer_as_slice();
871 RingSlices::ring_slices(buf, self.head, self.tail)
875 /// Returns a pair of slices which contain, in order, the contents of the
881 /// use std::collections::VecDeque;
883 /// let mut vector = VecDeque::new();
885 /// vector.push_back(0);
886 /// vector.push_back(1);
888 /// vector.push_front(10);
889 /// vector.push_front(9);
891 /// vector.as_mut_slices().0[0] = 42;
892 /// vector.as_mut_slices().1[0] = 24;
893 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
896 #[stable(feature = "deque_extras_15", since = "1.5.0")]
897 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
899 let head = self.head;
900 let tail = self.tail;
901 let buf = self.buffer_as_mut_slice();
902 RingSlices::ring_slices(buf, head, tail)
906 /// Returns the number of elements in the `VecDeque`.
911 /// use std::collections::VecDeque;
913 /// let mut v = VecDeque::new();
914 /// assert_eq!(v.len(), 0);
916 /// assert_eq!(v.len(), 1);
918 #[stable(feature = "rust1", since = "1.0.0")]
919 pub fn len(&self) -> usize {
920 count(self.tail, self.head, self.cap())
923 /// Returns `true` if the `VecDeque` is empty.
928 /// use std::collections::VecDeque;
930 /// let mut v = VecDeque::new();
931 /// assert!(v.is_empty());
933 /// assert!(!v.is_empty());
935 #[stable(feature = "rust1", since = "1.0.0")]
936 pub fn is_empty(&self) -> bool {
937 self.tail == self.head
940 /// Create a draining iterator that removes the specified range in the
941 /// `VecDeque` and yields the removed items.
943 /// Note 1: The element range is removed even if the iterator is not
944 /// consumed until the end.
946 /// Note 2: It is unspecified how many elements are removed from the deque,
947 /// if the `Drain` value is not dropped, but the borrow it holds expires
948 /// (eg. due to mem::forget).
952 /// Panics if the starting point is greater than the end point or if
953 /// the end point is greater than the length of the vector.
958 /// use std::collections::VecDeque;
960 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
961 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
962 /// assert_eq!(drained, [3]);
963 /// assert_eq!(v, [1, 2]);
965 /// // A full range clears all contents
967 /// assert!(v.is_empty());
970 #[stable(feature = "drain", since = "1.6.0")]
971 pub fn drain<R>(&mut self, range: R) -> Drain<T>
972 where R: RangeBounds<usize>
976 // When the Drain is first created, the source deque is shortened to
977 // make sure no uninitialized or moved-from elements are accessible at
978 // all if the Drain's destructor never gets to run.
980 // Drain will ptr::read out the values to remove.
981 // When finished, the remaining data will be copied back to cover the hole,
982 // and the head/tail values will be restored correctly.
984 let len = self.len();
985 let start = match range.start_bound() {
987 Excluded(&n) => n + 1,
990 let end = match range.end_bound() {
991 Included(&n) => n + 1,
995 assert!(start <= end, "drain lower bound was too large");
996 assert!(end <= len, "drain upper bound was too large");
998 // The deque's elements are parted into three segments:
999 // * self.tail -> drain_tail
1000 // * drain_tail -> drain_head
1001 // * drain_head -> self.head
1003 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1005 // We store drain_tail as self.head, and drain_head and self.head as
1006 // after_tail and after_head respectively on the Drain. This also
1007 // truncates the effective array such that if the Drain is leaked, we
1008 // have forgotten about the potentially moved values after the start of
1012 // [. . . o o x x o o . . .]
1014 let drain_tail = self.wrap_add(self.tail, start);
1015 let drain_head = self.wrap_add(self.tail, end);
1016 let head = self.head;
1018 // "forget" about the values after the start of the drain until after
1019 // the drain is complete and the Drain destructor is run.
1020 self.head = drain_tail;
1023 deque: NonNull::from(&mut *self),
1024 after_tail: drain_head,
1029 ring: unsafe { self.buffer_as_mut_slice() },
1034 /// Clears the `VecDeque`, removing all values.
1039 /// use std::collections::VecDeque;
1041 /// let mut v = VecDeque::new();
1044 /// assert!(v.is_empty());
1046 #[stable(feature = "rust1", since = "1.0.0")]
1048 pub fn clear(&mut self) {
1052 /// Returns `true` if the `VecDeque` contains an element equal to the
1058 /// use std::collections::VecDeque;
1060 /// let mut vector: VecDeque<u32> = VecDeque::new();
1062 /// vector.push_back(0);
1063 /// vector.push_back(1);
1065 /// assert_eq!(vector.contains(&1), true);
1066 /// assert_eq!(vector.contains(&10), false);
1068 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1069 pub fn contains(&self, x: &T) -> bool
1070 where T: PartialEq<T>
1072 let (a, b) = self.as_slices();
1073 a.contains(x) || b.contains(x)
1076 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1082 /// use std::collections::VecDeque;
1084 /// let mut d = VecDeque::new();
1085 /// assert_eq!(d.front(), None);
1089 /// assert_eq!(d.front(), Some(&1));
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 pub fn front(&self) -> Option<&T> {
1093 if !self.is_empty() {
1100 /// Provides a mutable reference to the front element, or `None` if the
1101 /// `VecDeque` is empty.
1106 /// use std::collections::VecDeque;
1108 /// let mut d = VecDeque::new();
1109 /// assert_eq!(d.front_mut(), None);
1113 /// match d.front_mut() {
1114 /// Some(x) => *x = 9,
1117 /// assert_eq!(d.front(), Some(&9));
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub fn front_mut(&mut self) -> Option<&mut T> {
1121 if !self.is_empty() {
1128 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1134 /// use std::collections::VecDeque;
1136 /// let mut d = VecDeque::new();
1137 /// assert_eq!(d.back(), None);
1141 /// assert_eq!(d.back(), Some(&2));
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 pub fn back(&self) -> Option<&T> {
1145 if !self.is_empty() {
1146 Some(&self[self.len() - 1])
1152 /// Provides a mutable reference to the back element, or `None` if the
1153 /// `VecDeque` is empty.
1158 /// use std::collections::VecDeque;
1160 /// let mut d = VecDeque::new();
1161 /// assert_eq!(d.back(), None);
1165 /// match d.back_mut() {
1166 /// Some(x) => *x = 9,
1169 /// assert_eq!(d.back(), Some(&9));
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 pub fn back_mut(&mut self) -> Option<&mut T> {
1173 let len = self.len();
1174 if !self.is_empty() {
1175 Some(&mut self[len - 1])
1181 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1187 /// use std::collections::VecDeque;
1189 /// let mut d = VecDeque::new();
1193 /// assert_eq!(d.pop_front(), Some(1));
1194 /// assert_eq!(d.pop_front(), Some(2));
1195 /// assert_eq!(d.pop_front(), None);
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn pop_front(&mut self) -> Option<T> {
1199 if self.is_empty() {
1202 let tail = self.tail;
1203 self.tail = self.wrap_add(self.tail, 1);
1204 unsafe { Some(self.buffer_read(tail)) }
1208 /// Prepends an element to the `VecDeque`.
1213 /// use std::collections::VecDeque;
1215 /// let mut d = VecDeque::new();
1216 /// d.push_front(1);
1217 /// d.push_front(2);
1218 /// assert_eq!(d.front(), Some(&2));
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub fn push_front(&mut self, value: T) {
1222 self.grow_if_necessary();
1224 self.tail = self.wrap_sub(self.tail, 1);
1225 let tail = self.tail;
1227 self.buffer_write(tail, value);
1231 /// Appends an element to the back of the `VecDeque`.
1236 /// use std::collections::VecDeque;
1238 /// let mut buf = VecDeque::new();
1239 /// buf.push_back(1);
1240 /// buf.push_back(3);
1241 /// assert_eq!(3, *buf.back().unwrap());
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 pub fn push_back(&mut self, value: T) {
1245 self.grow_if_necessary();
1247 let head = self.head;
1248 self.head = self.wrap_add(self.head, 1);
1249 unsafe { self.buffer_write(head, value) }
1252 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1258 /// use std::collections::VecDeque;
1260 /// let mut buf = VecDeque::new();
1261 /// assert_eq!(buf.pop_back(), None);
1262 /// buf.push_back(1);
1263 /// buf.push_back(3);
1264 /// assert_eq!(buf.pop_back(), Some(3));
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 pub fn pop_back(&mut self) -> Option<T> {
1268 if self.is_empty() {
1271 self.head = self.wrap_sub(self.head, 1);
1272 let head = self.head;
1273 unsafe { Some(self.buffer_read(head)) }
1278 fn is_contiguous(&self) -> bool {
1279 self.tail <= self.head
1282 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1285 /// This does not preserve ordering, but is O(1).
1287 /// Returns `None` if `index` is out of bounds.
1289 /// Element at index 0 is the front of the queue.
1294 /// use std::collections::VecDeque;
1296 /// let mut buf = VecDeque::new();
1297 /// assert_eq!(buf.swap_remove_back(0), None);
1298 /// buf.push_back(1);
1299 /// buf.push_back(2);
1300 /// buf.push_back(3);
1301 /// assert_eq!(buf, [1, 2, 3]);
1303 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1304 /// assert_eq!(buf, [3, 2]);
1306 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1307 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1308 let length = self.len();
1309 if length > 0 && index < length - 1 {
1310 self.swap(index, length - 1);
1311 } else if index >= length {
1317 /// Removes an element from anywhere in the `VecDeque` and returns it,
1318 /// replacing it with the first element.
1320 /// This does not preserve ordering, but is O(1).
1322 /// Returns `None` if `index` is out of bounds.
1324 /// Element at index 0 is the front of the queue.
1329 /// use std::collections::VecDeque;
1331 /// let mut buf = VecDeque::new();
1332 /// assert_eq!(buf.swap_remove_front(0), None);
1333 /// buf.push_back(1);
1334 /// buf.push_back(2);
1335 /// buf.push_back(3);
1336 /// assert_eq!(buf, [1, 2, 3]);
1338 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1339 /// assert_eq!(buf, [2, 1]);
1341 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1342 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1343 let length = self.len();
1344 if length > 0 && index < length && index != 0 {
1345 self.swap(index, 0);
1346 } else if index >= length {
1352 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1353 /// greater than or equal to `index` towards the back.
1355 /// Element at index 0 is the front of the queue.
1359 /// Panics if `index` is greater than `VecDeque`'s length
1364 /// use std::collections::VecDeque;
1366 /// let mut vec_deque = VecDeque::new();
1367 /// vec_deque.push_back('a');
1368 /// vec_deque.push_back('b');
1369 /// vec_deque.push_back('c');
1370 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1372 /// vec_deque.insert(1, 'd');
1373 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1375 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1376 pub fn insert(&mut self, index: usize, value: T) {
1377 assert!(index <= self.len(), "index out of bounds");
1378 self.grow_if_necessary();
1380 // Move the least number of elements in the ring buffer and insert
1383 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1385 // There are three main cases:
1386 // Elements are contiguous
1387 // - special case when tail is 0
1388 // Elements are discontiguous and the insert is in the tail section
1389 // Elements are discontiguous and the insert is in the head section
1391 // For each of those there are two more cases:
1392 // Insert is closer to tail
1393 // Insert is closer to head
1395 // Key: H - self.head
1397 // o - Valid element
1398 // I - Insertion element
1399 // A - The element that should be after the insertion point
1400 // M - Indicates element was moved
1402 let idx = self.wrap_add(self.tail, index);
1404 let distance_to_tail = index;
1405 let distance_to_head = self.len() - index;
1407 let contiguous = self.is_contiguous();
1409 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1410 (true, true, _) if index == 0 => {
1415 // [A o o o o o o . . . . . . . . .]
1418 // [A o o o o o o o . . . . . I]
1421 self.tail = self.wrap_sub(self.tail, 1);
1423 (true, true, _) => {
1425 // contiguous, insert closer to tail:
1428 // [. . . o o A o o o o . . . . . .]
1431 // [. . o o I A o o o o . . . . . .]
1434 // contiguous, insert closer to tail and tail is 0:
1438 // [o o A o o o o . . . . . . . . .]
1441 // [o I A o o o o o . . . . . . . o]
1444 let new_tail = self.wrap_sub(self.tail, 1);
1446 self.copy(new_tail, self.tail, 1);
1447 // Already moved the tail, so we only copy `index - 1` elements.
1448 self.copy(self.tail, self.tail + 1, index - 1);
1450 self.tail = new_tail;
1453 (true, false, _) => {
1455 // contiguous, insert closer to head:
1458 // [. . . o o o o A o o . . . . . .]
1461 // [. . . o o o o I A o o . . . . .]
1464 self.copy(idx + 1, idx, self.head - idx);
1465 self.head = self.wrap_add(self.head, 1);
1468 (false, true, true) => {
1470 // discontiguous, insert closer to tail, tail section:
1473 // [o o o o o o . . . . . o o A o o]
1476 // [o o o o o o . . . . o o I A o o]
1479 self.copy(self.tail - 1, self.tail, index);
1483 (false, false, true) => {
1485 // discontiguous, insert closer to head, tail section:
1488 // [o o . . . . . . . o o o o o A o]
1491 // [o o o . . . . . . o o o o o I A]
1494 // copy elements up to new head
1495 self.copy(1, 0, self.head);
1497 // copy last element into empty spot at bottom of buffer
1498 self.copy(0, self.cap() - 1, 1);
1500 // move elements from idx to end forward not including ^ element
1501 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1506 (false, true, false) if idx == 0 => {
1508 // discontiguous, insert is closer to tail, head section,
1509 // and is at index zero in the internal buffer:
1512 // [A o o o o o o o o o . . . o o o]
1515 // [A o o o o o o o o o . . o o o I]
1518 // copy elements up to new tail
1519 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1521 // copy last element into empty spot at bottom of buffer
1522 self.copy(self.cap() - 1, 0, 1);
1527 (false, true, false) => {
1529 // discontiguous, insert closer to tail, head section:
1532 // [o o o A o o o o o o . . . o o o]
1535 // [o o I A o o o o o o . . o o o o]
1538 // copy elements up to new tail
1539 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1541 // copy last element into empty spot at bottom of buffer
1542 self.copy(self.cap() - 1, 0, 1);
1544 // move elements from idx-1 to end forward not including ^ element
1545 self.copy(0, 1, idx - 1);
1550 (false, false, false) => {
1552 // discontiguous, insert closer to head, head section:
1555 // [o o o o A o o . . . . . . o o o]
1558 // [o o o o I A o o . . . . . o o o]
1561 self.copy(idx + 1, idx, self.head - idx);
1567 // tail might've been changed so we need to recalculate
1568 let new_idx = self.wrap_add(self.tail, index);
1570 self.buffer_write(new_idx, value);
1574 /// Removes and returns the element at `index` from the `VecDeque`.
1575 /// Whichever end is closer to the removal point will be moved to make
1576 /// room, and all the affected elements will be moved to new positions.
1577 /// Returns `None` if `index` is out of bounds.
1579 /// Element at index 0 is the front of the queue.
1584 /// use std::collections::VecDeque;
1586 /// let mut buf = VecDeque::new();
1587 /// buf.push_back(1);
1588 /// buf.push_back(2);
1589 /// buf.push_back(3);
1590 /// assert_eq!(buf, [1, 2, 3]);
1592 /// assert_eq!(buf.remove(1), Some(2));
1593 /// assert_eq!(buf, [1, 3]);
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 pub fn remove(&mut self, index: usize) -> Option<T> {
1597 if self.is_empty() || self.len() <= index {
1601 // There are three main cases:
1602 // Elements are contiguous
1603 // Elements are discontiguous and the removal is in the tail section
1604 // Elements are discontiguous and the removal is in the head section
1605 // - special case when elements are technically contiguous,
1606 // but self.head = 0
1608 // For each of those there are two more cases:
1609 // Insert is closer to tail
1610 // Insert is closer to head
1612 // Key: H - self.head
1614 // o - Valid element
1615 // x - Element marked for removal
1616 // R - Indicates element that is being removed
1617 // M - Indicates element was moved
1619 let idx = self.wrap_add(self.tail, index);
1621 let elem = unsafe { Some(self.buffer_read(idx)) };
1623 let distance_to_tail = index;
1624 let distance_to_head = self.len() - index;
1626 let contiguous = self.is_contiguous();
1628 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1629 (true, true, _) => {
1631 // contiguous, remove closer to tail:
1634 // [. . . o o x o o o o . . . . . .]
1637 // [. . . . o o o o o o . . . . . .]
1640 self.copy(self.tail + 1, self.tail, index);
1644 (true, false, _) => {
1646 // contiguous, remove closer to head:
1649 // [. . . o o o o x o o . . . . . .]
1652 // [. . . o o o o o o . . . . . . .]
1655 self.copy(idx, idx + 1, self.head - idx - 1);
1659 (false, true, true) => {
1661 // discontiguous, remove closer to tail, tail section:
1664 // [o o o o o o . . . . . o o x o o]
1667 // [o o o o o o . . . . . . o o o o]
1670 self.copy(self.tail + 1, self.tail, index);
1671 self.tail = self.wrap_add(self.tail, 1);
1674 (false, false, false) => {
1676 // discontiguous, remove closer to head, head section:
1679 // [o o o o x o o . . . . . . o o o]
1682 // [o o o o o o . . . . . . . o o o]
1685 self.copy(idx, idx + 1, self.head - idx - 1);
1689 (false, false, true) => {
1691 // discontiguous, remove closer to head, tail section:
1694 // [o o o . . . . . . o o o o o x o]
1697 // [o o . . . . . . . o o o o o o o]
1700 // or quasi-discontiguous, remove next to head, tail section:
1703 // [. . . . . . . . . o o o o o x o]
1706 // [. . . . . . . . . o o o o o o .]
1709 // draw in elements in the tail section
1710 self.copy(idx, idx + 1, self.cap() - idx - 1);
1712 // Prevents underflow.
1714 // copy first element into empty spot
1715 self.copy(self.cap() - 1, 0, 1);
1717 // move elements in the head section backwards
1718 self.copy(0, 1, self.head - 1);
1721 self.head = self.wrap_sub(self.head, 1);
1724 (false, true, false) => {
1726 // discontiguous, remove closer to tail, head section:
1729 // [o o x o o o o o o o . . . o o o]
1732 // [o o o o o o o o o o . . . . o o]
1735 // draw in elements up to idx
1736 self.copy(1, 0, idx);
1738 // copy last element into empty spot
1739 self.copy(0, self.cap() - 1, 1);
1741 // move elements from tail to end forward, excluding the last one
1742 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1744 self.tail = self.wrap_add(self.tail, 1);
1752 /// Splits the `VecDeque` into two at the given index.
1754 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1755 /// and the returned `VecDeque` contains elements `[at, len)`.
1757 /// Note that the capacity of `self` does not change.
1759 /// Element at index 0 is the front of the queue.
1763 /// Panics if `at > len`.
1768 /// use std::collections::VecDeque;
1770 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1771 /// let buf2 = buf.split_off(1);
1772 /// assert_eq!(buf, [1]);
1773 /// assert_eq!(buf2, [2, 3]);
1776 #[stable(feature = "split_off", since = "1.4.0")]
1777 pub fn split_off(&mut self, at: usize) -> Self {
1778 let len = self.len();
1779 assert!(at <= len, "`at` out of bounds");
1781 let other_len = len - at;
1782 let mut other = VecDeque::with_capacity(other_len);
1785 let (first_half, second_half) = self.as_slices();
1787 let first_len = first_half.len();
1788 let second_len = second_half.len();
1790 // `at` lies in the first half.
1791 let amount_in_first = first_len - at;
1793 ptr::copy_nonoverlapping(first_half.as_ptr().add(at),
1797 // just take all of the second half.
1798 ptr::copy_nonoverlapping(second_half.as_ptr(),
1799 other.ptr().add(amount_in_first),
1802 // `at` lies in the second half, need to factor in the elements we skipped
1803 // in the first half.
1804 let offset = at - first_len;
1805 let amount_in_second = second_len - offset;
1806 ptr::copy_nonoverlapping(second_half.as_ptr().add(offset),
1812 // Cleanup where the ends of the buffers are
1813 self.head = self.wrap_sub(self.head, other_len);
1814 other.head = other.wrap_index(other_len);
1819 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1823 /// Panics if the new number of elements in self overflows a `usize`.
1828 /// use std::collections::VecDeque;
1830 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1831 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1832 /// buf.append(&mut buf2);
1833 /// assert_eq!(buf, [1, 2, 3, 4]);
1834 /// assert_eq!(buf2, []);
1837 #[stable(feature = "append", since = "1.4.0")]
1838 pub fn append(&mut self, other: &mut Self) {
1840 self.extend(other.drain(..));
1843 /// Retains only the elements specified by the predicate.
1845 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1846 /// This method operates in place and preserves the order of the retained
1852 /// use std::collections::VecDeque;
1854 /// let mut buf = VecDeque::new();
1855 /// buf.extend(1..5);
1856 /// buf.retain(|&x| x%2 == 0);
1857 /// assert_eq!(buf, [2, 4]);
1859 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1860 pub fn retain<F>(&mut self, mut f: F)
1861 where F: FnMut(&T) -> bool
1863 let len = self.len();
1869 self.swap(i - del, i);
1873 self.truncate(len - del);
1877 // This may panic or abort
1879 fn grow_if_necessary(&mut self) {
1881 let old_cap = self.cap();
1884 self.handle_cap_increase(old_cap);
1886 debug_assert!(!self.is_full());
1891 impl<T: Clone> VecDeque<T> {
1892 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1893 /// either by removing excess elements from the back or by appending clones of `value`
1899 /// use std::collections::VecDeque;
1901 /// let mut buf = VecDeque::new();
1902 /// buf.push_back(5);
1903 /// buf.push_back(10);
1904 /// buf.push_back(15);
1905 /// assert_eq!(buf, [5, 10, 15]);
1907 /// buf.resize(2, 0);
1908 /// assert_eq!(buf, [5, 10]);
1910 /// buf.resize(5, 20);
1911 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
1913 #[stable(feature = "deque_extras", since = "1.16.0")]
1914 pub fn resize(&mut self, new_len: usize, value: T) {
1915 let len = self.len();
1918 self.extend(repeat(value).take(new_len - len))
1920 self.truncate(new_len);
1925 /// Returns the index in the underlying buffer for a given logical element index.
1927 fn wrap_index(index: usize, size: usize) -> usize {
1928 // size is always a power of 2
1929 debug_assert!(size.is_power_of_two());
1933 /// Returns the two slices that cover the `VecDeque`'s valid range
1934 trait RingSlices: Sized {
1935 fn slice(self, from: usize, to: usize) -> Self;
1936 fn split_at(self, i: usize) -> (Self, Self);
1938 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
1939 let contiguous = tail <= head;
1941 let (empty, buf) = buf.split_at(0);
1942 (buf.slice(tail, head), empty)
1944 let (mid, right) = buf.split_at(tail);
1945 let (left, _) = mid.split_at(head);
1951 impl<'a, T> RingSlices for &'a [T] {
1952 fn slice(self, from: usize, to: usize) -> Self {
1955 fn split_at(self, i: usize) -> (Self, Self) {
1960 impl<'a, T> RingSlices for &'a mut [T] {
1961 fn slice(self, from: usize, to: usize) -> Self {
1964 fn split_at(self, i: usize) -> (Self, Self) {
1965 (*self).split_at_mut(i)
1969 /// Calculate the number of elements left to be read in the buffer
1971 fn count(tail: usize, head: usize, size: usize) -> usize {
1972 // size is always a power of 2
1973 (head.wrapping_sub(tail)) & (size - 1)
1976 /// An iterator over the elements of a `VecDeque`.
1978 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
1979 /// documentation for more.
1981 /// [`iter`]: struct.VecDeque.html#method.iter
1982 /// [`VecDeque`]: struct.VecDeque.html
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 pub struct Iter<'a, T: 'a> {
1990 #[stable(feature = "collection_debug", since = "1.17.0")]
1991 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1992 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1993 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
1994 f.debug_tuple("Iter")
2001 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 impl<'a, T> Clone for Iter<'a, T> {
2004 fn clone(&self) -> Iter<'a, T> {
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl<'a, T> Iterator for Iter<'a, T> {
2018 fn next(&mut self) -> Option<&'a T> {
2019 if self.tail == self.head {
2022 let tail = self.tail;
2023 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2024 unsafe { Some(self.ring.get_unchecked(tail)) }
2028 fn size_hint(&self) -> (usize, Option<usize>) {
2029 let len = count(self.tail, self.head, self.ring.len());
2033 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2034 where F: FnMut(Acc, Self::Item) -> Acc
2036 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2037 accum = front.iter().fold(accum, &mut f);
2038 back.iter().fold(accum, &mut f)
2042 #[stable(feature = "rust1", since = "1.0.0")]
2043 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2045 fn next_back(&mut self) -> Option<&'a T> {
2046 if self.tail == self.head {
2049 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2050 unsafe { Some(self.ring.get_unchecked(self.head)) }
2053 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2054 where F: FnMut(Acc, Self::Item) -> Acc
2056 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2057 accum = back.iter().rfold(accum, &mut f);
2058 front.iter().rfold(accum, &mut f)
2062 #[stable(feature = "rust1", since = "1.0.0")]
2063 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
2064 fn is_empty(&self) -> bool {
2065 self.head == self.tail
2069 #[stable(feature = "fused", since = "1.26.0")]
2070 impl<'a, T> FusedIterator for Iter<'a, T> {}
2073 /// A mutable iterator over the elements of a `VecDeque`.
2075 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2076 /// documentation for more.
2078 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2079 /// [`VecDeque`]: struct.VecDeque.html
2080 #[stable(feature = "rust1", since = "1.0.0")]
2081 pub struct IterMut<'a, T: 'a> {
2087 #[stable(feature = "collection_debug", since = "1.17.0")]
2088 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2089 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2090 let (front, back) = RingSlices::ring_slices(&*self.ring, self.head, self.tail);
2091 f.debug_tuple("IterMut")
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 impl<'a, T> Iterator for IterMut<'a, T> {
2100 type Item = &'a mut T;
2103 fn next(&mut self) -> Option<&'a mut T> {
2104 if self.tail == self.head {
2107 let tail = self.tail;
2108 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2111 let elem = self.ring.get_unchecked_mut(tail);
2112 Some(&mut *(elem as *mut _))
2117 fn size_hint(&self) -> (usize, Option<usize>) {
2118 let len = count(self.tail, self.head, self.ring.len());
2122 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2123 where F: FnMut(Acc, Self::Item) -> Acc
2125 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2126 accum = front.iter_mut().fold(accum, &mut f);
2127 back.iter_mut().fold(accum, &mut f)
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2134 fn next_back(&mut self) -> Option<&'a mut T> {
2135 if self.tail == self.head {
2138 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2141 let elem = self.ring.get_unchecked_mut(self.head);
2142 Some(&mut *(elem as *mut _))
2146 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2147 where F: FnMut(Acc, Self::Item) -> Acc
2149 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2150 accum = back.iter_mut().rfold(accum, &mut f);
2151 front.iter_mut().rfold(accum, &mut f)
2155 #[stable(feature = "rust1", since = "1.0.0")]
2156 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
2157 fn is_empty(&self) -> bool {
2158 self.head == self.tail
2162 #[stable(feature = "fused", since = "1.26.0")]
2163 impl<'a, T> FusedIterator for IterMut<'a, T> {}
2165 /// An owning iterator over the elements of a `VecDeque`.
2167 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`][`VecDeque`]
2168 /// (provided by the `IntoIterator` trait). See its documentation for more.
2170 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2171 /// [`VecDeque`]: struct.VecDeque.html
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 pub struct IntoIter<T> {
2178 #[stable(feature = "collection_debug", since = "1.17.0")]
2179 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2181 f.debug_tuple("IntoIter")
2187 #[stable(feature = "rust1", since = "1.0.0")]
2188 impl<T> Iterator for IntoIter<T> {
2192 fn next(&mut self) -> Option<T> {
2193 self.inner.pop_front()
2197 fn size_hint(&self) -> (usize, Option<usize>) {
2198 let len = self.inner.len();
2203 #[stable(feature = "rust1", since = "1.0.0")]
2204 impl<T> DoubleEndedIterator for IntoIter<T> {
2206 fn next_back(&mut self) -> Option<T> {
2207 self.inner.pop_back()
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 impl<T> ExactSizeIterator for IntoIter<T> {
2213 fn is_empty(&self) -> bool {
2214 self.inner.is_empty()
2218 #[stable(feature = "fused", since = "1.26.0")]
2219 impl<T> FusedIterator for IntoIter<T> {}
2221 /// A draining iterator over the elements of a `VecDeque`.
2223 /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its
2224 /// documentation for more.
2226 /// [`drain`]: struct.VecDeque.html#method.drain
2227 /// [`VecDeque`]: struct.VecDeque.html
2228 #[stable(feature = "drain", since = "1.6.0")]
2229 pub struct Drain<'a, T: 'a> {
2233 deque: NonNull<VecDeque<T>>,
2236 #[stable(feature = "collection_debug", since = "1.17.0")]
2237 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2238 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2239 f.debug_tuple("Drain")
2240 .field(&self.after_tail)
2241 .field(&self.after_head)
2247 #[stable(feature = "drain", since = "1.6.0")]
2248 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2249 #[stable(feature = "drain", since = "1.6.0")]
2250 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2252 #[stable(feature = "drain", since = "1.6.0")]
2253 impl<'a, T: 'a> Drop for Drain<'a, T> {
2254 fn drop(&mut self) {
2255 self.for_each(drop);
2257 let source_deque = unsafe { self.deque.as_mut() };
2259 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2262 // [. . . o o x x o o . . .]
2264 let orig_tail = source_deque.tail;
2265 let drain_tail = source_deque.head;
2266 let drain_head = self.after_tail;
2267 let orig_head = self.after_head;
2269 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2270 let head_len = count(drain_head, orig_head, source_deque.cap());
2272 // Restore the original head value
2273 source_deque.head = orig_head;
2275 match (tail_len, head_len) {
2277 source_deque.head = 0;
2278 source_deque.tail = 0;
2281 source_deque.tail = drain_head;
2284 source_deque.head = drain_tail;
2287 if tail_len <= head_len {
2288 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2289 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2291 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2292 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2299 #[stable(feature = "drain", since = "1.6.0")]
2300 impl<'a, T: 'a> Iterator for Drain<'a, T> {
2304 fn next(&mut self) -> Option<T> {
2305 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2309 fn size_hint(&self) -> (usize, Option<usize>) {
2310 self.iter.size_hint()
2314 #[stable(feature = "drain", since = "1.6.0")]
2315 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
2317 fn next_back(&mut self) -> Option<T> {
2318 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2322 #[stable(feature = "drain", since = "1.6.0")]
2323 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
2325 #[stable(feature = "fused", since = "1.26.0")]
2326 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
2328 #[stable(feature = "rust1", since = "1.0.0")]
2329 impl<A: PartialEq> PartialEq for VecDeque<A> {
2330 fn eq(&self, other: &VecDeque<A>) -> bool {
2331 if self.len() != other.len() {
2334 let (sa, sb) = self.as_slices();
2335 let (oa, ob) = other.as_slices();
2336 if sa.len() == oa.len() {
2337 sa == oa && sb == ob
2338 } else if sa.len() < oa.len() {
2339 // Always divisible in three sections, for example:
2340 // self: [a b c|d e f]
2341 // other: [0 1 2 3|4 5]
2342 // front = 3, mid = 1,
2343 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2344 let front = sa.len();
2345 let mid = oa.len() - front;
2347 let (oa_front, oa_mid) = oa.split_at(front);
2348 let (sb_mid, sb_back) = sb.split_at(mid);
2349 debug_assert_eq!(sa.len(), oa_front.len());
2350 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2351 debug_assert_eq!(sb_back.len(), ob.len());
2352 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2354 let front = oa.len();
2355 let mid = sa.len() - front;
2357 let (sa_front, sa_mid) = sa.split_at(front);
2358 let (ob_mid, ob_back) = ob.split_at(mid);
2359 debug_assert_eq!(sa_front.len(), oa.len());
2360 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2361 debug_assert_eq!(sb.len(), ob_back.len());
2362 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2367 #[stable(feature = "rust1", since = "1.0.0")]
2368 impl<A: Eq> Eq for VecDeque<A> {}
2370 macro_rules! __impl_slice_eq1 {
2371 ($Lhs: ty, $Rhs: ty) => {
2372 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2374 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2375 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2376 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2377 fn eq(&self, other: &$Rhs) -> bool {
2378 if self.len() != other.len() {
2381 let (sa, sb) = self.as_slices();
2382 let (oa, ob) = other[..].split_at(sa.len());
2383 sa == oa && sb == ob
2389 __impl_slice_eq1! { VecDeque<A>, Vec<B> }
2390 __impl_slice_eq1! { VecDeque<A>, &'b [B] }
2391 __impl_slice_eq1! { VecDeque<A>, &'b mut [B] }
2393 macro_rules! array_impls {
2396 __impl_slice_eq1! { VecDeque<A>, [B; $N] }
2397 __impl_slice_eq1! { VecDeque<A>, &'b [B; $N] }
2398 __impl_slice_eq1! { VecDeque<A>, &'b mut [B; $N] }
2405 10 11 12 13 14 15 16 17 18 19
2406 20 21 22 23 24 25 26 27 28 29
2410 #[stable(feature = "rust1", since = "1.0.0")]
2411 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2412 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2413 self.iter().partial_cmp(other.iter())
2417 #[stable(feature = "rust1", since = "1.0.0")]
2418 impl<A: Ord> Ord for VecDeque<A> {
2420 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2421 self.iter().cmp(other.iter())
2425 #[stable(feature = "rust1", since = "1.0.0")]
2426 impl<A: Hash> Hash for VecDeque<A> {
2427 fn hash<H: Hasher>(&self, state: &mut H) {
2428 self.len().hash(state);
2429 let (a, b) = self.as_slices();
2430 Hash::hash_slice(a, state);
2431 Hash::hash_slice(b, state);
2435 #[stable(feature = "rust1", since = "1.0.0")]
2436 impl<A> Index<usize> for VecDeque<A> {
2440 fn index(&self, index: usize) -> &A {
2441 self.get(index).expect("Out of bounds access")
2445 #[stable(feature = "rust1", since = "1.0.0")]
2446 impl<A> IndexMut<usize> for VecDeque<A> {
2448 fn index_mut(&mut self, index: usize) -> &mut A {
2449 self.get_mut(index).expect("Out of bounds access")
2453 #[stable(feature = "rust1", since = "1.0.0")]
2454 impl<A> FromIterator<A> for VecDeque<A> {
2455 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2456 let iterator = iter.into_iter();
2457 let (lower, _) = iterator.size_hint();
2458 let mut deq = VecDeque::with_capacity(lower);
2459 deq.extend(iterator);
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 impl<T> IntoIterator for VecDeque<T> {
2467 type IntoIter = IntoIter<T>;
2469 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2471 fn into_iter(self) -> IntoIter<T> {
2472 IntoIter { inner: self }
2476 #[stable(feature = "rust1", since = "1.0.0")]
2477 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2479 type IntoIter = Iter<'a, T>;
2481 fn into_iter(self) -> Iter<'a, T> {
2486 #[stable(feature = "rust1", since = "1.0.0")]
2487 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2488 type Item = &'a mut T;
2489 type IntoIter = IterMut<'a, T>;
2491 fn into_iter(self) -> IterMut<'a, T> {
2496 #[stable(feature = "rust1", since = "1.0.0")]
2497 impl<A> Extend<A> for VecDeque<A> {
2498 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2500 self.push_back(elt);
2505 #[stable(feature = "extend_ref", since = "1.2.0")]
2506 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2507 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2508 self.extend(iter.into_iter().cloned());
2512 #[stable(feature = "rust1", since = "1.0.0")]
2513 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2514 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2515 f.debug_list().entries(self).finish()
2519 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2520 impl<T> From<Vec<T>> for VecDeque<T> {
2521 fn from(mut other: Vec<T>) -> Self {
2523 let other_buf = other.as_mut_ptr();
2524 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2525 let len = other.len();
2528 // We need to extend the buf if it's not a power of two, too small
2529 // or doesn't have at least one free space
2530 if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) ||
2531 (buf.cap() == len) {
2532 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2533 buf.reserve_exact(len, cap - len);
2545 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2546 impl<T> From<VecDeque<T>> for Vec<T> {
2547 fn from(other: VecDeque<T>) -> Self {
2549 let buf = other.buf.ptr();
2550 let len = other.len();
2551 let tail = other.tail;
2552 let head = other.head;
2553 let cap = other.cap();
2555 // Need to move the ring to the front of the buffer, as vec will expect this.
2556 if other.is_contiguous() {
2557 ptr::copy(buf.add(tail), buf, len);
2559 if (tail - head) >= cmp::min(cap - tail, head) {
2560 // There is enough free space in the centre for the shortest block so we can
2561 // do this in at most three copy moves.
2562 if (cap - tail) > head {
2563 // right hand block is the long one; move that enough for the left
2564 ptr::copy(buf.add(tail),
2565 buf.add(tail - head),
2567 // copy left in the end
2568 ptr::copy(buf, buf.add(cap - head), head);
2569 // shift the new thing to the start
2570 ptr::copy(buf.add(tail - head), buf, len);
2572 // left hand block is the long one, we can do it in two!
2573 ptr::copy(buf, buf.add(cap - tail), head);
2574 ptr::copy(buf.add(tail), buf, cap - tail);
2577 // Need to use N swaps to move the ring
2578 // We can use the space at the end of the ring as a temp store
2580 let mut left_edge: usize = 0;
2581 let mut right_edge: usize = tail;
2583 // The general problem looks like this
2584 // GHIJKLM...ABCDEF - before any swaps
2585 // ABCDEFM...GHIJKL - after 1 pass of swaps
2586 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2587 // - then restart the algorithm with a new (smaller) store
2588 // Sometimes the temp store is reached when the right edge is at the end
2589 // of the buffer - this means we've hit the right order with fewer swaps!
2592 // ABCDEF.. - after four only swaps we've finished
2594 while left_edge < len && right_edge != cap {
2595 let mut right_offset = 0;
2596 for i in left_edge..right_edge {
2597 right_offset = (i - left_edge) % (cap - right_edge);
2598 let src: isize = (right_edge + right_offset) as isize;
2599 ptr::swap(buf.add(i), buf.offset(src));
2601 let n_ops = right_edge - left_edge;
2603 right_edge += right_offset + 1;
2609 let out = Vec::from_raw_parts(buf, len, cap);
2620 use super::VecDeque;
2623 fn bench_push_back_100(b: &mut test::Bencher) {
2624 let mut deq = VecDeque::with_capacity(101);
2635 fn bench_push_front_100(b: &mut test::Bencher) {
2636 let mut deq = VecDeque::with_capacity(101);
2647 fn bench_pop_back_100(b: &mut test::Bencher) {
2648 let mut deq = VecDeque::<i32>::with_capacity(101);
2653 while !deq.is_empty() {
2654 test::black_box(deq.pop_back());
2660 fn bench_pop_front_100(b: &mut test::Bencher) {
2661 let mut deq = VecDeque::<i32>::with_capacity(101);
2666 while !deq.is_empty() {
2667 test::black_box(deq.pop_front());
2673 fn test_swap_front_back_remove() {
2674 fn test(back: bool) {
2675 // This test checks that every single combination of tail position and length is tested.
2676 // Capacity 15 should be large enough to cover every case.
2677 let mut tester = VecDeque::with_capacity(15);
2678 let usable_cap = tester.capacity();
2679 let final_len = usable_cap / 2;
2681 for len in 0..final_len {
2682 let expected: VecDeque<_> = if back {
2685 (0..len).rev().collect()
2687 for tail_pos in 0..usable_cap {
2688 tester.tail = tail_pos;
2689 tester.head = tail_pos;
2691 for i in 0..len * 2 {
2692 tester.push_front(i);
2695 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2698 for i in 0..len * 2 {
2699 tester.push_back(i);
2702 let idx = tester.len() - 1 - i;
2703 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2706 assert!(tester.tail < tester.cap());
2707 assert!(tester.head < tester.cap());
2708 assert_eq!(tester, expected);
2718 // This test checks that every single combination of tail position, length, and
2719 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2721 let mut tester = VecDeque::with_capacity(15);
2722 // can't guarantee we got 15, so have to get what we got.
2723 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2724 // this test isn't covering what it wants to
2725 let cap = tester.capacity();
2728 // len is the length *after* insertion
2730 // 0, 1, 2, .., len - 1
2731 let expected = (0..).take(len).collect::<VecDeque<_>>();
2732 for tail_pos in 0..cap {
2733 for to_insert in 0..len {
2734 tester.tail = tail_pos;
2735 tester.head = tail_pos;
2738 tester.push_back(i);
2741 tester.insert(to_insert, to_insert);
2742 assert!(tester.tail < tester.cap());
2743 assert!(tester.head < tester.cap());
2744 assert_eq!(tester, expected);
2752 // This test checks that every single combination of tail position, length, and
2753 // removal position is tested. Capacity 15 should be large enough to cover every case.
2755 let mut tester = VecDeque::with_capacity(15);
2756 // can't guarantee we got 15, so have to get what we got.
2757 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2758 // this test isn't covering what it wants to
2759 let cap = tester.capacity();
2761 // len is the length *after* removal
2762 for len in 0..cap - 1 {
2763 // 0, 1, 2, .., len - 1
2764 let expected = (0..).take(len).collect::<VecDeque<_>>();
2765 for tail_pos in 0..cap {
2766 for to_remove in 0..len + 1 {
2767 tester.tail = tail_pos;
2768 tester.head = tail_pos;
2771 tester.push_back(1234);
2773 tester.push_back(i);
2775 if to_remove == len {
2776 tester.push_back(1234);
2778 tester.remove(to_remove);
2779 assert!(tester.tail < tester.cap());
2780 assert!(tester.head < tester.cap());
2781 assert_eq!(tester, expected);
2789 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2791 let cap = tester.capacity();
2792 for len in 0..cap + 1 {
2793 for tail in 0..cap + 1 {
2794 for drain_start in 0..len + 1 {
2795 for drain_end in drain_start..len + 1 {
2799 tester.push_back(i);
2802 // Check that we drain the correct values
2803 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2804 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2805 assert_eq!(drained, drained_expected);
2807 // We shouldn't have changed the capacity or made the
2808 // head or tail out of bounds
2809 assert_eq!(tester.capacity(), cap);
2810 assert!(tester.tail < tester.cap());
2811 assert!(tester.head < tester.cap());
2813 // We should see the correct values in the VecDeque
2814 let expected: VecDeque<_> = (0..drain_start)
2815 .chain(drain_end..len)
2817 assert_eq!(expected, tester);
2825 fn test_shrink_to_fit() {
2826 // This test checks that every single combination of head and tail position,
2827 // is tested. Capacity 15 should be large enough to cover every case.
2829 let mut tester = VecDeque::with_capacity(15);
2830 // can't guarantee we got 15, so have to get what we got.
2831 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2832 // this test isn't covering what it wants to
2833 let cap = tester.capacity();
2835 let max_cap = tester.capacity();
2837 for len in 0..cap + 1 {
2838 // 0, 1, 2, .., len - 1
2839 let expected = (0..).take(len).collect::<VecDeque<_>>();
2840 for tail_pos in 0..max_cap + 1 {
2841 tester.tail = tail_pos;
2842 tester.head = tail_pos;
2845 tester.push_back(i);
2847 tester.shrink_to_fit();
2848 assert!(tester.capacity() <= cap);
2849 assert!(tester.tail < tester.cap());
2850 assert!(tester.head < tester.cap());
2851 assert_eq!(tester, expected);
2857 fn test_split_off() {
2858 // This test checks that every single combination of tail position, length, and
2859 // split position is tested. Capacity 15 should be large enough to cover every case.
2861 let mut tester = VecDeque::with_capacity(15);
2862 // can't guarantee we got 15, so have to get what we got.
2863 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2864 // this test isn't covering what it wants to
2865 let cap = tester.capacity();
2867 // len is the length *before* splitting
2869 // index to split at
2870 for at in 0..len + 1 {
2871 // 0, 1, 2, .., at - 1 (may be empty)
2872 let expected_self = (0..).take(at).collect::<VecDeque<_>>();
2873 // at, at + 1, .., len - 1 (may be empty)
2874 let expected_other = (at..).take(len - at).collect::<VecDeque<_>>();
2876 for tail_pos in 0..cap {
2877 tester.tail = tail_pos;
2878 tester.head = tail_pos;
2880 tester.push_back(i);
2882 let result = tester.split_off(at);
2883 assert!(tester.tail < tester.cap());
2884 assert!(tester.head < tester.cap());
2885 assert!(result.tail < result.cap());
2886 assert!(result.head < result.cap());
2887 assert_eq!(tester, expected_self);
2888 assert_eq!(result, expected_other);
2895 fn test_from_vec() {
2898 for len in 0..cap + 1 {
2899 let mut vec = Vec::with_capacity(cap);
2902 let vd = VecDeque::from(vec.clone());
2903 assert!(vd.cap().is_power_of_two());
2904 assert_eq!(vd.len(), vec.len());
2905 assert!(vd.into_iter().eq(vec));
2911 fn test_vec_from_vecdeque() {
2914 fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
2915 let mut vd = VecDeque::with_capacity(cap);
2916 for _ in 0..offset {
2922 let vec: Vec<_> = Vec::from(vd.clone());
2923 assert_eq!(vec.len(), vd.len());
2924 assert!(vec.into_iter().eq(vd));
2927 for cap_pwr in 0..7 {
2928 // Make capacity as a (2^x)-1, so that the ring size is 2^x
2929 let cap = (2i32.pow(cap_pwr) - 1) as usize;
2931 // In these cases there is enough free space to solve it with copies
2932 for len in 0..((cap + 1) / 2) {
2933 // Test contiguous cases
2934 for offset in 0..(cap - len) {
2935 create_vec_and_test_convert(cap, offset, len)
2938 // Test cases where block at end of buffer is bigger than block at start
2939 for offset in (cap - len)..(cap - (len / 2)) {
2940 create_vec_and_test_convert(cap, offset, len)
2943 // Test cases where block at start of buffer is bigger than block at end
2944 for offset in (cap - (len / 2))..cap {
2945 create_vec_and_test_convert(cap, offset, len)
2949 // Now there's not (necessarily) space to straighten the ring with simple copies,
2950 // the ring will use swapping when:
2951 // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
2952 // right block size > free space && left block size > free space
2953 for len in ((cap + 1) / 2)..cap {
2954 // Test contiguous cases
2955 for offset in 0..(cap - len) {
2956 create_vec_and_test_convert(cap, offset, len)
2959 // Test cases where block at end of buffer is bigger than block at start
2960 for offset in (cap - len)..(cap - (len / 2)) {
2961 create_vec_and_test_convert(cap, offset, len)
2964 // Test cases where block at start of buffer is bigger than block at end
2965 for offset in (cap - (len / 2))..cap {
2966 create_vec_and_test_convert(cap, offset, len)
2976 let mut dst = VecDeque::new();
2977 dst.push_front(Box::new(1));
2978 dst.push_front(Box::new(2));
2979 assert_eq!(*dst.pop_back().unwrap(), 1);
2981 let mut src = VecDeque::new();
2982 src.push_front(Box::new(2));
2983 dst.append(&mut src);