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::{Index, IndexMut, Place, Placer, InPlace};
26 use core::ptr::Shared;
29 use core::hash::{Hash, Hasher};
34 use super::range::RangeArgument;
35 use Bound::{Excluded, Included, Unbounded};
38 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
39 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
40 #[cfg(target_pointer_width = "32")]
41 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
42 #[cfg(target_pointer_width = "64")]
43 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
45 /// A double-ended queue implemented with a growable ring buffer.
47 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
48 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
49 /// push onto the back in this manner, and iterating over `VecDeque` goes front
52 /// [`push_back`]: #method.push_back
53 /// [`pop_front`]: #method.pop_front
54 /// [`extend`]: #method.extend
55 /// [`append`]: #method.append
56 #[stable(feature = "rust1", since = "1.0.0")]
57 pub struct VecDeque<T> {
58 // tail and head are pointers into the buffer. Tail always points
59 // to the first element that could be read, Head always points
60 // to where data should be written.
61 // If tail == head the buffer is empty. The length of the ringbuffer
62 // is defined as the distance between the two.
68 #[stable(feature = "rust1", since = "1.0.0")]
69 impl<T: Clone> Clone for VecDeque<T> {
70 fn clone(&self) -> VecDeque<T> {
71 self.iter().cloned().collect()
75 #[stable(feature = "rust1", since = "1.0.0")]
76 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
78 let (front, back) = self.as_mut_slices();
81 ptr::drop_in_place(front);
82 ptr::drop_in_place(back);
84 // RawVec handles deallocation
88 #[stable(feature = "rust1", since = "1.0.0")]
89 impl<T> Default for VecDeque<T> {
90 /// Creates an empty `VecDeque<T>`.
92 fn default() -> VecDeque<T> {
98 /// Marginally more convenient
100 fn ptr(&self) -> *mut T {
104 /// Marginally more convenient
106 fn cap(&self) -> usize {
107 if mem::size_of::<T>() == 0 {
108 // For zero sized types, we are always at maximum capacity
115 /// Turn ptr into a slice
117 unsafe fn buffer_as_slice(&self) -> &[T] {
118 slice::from_raw_parts(self.ptr(), self.cap())
121 /// Turn ptr into a mut slice
123 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
124 slice::from_raw_parts_mut(self.ptr(), self.cap())
127 /// Moves an element out of the buffer
129 unsafe fn buffer_read(&mut self, off: usize) -> T {
130 ptr::read(self.ptr().offset(off as isize))
133 /// Writes an element into the buffer, moving it.
135 unsafe fn buffer_write(&mut self, off: usize, value: T) {
136 ptr::write(self.ptr().offset(off as isize), value);
139 /// Returns `true` if and only if the buffer is at full capacity.
141 fn is_full(&self) -> bool {
142 self.cap() - self.len() == 1
145 /// Returns the index in the underlying buffer for a given logical element
148 fn wrap_index(&self, idx: usize) -> usize {
149 wrap_index(idx, self.cap())
152 /// Returns the index in the underlying buffer for a given logical element
155 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
156 wrap_index(idx.wrapping_add(addend), self.cap())
159 /// Returns the index in the underlying buffer for a given logical element
160 /// index - subtrahend.
162 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
163 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
166 /// Copies a contiguous block of memory len long from src to dst
168 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
169 debug_assert!(dst + len <= self.cap(),
170 "cpy dst={} src={} len={} cap={}",
175 debug_assert!(src + len <= self.cap(),
176 "cpy dst={} src={} len={} cap={}",
181 ptr::copy(self.ptr().offset(src as isize),
182 self.ptr().offset(dst as isize),
186 /// Copies a contiguous block of memory len long from src to dst
188 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
189 debug_assert!(dst + len <= self.cap(),
190 "cno dst={} src={} len={} cap={}",
195 debug_assert!(src + len <= self.cap(),
196 "cno dst={} src={} len={} cap={}",
201 ptr::copy_nonoverlapping(self.ptr().offset(src as isize),
202 self.ptr().offset(dst as isize),
206 /// Copies a potentially wrapping block of memory len long from src to dest.
207 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
208 /// most one continuous overlapping region between src and dest).
209 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
211 fn diff(a: usize, b: usize) -> usize {
212 if a <= b { b - a } else { a - b }
214 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
215 "wrc dst={} src={} len={} cap={}",
221 if src == dst || len == 0 {
225 let dst_after_src = self.wrap_sub(dst, src) < len;
227 let src_pre_wrap_len = self.cap() - src;
228 let dst_pre_wrap_len = self.cap() - dst;
229 let src_wraps = src_pre_wrap_len < len;
230 let dst_wraps = dst_pre_wrap_len < len;
232 match (dst_after_src, src_wraps, dst_wraps) {
233 (_, false, false) => {
234 // src doesn't wrap, dst doesn't wrap
237 // 1 [_ _ A A B B C C _]
238 // 2 [_ _ A A A A B B _]
241 self.copy(dst, src, len);
243 (false, false, true) => {
244 // dst before src, src doesn't wrap, dst wraps
247 // 1 [A A B B _ _ _ C C]
248 // 2 [A A B B _ _ _ A A]
249 // 3 [B B B B _ _ _ A A]
252 self.copy(dst, src, dst_pre_wrap_len);
253 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
255 (true, false, true) => {
256 // src before dst, src doesn't wrap, dst wraps
259 // 1 [C C _ _ _ A A B B]
260 // 2 [B B _ _ _ A A B B]
261 // 3 [B B _ _ _ A A A A]
264 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
265 self.copy(dst, src, dst_pre_wrap_len);
267 (false, true, false) => {
268 // dst before src, src wraps, dst doesn't wrap
271 // 1 [C C _ _ _ A A B B]
272 // 2 [C C _ _ _ B B B B]
273 // 3 [C C _ _ _ B B C C]
276 self.copy(dst, src, src_pre_wrap_len);
277 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
279 (true, true, false) => {
280 // src before dst, src wraps, dst doesn't wrap
283 // 1 [A A B B _ _ _ C C]
284 // 2 [A A A A _ _ _ C C]
285 // 3 [C C A A _ _ _ C C]
288 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
289 self.copy(dst, src, src_pre_wrap_len);
291 (false, true, true) => {
292 // dst before src, src wraps, dst wraps
295 // 1 [A B C D _ E F G H]
296 // 2 [A B C D _ E G H H]
297 // 3 [A B C D _ E G H A]
298 // 4 [B C C D _ E G H A]
301 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
302 let delta = dst_pre_wrap_len - src_pre_wrap_len;
303 self.copy(dst, src, src_pre_wrap_len);
304 self.copy(dst + src_pre_wrap_len, 0, delta);
305 self.copy(0, delta, len - dst_pre_wrap_len);
307 (true, true, true) => {
308 // src before dst, src wraps, dst wraps
311 // 1 [A B C D _ E F G H]
312 // 2 [A A B D _ E F G H]
313 // 3 [H A B D _ E F G H]
314 // 4 [H A B D _ E F F G]
317 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
318 let delta = src_pre_wrap_len - dst_pre_wrap_len;
319 self.copy(delta, 0, len - src_pre_wrap_len);
320 self.copy(0, self.cap() - delta, delta);
321 self.copy(dst, src, dst_pre_wrap_len);
326 /// Frobs the head and tail sections around to handle the fact that we
327 /// just reallocated. Unsafe because it trusts old_cap.
329 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
330 let new_cap = self.cap();
332 // Move the shortest contiguous section of the ring buffer
334 // [o o o o o o o . ]
336 // A [o o o o o o o . . . . . . . . . ]
338 // [o o . o o o o o ]
340 // B [. . . o o o o o o o . . . . . . ]
342 // [o o o o o . o o ]
344 // C [o o o o o . . . . . . . . . o o ]
346 if self.tail <= self.head {
349 } else if self.head < old_cap - self.tail {
351 self.copy_nonoverlapping(old_cap, 0, self.head);
352 self.head += old_cap;
353 debug_assert!(self.head > self.tail);
356 let new_tail = new_cap - (old_cap - self.tail);
357 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
358 self.tail = new_tail;
359 debug_assert!(self.head < self.tail);
361 debug_assert!(self.head < self.cap());
362 debug_assert!(self.tail < self.cap());
363 debug_assert!(self.cap().count_ones() == 1);
367 impl<T> VecDeque<T> {
368 /// Creates an empty `VecDeque`.
373 /// use std::collections::VecDeque;
375 /// let vector: VecDeque<u32> = VecDeque::new();
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn new() -> VecDeque<T> {
379 VecDeque::with_capacity(INITIAL_CAPACITY)
382 /// Creates an empty `VecDeque` with space for at least `n` elements.
387 /// use std::collections::VecDeque;
389 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
391 #[stable(feature = "rust1", since = "1.0.0")]
392 pub fn with_capacity(n: usize) -> VecDeque<T> {
393 // +1 since the ringbuffer always leaves one space empty
394 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
395 assert!(cap > n, "capacity overflow");
400 buf: RawVec::with_capacity(cap),
404 /// Retrieves an element in the `VecDeque` by index.
406 /// Element at index 0 is the front of the queue.
411 /// use std::collections::VecDeque;
413 /// let mut buf = VecDeque::new();
414 /// buf.push_back(3);
415 /// buf.push_back(4);
416 /// buf.push_back(5);
417 /// assert_eq!(buf.get(1), Some(&4));
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn get(&self, index: usize) -> Option<&T> {
421 if index < self.len() {
422 let idx = self.wrap_add(self.tail, index);
423 unsafe { Some(&*self.ptr().offset(idx as isize)) }
429 /// Retrieves an element in the `VecDeque` mutably by index.
431 /// Element at index 0 is the front of the queue.
436 /// use std::collections::VecDeque;
438 /// let mut buf = VecDeque::new();
439 /// buf.push_back(3);
440 /// buf.push_back(4);
441 /// buf.push_back(5);
442 /// if let Some(elem) = buf.get_mut(1) {
446 /// assert_eq!(buf[1], 7);
448 #[stable(feature = "rust1", since = "1.0.0")]
449 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
450 if index < self.len() {
451 let idx = self.wrap_add(self.tail, index);
452 unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
458 /// Swaps elements at indices `i` and `j`.
460 /// `i` and `j` may be equal.
462 /// Fails if there is no element with either index.
464 /// Element at index 0 is the front of the queue.
469 /// use std::collections::VecDeque;
471 /// let mut buf = VecDeque::new();
472 /// buf.push_back(3);
473 /// buf.push_back(4);
474 /// buf.push_back(5);
475 /// assert_eq!(buf, [3, 4, 5]);
477 /// assert_eq!(buf, [5, 4, 3]);
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn swap(&mut self, i: usize, j: usize) {
481 assert!(i < self.len());
482 assert!(j < self.len());
483 let ri = self.wrap_add(self.tail, i);
484 let rj = self.wrap_add(self.tail, j);
486 ptr::swap(self.ptr().offset(ri as isize),
487 self.ptr().offset(rj as isize))
491 /// Returns the number of elements the `VecDeque` can hold without
497 /// use std::collections::VecDeque;
499 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
500 /// assert!(buf.capacity() >= 10);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn capacity(&self) -> usize {
508 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
509 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
511 /// Note that the allocator may give the collection more space than it requests. Therefore
512 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
513 /// insertions are expected.
517 /// Panics if the new capacity overflows `usize`.
522 /// use std::collections::VecDeque;
524 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
525 /// buf.reserve_exact(10);
526 /// assert!(buf.capacity() >= 11);
529 /// [`reserve`]: #method.reserve
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn reserve_exact(&mut self, additional: usize) {
532 self.reserve(additional);
535 /// Reserves capacity for at least `additional` more elements to be inserted in the given
536 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
540 /// Panics if the new capacity overflows `usize`.
545 /// use std::collections::VecDeque;
547 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
549 /// assert!(buf.capacity() >= 11);
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn reserve(&mut self, additional: usize) {
553 let old_cap = self.cap();
554 let used_cap = self.len() + 1;
555 let new_cap = used_cap.checked_add(additional)
556 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
557 .expect("capacity overflow");
559 if new_cap > self.capacity() {
560 self.buf.reserve_exact(used_cap, new_cap - used_cap);
562 self.handle_cap_increase(old_cap);
567 /// Shrinks the capacity of the `VecDeque` as much as possible.
569 /// It will drop down as close as possible to the length but the allocator may still inform the
570 /// `VecDeque` that there is space for a few more elements.
575 /// use std::collections::VecDeque;
577 /// let mut buf = VecDeque::with_capacity(15);
578 /// buf.extend(0..4);
579 /// assert_eq!(buf.capacity(), 15);
580 /// buf.shrink_to_fit();
581 /// assert!(buf.capacity() >= 4);
583 #[stable(feature = "deque_extras_15", since = "1.5.0")]
584 pub fn shrink_to_fit(&mut self) {
585 // +1 since the ringbuffer always leaves one space empty
586 // len + 1 can't overflow for an existing, well-formed ringbuffer.
587 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
588 if target_cap < self.cap() {
589 // There are three cases of interest:
590 // All elements are out of desired bounds
591 // Elements are contiguous, and head is out of desired bounds
592 // Elements are discontiguous, and tail is out of desired bounds
594 // At all other times, element positions are unaffected.
596 // Indicates that elements at the head should be moved.
597 let head_outside = self.head == 0 || self.head >= target_cap;
598 // Move elements from out of desired bounds (positions after target_cap)
599 if self.tail >= target_cap && head_outside {
601 // [. . . . . . . . o o o o o o o . ]
603 // [o o o o o o o . ]
605 self.copy_nonoverlapping(0, self.tail, self.len());
607 self.head = self.len();
609 } else if self.tail != 0 && self.tail < target_cap && head_outside {
611 // [. . . o o o o o o o . . . . . . ]
613 // [o o . o o o o o ]
614 let len = self.wrap_sub(self.head, target_cap);
616 self.copy_nonoverlapping(0, target_cap, len);
619 debug_assert!(self.head < self.tail);
620 } else if self.tail >= target_cap {
622 // [o o o o o . . . . . . . . . o o ]
624 // [o o o o o . o o ]
625 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
626 let len = self.cap() - self.tail;
627 let new_tail = target_cap - len;
629 self.copy_nonoverlapping(new_tail, self.tail, len);
631 self.tail = new_tail;
632 debug_assert!(self.head < self.tail);
635 self.buf.shrink_to_fit(target_cap);
637 debug_assert!(self.head < self.cap());
638 debug_assert!(self.tail < self.cap());
639 debug_assert!(self.cap().count_ones() == 1);
643 /// Shortens the `VecDeque`, dropping excess elements from the back.
645 /// If `len` is greater than the `VecDeque`'s current length, this has no
651 /// use std::collections::VecDeque;
653 /// let mut buf = VecDeque::new();
654 /// buf.push_back(5);
655 /// buf.push_back(10);
656 /// buf.push_back(15);
657 /// assert_eq!(buf, [5, 10, 15]);
659 /// assert_eq!(buf, [5]);
661 #[stable(feature = "deque_extras", since = "1.16.0")]
662 pub fn truncate(&mut self, len: usize) {
663 for _ in len..self.len() {
668 /// Returns a front-to-back iterator.
673 /// use std::collections::VecDeque;
675 /// let mut buf = VecDeque::new();
676 /// buf.push_back(5);
677 /// buf.push_back(3);
678 /// buf.push_back(4);
679 /// let b: &[_] = &[&5, &3, &4];
680 /// let c: Vec<&i32> = buf.iter().collect();
681 /// assert_eq!(&c[..], b);
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn iter(&self) -> Iter<T> {
688 ring: unsafe { self.buffer_as_slice() },
692 /// Returns a front-to-back iterator that returns mutable references.
697 /// use std::collections::VecDeque;
699 /// let mut buf = VecDeque::new();
700 /// buf.push_back(5);
701 /// buf.push_back(3);
702 /// buf.push_back(4);
703 /// for num in buf.iter_mut() {
706 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
707 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
709 #[stable(feature = "rust1", since = "1.0.0")]
710 pub fn iter_mut(&mut self) -> IterMut<T> {
714 ring: unsafe { self.buffer_as_mut_slice() },
718 /// Returns a pair of slices which contain, in order, the contents of the
724 /// use std::collections::VecDeque;
726 /// let mut vector = VecDeque::new();
728 /// vector.push_back(0);
729 /// vector.push_back(1);
730 /// vector.push_back(2);
732 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
734 /// vector.push_front(10);
735 /// vector.push_front(9);
737 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
740 #[stable(feature = "deque_extras_15", since = "1.5.0")]
741 pub fn as_slices(&self) -> (&[T], &[T]) {
743 let buf = self.buffer_as_slice();
744 RingSlices::ring_slices(buf, self.head, self.tail)
748 /// Returns a pair of slices which contain, in order, the contents of the
754 /// use std::collections::VecDeque;
756 /// let mut vector = VecDeque::new();
758 /// vector.push_back(0);
759 /// vector.push_back(1);
761 /// vector.push_front(10);
762 /// vector.push_front(9);
764 /// vector.as_mut_slices().0[0] = 42;
765 /// vector.as_mut_slices().1[0] = 24;
766 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
769 #[stable(feature = "deque_extras_15", since = "1.5.0")]
770 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
772 let head = self.head;
773 let tail = self.tail;
774 let buf = self.buffer_as_mut_slice();
775 RingSlices::ring_slices(buf, head, tail)
779 /// Returns the number of elements in the `VecDeque`.
784 /// use std::collections::VecDeque;
786 /// let mut v = VecDeque::new();
787 /// assert_eq!(v.len(), 0);
789 /// assert_eq!(v.len(), 1);
791 #[stable(feature = "rust1", since = "1.0.0")]
792 pub fn len(&self) -> usize {
793 count(self.tail, self.head, self.cap())
796 /// Returns `true` if the `VecDeque` is empty.
801 /// use std::collections::VecDeque;
803 /// let mut v = VecDeque::new();
804 /// assert!(v.is_empty());
806 /// assert!(!v.is_empty());
808 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn is_empty(&self) -> bool {
810 self.tail == self.head
813 /// Create a draining iterator that removes the specified range in the
814 /// `VecDeque` and yields the removed items.
816 /// Note 1: The element range is removed even if the iterator is not
817 /// consumed until the end.
819 /// Note 2: It is unspecified how many elements are removed from the deque,
820 /// if the `Drain` value is not dropped, but the borrow it holds expires
821 /// (eg. due to mem::forget).
825 /// Panics if the starting point is greater than the end point or if
826 /// the end point is greater than the length of the vector.
831 /// use std::collections::VecDeque;
833 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
834 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
835 /// assert_eq!(drained, [3]);
836 /// assert_eq!(v, [1, 2]);
838 /// // A full range clears all contents
840 /// assert!(v.is_empty());
843 #[stable(feature = "drain", since = "1.6.0")]
844 pub fn drain<R>(&mut self, range: R) -> Drain<T>
845 where R: RangeArgument<usize>
849 // When the Drain is first created, the source deque is shortened to
850 // make sure no uninitialized or moved-from elements are accessible at
851 // all if the Drain's destructor never gets to run.
853 // Drain will ptr::read out the values to remove.
854 // When finished, the remaining data will be copied back to cover the hole,
855 // and the head/tail values will be restored correctly.
857 let len = self.len();
858 let start = match range.start() {
860 Excluded(&n) => n + 1,
863 let end = match range.end() {
864 Included(&n) => n + 1,
868 assert!(start <= end, "drain lower bound was too large");
869 assert!(end <= len, "drain upper bound was too large");
871 // The deque's elements are parted into three segments:
872 // * self.tail -> drain_tail
873 // * drain_tail -> drain_head
874 // * drain_head -> self.head
876 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
878 // We store drain_tail as self.head, and drain_head and self.head as
879 // after_tail and after_head respectively on the Drain. This also
880 // truncates the effective array such that if the Drain is leaked, we
881 // have forgotten about the potentially moved values after the start of
885 // [. . . o o x x o o . . .]
887 let drain_tail = self.wrap_add(self.tail, start);
888 let drain_head = self.wrap_add(self.tail, end);
889 let head = self.head;
891 // "forget" about the values after the start of the drain until after
892 // the drain is complete and the Drain destructor is run.
893 self.head = drain_tail;
896 deque: Shared::from(&mut *self),
897 after_tail: drain_head,
902 ring: unsafe { self.buffer_as_mut_slice() },
907 /// Clears the buffer, removing all values.
912 /// use std::collections::VecDeque;
914 /// let mut v = VecDeque::new();
917 /// assert!(v.is_empty());
919 #[stable(feature = "rust1", since = "1.0.0")]
921 pub fn clear(&mut self) {
925 /// Returns `true` if the `VecDeque` contains an element equal to the
931 /// use std::collections::VecDeque;
933 /// let mut vector: VecDeque<u32> = VecDeque::new();
935 /// vector.push_back(0);
936 /// vector.push_back(1);
938 /// assert_eq!(vector.contains(&1), true);
939 /// assert_eq!(vector.contains(&10), false);
941 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
942 pub fn contains(&self, x: &T) -> bool
943 where T: PartialEq<T>
945 let (a, b) = self.as_slices();
946 a.contains(x) || b.contains(x)
949 /// Provides a reference to the front element, or `None` if the `VecDeque` is
955 /// use std::collections::VecDeque;
957 /// let mut d = VecDeque::new();
958 /// assert_eq!(d.front(), None);
962 /// assert_eq!(d.front(), Some(&1));
964 #[stable(feature = "rust1", since = "1.0.0")]
965 pub fn front(&self) -> Option<&T> {
966 if !self.is_empty() {
973 /// Provides a mutable reference to the front element, or `None` if the
974 /// `VecDeque` is empty.
979 /// use std::collections::VecDeque;
981 /// let mut d = VecDeque::new();
982 /// assert_eq!(d.front_mut(), None);
986 /// match d.front_mut() {
987 /// Some(x) => *x = 9,
990 /// assert_eq!(d.front(), Some(&9));
992 #[stable(feature = "rust1", since = "1.0.0")]
993 pub fn front_mut(&mut self) -> Option<&mut T> {
994 if !self.is_empty() {
1001 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1007 /// use std::collections::VecDeque;
1009 /// let mut d = VecDeque::new();
1010 /// assert_eq!(d.back(), None);
1014 /// assert_eq!(d.back(), Some(&2));
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 pub fn back(&self) -> Option<&T> {
1018 if !self.is_empty() {
1019 Some(&self[self.len() - 1])
1025 /// Provides a mutable reference to the back element, or `None` if the
1026 /// `VecDeque` is empty.
1031 /// use std::collections::VecDeque;
1033 /// let mut d = VecDeque::new();
1034 /// assert_eq!(d.back(), None);
1038 /// match d.back_mut() {
1039 /// Some(x) => *x = 9,
1042 /// assert_eq!(d.back(), Some(&9));
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 pub fn back_mut(&mut self) -> Option<&mut T> {
1046 let len = self.len();
1047 if !self.is_empty() {
1048 Some(&mut self[len - 1])
1054 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1060 /// use std::collections::VecDeque;
1062 /// let mut d = VecDeque::new();
1066 /// assert_eq!(d.pop_front(), Some(1));
1067 /// assert_eq!(d.pop_front(), Some(2));
1068 /// assert_eq!(d.pop_front(), None);
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 pub fn pop_front(&mut self) -> Option<T> {
1072 if self.is_empty() {
1075 let tail = self.tail;
1076 self.tail = self.wrap_add(self.tail, 1);
1077 unsafe { Some(self.buffer_read(tail)) }
1081 /// Prepends an element to the `VecDeque`.
1086 /// use std::collections::VecDeque;
1088 /// let mut d = VecDeque::new();
1089 /// d.push_front(1);
1090 /// d.push_front(2);
1091 /// assert_eq!(d.front(), Some(&2));
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 pub fn push_front(&mut self, value: T) {
1095 self.grow_if_necessary();
1097 self.tail = self.wrap_sub(self.tail, 1);
1098 let tail = self.tail;
1100 self.buffer_write(tail, value);
1104 /// Appends an element to the back of the `VecDeque`.
1109 /// use std::collections::VecDeque;
1111 /// let mut buf = VecDeque::new();
1112 /// buf.push_back(1);
1113 /// buf.push_back(3);
1114 /// assert_eq!(3, *buf.back().unwrap());
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 pub fn push_back(&mut self, value: T) {
1118 self.grow_if_necessary();
1120 let head = self.head;
1121 self.head = self.wrap_add(self.head, 1);
1122 unsafe { self.buffer_write(head, value) }
1125 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1131 /// use std::collections::VecDeque;
1133 /// let mut buf = VecDeque::new();
1134 /// assert_eq!(buf.pop_back(), None);
1135 /// buf.push_back(1);
1136 /// buf.push_back(3);
1137 /// assert_eq!(buf.pop_back(), Some(3));
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub fn pop_back(&mut self) -> Option<T> {
1141 if self.is_empty() {
1144 self.head = self.wrap_sub(self.head, 1);
1145 let head = self.head;
1146 unsafe { Some(self.buffer_read(head)) }
1151 fn is_contiguous(&self) -> bool {
1152 self.tail <= self.head
1155 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1158 /// This does not preserve ordering, but is O(1).
1160 /// Returns `None` if `index` is out of bounds.
1162 /// Element at index 0 is the front of the queue.
1167 /// use std::collections::VecDeque;
1169 /// let mut buf = VecDeque::new();
1170 /// assert_eq!(buf.swap_remove_back(0), None);
1171 /// buf.push_back(1);
1172 /// buf.push_back(2);
1173 /// buf.push_back(3);
1174 /// assert_eq!(buf, [1, 2, 3]);
1176 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1177 /// assert_eq!(buf, [3, 2]);
1179 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1180 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1181 let length = self.len();
1182 if length > 0 && index < length - 1 {
1183 self.swap(index, length - 1);
1184 } else if index >= length {
1190 /// Removes an element from anywhere in the `VecDeque` and returns it,
1191 /// replacing it with the first element.
1193 /// This does not preserve ordering, but is O(1).
1195 /// Returns `None` if `index` is out of bounds.
1197 /// Element at index 0 is the front of the queue.
1202 /// use std::collections::VecDeque;
1204 /// let mut buf = VecDeque::new();
1205 /// assert_eq!(buf.swap_remove_front(0), None);
1206 /// buf.push_back(1);
1207 /// buf.push_back(2);
1208 /// buf.push_back(3);
1209 /// assert_eq!(buf, [1, 2, 3]);
1211 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1212 /// assert_eq!(buf, [2, 1]);
1214 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1215 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1216 let length = self.len();
1217 if length > 0 && index < length && index != 0 {
1218 self.swap(index, 0);
1219 } else if index >= length {
1225 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1226 /// greater than or equal to `index` towards the back.
1228 /// Element at index 0 is the front of the queue.
1232 /// Panics if `index` is greater than `VecDeque`'s length
1237 /// use std::collections::VecDeque;
1239 /// let mut vec_deque = VecDeque::new();
1240 /// vec_deque.push_back('a');
1241 /// vec_deque.push_back('b');
1242 /// vec_deque.push_back('c');
1243 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1245 /// vec_deque.insert(1, 'd');
1246 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1248 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1249 pub fn insert(&mut self, index: usize, value: T) {
1250 assert!(index <= self.len(), "index out of bounds");
1251 self.grow_if_necessary();
1253 // Move the least number of elements in the ring buffer and insert
1256 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1258 // There are three main cases:
1259 // Elements are contiguous
1260 // - special case when tail is 0
1261 // Elements are discontiguous and the insert is in the tail section
1262 // Elements are discontiguous and the insert is in the head section
1264 // For each of those there are two more cases:
1265 // Insert is closer to tail
1266 // Insert is closer to head
1268 // Key: H - self.head
1270 // o - Valid element
1271 // I - Insertion element
1272 // A - The element that should be after the insertion point
1273 // M - Indicates element was moved
1275 let idx = self.wrap_add(self.tail, index);
1277 let distance_to_tail = index;
1278 let distance_to_head = self.len() - index;
1280 let contiguous = self.is_contiguous();
1282 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1283 (true, true, _) if index == 0 => {
1288 // [A o o o o o o . . . . . . . . .]
1291 // [A o o o o o o o . . . . . I]
1294 self.tail = self.wrap_sub(self.tail, 1);
1296 (true, true, _) => {
1298 // contiguous, insert closer to tail:
1301 // [. . . o o A o o o o . . . . . .]
1304 // [. . o o I A o o o o . . . . . .]
1307 // contiguous, insert closer to tail and tail is 0:
1311 // [o o A o o o o . . . . . . . . .]
1314 // [o I A o o o o o . . . . . . . o]
1317 let new_tail = self.wrap_sub(self.tail, 1);
1319 self.copy(new_tail, self.tail, 1);
1320 // Already moved the tail, so we only copy `index - 1` elements.
1321 self.copy(self.tail, self.tail + 1, index - 1);
1323 self.tail = new_tail;
1326 (true, false, _) => {
1328 // contiguous, insert closer to head:
1331 // [. . . o o o o A o o . . . . . .]
1334 // [. . . o o o o I A o o . . . . .]
1337 self.copy(idx + 1, idx, self.head - idx);
1338 self.head = self.wrap_add(self.head, 1);
1341 (false, true, true) => {
1343 // discontiguous, insert closer to tail, tail section:
1346 // [o o o o o o . . . . . o o A o o]
1349 // [o o o o o o . . . . o o I A o o]
1352 self.copy(self.tail - 1, self.tail, index);
1356 (false, false, true) => {
1358 // discontiguous, insert closer to head, tail section:
1361 // [o o . . . . . . . o o o o o A o]
1364 // [o o o . . . . . . o o o o o I A]
1367 // copy elements up to new head
1368 self.copy(1, 0, self.head);
1370 // copy last element into empty spot at bottom of buffer
1371 self.copy(0, self.cap() - 1, 1);
1373 // move elements from idx to end forward not including ^ element
1374 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1379 (false, true, false) if idx == 0 => {
1381 // discontiguous, insert is closer to tail, head section,
1382 // and is at index zero in the internal buffer:
1385 // [A o o o o o o o o o . . . o o o]
1388 // [A o o o o o o o o o . . o o o I]
1391 // copy elements up to new tail
1392 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1394 // copy last element into empty spot at bottom of buffer
1395 self.copy(self.cap() - 1, 0, 1);
1400 (false, true, false) => {
1402 // discontiguous, insert closer to tail, head section:
1405 // [o o o A o o o o o o . . . o o o]
1408 // [o o I A o o o o o o . . o o o o]
1411 // copy elements up to new tail
1412 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1414 // copy last element into empty spot at bottom of buffer
1415 self.copy(self.cap() - 1, 0, 1);
1417 // move elements from idx-1 to end forward not including ^ element
1418 self.copy(0, 1, idx - 1);
1423 (false, false, false) => {
1425 // discontiguous, insert closer to head, head section:
1428 // [o o o o A o o . . . . . . o o o]
1431 // [o o o o I A o o . . . . . o o o]
1434 self.copy(idx + 1, idx, self.head - idx);
1440 // tail might've been changed so we need to recalculate
1441 let new_idx = self.wrap_add(self.tail, index);
1443 self.buffer_write(new_idx, value);
1447 /// Removes and returns the element at `index` from the `VecDeque`.
1448 /// Whichever end is closer to the removal point will be moved to make
1449 /// room, and all the affected elements will be moved to new positions.
1450 /// Returns `None` if `index` is out of bounds.
1452 /// Element at index 0 is the front of the queue.
1457 /// use std::collections::VecDeque;
1459 /// let mut buf = VecDeque::new();
1460 /// buf.push_back(1);
1461 /// buf.push_back(2);
1462 /// buf.push_back(3);
1463 /// assert_eq!(buf, [1, 2, 3]);
1465 /// assert_eq!(buf.remove(1), Some(2));
1466 /// assert_eq!(buf, [1, 3]);
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 pub fn remove(&mut self, index: usize) -> Option<T> {
1470 if self.is_empty() || self.len() <= index {
1474 // There are three main cases:
1475 // Elements are contiguous
1476 // Elements are discontiguous and the removal is in the tail section
1477 // Elements are discontiguous and the removal is in the head section
1478 // - special case when elements are technically contiguous,
1479 // but self.head = 0
1481 // For each of those there are two more cases:
1482 // Insert is closer to tail
1483 // Insert is closer to head
1485 // Key: H - self.head
1487 // o - Valid element
1488 // x - Element marked for removal
1489 // R - Indicates element that is being removed
1490 // M - Indicates element was moved
1492 let idx = self.wrap_add(self.tail, index);
1494 let elem = unsafe { Some(self.buffer_read(idx)) };
1496 let distance_to_tail = index;
1497 let distance_to_head = self.len() - index;
1499 let contiguous = self.is_contiguous();
1501 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1502 (true, true, _) => {
1504 // contiguous, remove closer to tail:
1507 // [. . . o o x o o o o . . . . . .]
1510 // [. . . . o o o o o o . . . . . .]
1513 self.copy(self.tail + 1, self.tail, index);
1517 (true, false, _) => {
1519 // contiguous, remove closer to head:
1522 // [. . . o o o o x o o . . . . . .]
1525 // [. . . o o o o o o . . . . . . .]
1528 self.copy(idx, idx + 1, self.head - idx - 1);
1532 (false, true, true) => {
1534 // discontiguous, remove closer to tail, tail section:
1537 // [o o o o o o . . . . . o o x o o]
1540 // [o o o o o o . . . . . . o o o o]
1543 self.copy(self.tail + 1, self.tail, index);
1544 self.tail = self.wrap_add(self.tail, 1);
1547 (false, false, false) => {
1549 // discontiguous, remove closer to head, head section:
1552 // [o o o o x o o . . . . . . o o o]
1555 // [o o o o o o . . . . . . . o o o]
1558 self.copy(idx, idx + 1, self.head - idx - 1);
1562 (false, false, true) => {
1564 // discontiguous, remove closer to head, tail section:
1567 // [o o o . . . . . . o o o o o x o]
1570 // [o o . . . . . . . o o o o o o o]
1573 // or quasi-discontiguous, remove next to head, tail section:
1576 // [. . . . . . . . . o o o o o x o]
1579 // [. . . . . . . . . o o o o o o .]
1582 // draw in elements in the tail section
1583 self.copy(idx, idx + 1, self.cap() - idx - 1);
1585 // Prevents underflow.
1587 // copy first element into empty spot
1588 self.copy(self.cap() - 1, 0, 1);
1590 // move elements in the head section backwards
1591 self.copy(0, 1, self.head - 1);
1594 self.head = self.wrap_sub(self.head, 1);
1597 (false, true, false) => {
1599 // discontiguous, remove closer to tail, head section:
1602 // [o o x o o o o o o o . . . o o o]
1605 // [o o o o o o o o o o . . . . o o]
1608 // draw in elements up to idx
1609 self.copy(1, 0, idx);
1611 // copy last element into empty spot
1612 self.copy(0, self.cap() - 1, 1);
1614 // move elements from tail to end forward, excluding the last one
1615 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1617 self.tail = self.wrap_add(self.tail, 1);
1625 /// Splits the collection into two at the given index.
1627 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1628 /// and the returned `Self` contains elements `[at, len)`.
1630 /// Note that the capacity of `self` does not change.
1632 /// Element at index 0 is the front of the queue.
1636 /// Panics if `at > len`
1641 /// use std::collections::VecDeque;
1643 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1644 /// let buf2 = buf.split_off(1);
1645 /// assert_eq!(buf, [1]);
1646 /// assert_eq!(buf2, [2, 3]);
1649 #[stable(feature = "split_off", since = "1.4.0")]
1650 pub fn split_off(&mut self, at: usize) -> Self {
1651 let len = self.len();
1652 assert!(at <= len, "`at` out of bounds");
1654 let other_len = len - at;
1655 let mut other = VecDeque::with_capacity(other_len);
1658 let (first_half, second_half) = self.as_slices();
1660 let first_len = first_half.len();
1661 let second_len = second_half.len();
1663 // `at` lies in the first half.
1664 let amount_in_first = first_len - at;
1666 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1670 // just take all of the second half.
1671 ptr::copy_nonoverlapping(second_half.as_ptr(),
1672 other.ptr().offset(amount_in_first as isize),
1675 // `at` lies in the second half, need to factor in the elements we skipped
1676 // in the first half.
1677 let offset = at - first_len;
1678 let amount_in_second = second_len - offset;
1679 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1685 // Cleanup where the ends of the buffers are
1686 self.head = self.wrap_sub(self.head, other_len);
1687 other.head = other.wrap_index(other_len);
1692 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1696 /// Panics if the new number of elements in self overflows a `usize`.
1701 /// use std::collections::VecDeque;
1703 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1704 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1705 /// buf.append(&mut buf2);
1706 /// assert_eq!(buf, [1, 2, 3, 4]);
1707 /// assert_eq!(buf2, []);
1710 #[stable(feature = "append", since = "1.4.0")]
1711 pub fn append(&mut self, other: &mut Self) {
1713 self.extend(other.drain(..));
1716 /// Retains only the elements specified by the predicate.
1718 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1719 /// This method operates in place and preserves the order of the retained
1725 /// use std::collections::VecDeque;
1727 /// let mut buf = VecDeque::new();
1728 /// buf.extend(1..5);
1729 /// buf.retain(|&x| x%2 == 0);
1730 /// assert_eq!(buf, [2, 4]);
1732 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1733 pub fn retain<F>(&mut self, mut f: F)
1734 where F: FnMut(&T) -> bool
1736 let len = self.len();
1742 self.swap(i - del, i);
1746 self.truncate(len - del);
1750 // This may panic or abort
1752 fn grow_if_necessary(&mut self) {
1754 let old_cap = self.cap();
1757 self.handle_cap_increase(old_cap);
1759 debug_assert!(!self.is_full());
1763 /// Returns a place for insertion at the back of the `VecDeque`.
1765 /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back),
1766 /// but may be more efficient.
1771 /// #![feature(collection_placement)]
1772 /// #![feature(placement_in_syntax)]
1774 /// use std::collections::VecDeque;
1776 /// let mut buf = VecDeque::new();
1777 /// buf.place_back() <- 3;
1778 /// buf.place_back() <- 4;
1779 /// assert_eq!(&buf, &[3, 4]);
1781 #[unstable(feature = "collection_placement",
1782 reason = "placement protocol is subject to change",
1784 pub fn place_back(&mut self) -> PlaceBack<T> {
1785 PlaceBack { vec_deque: self }
1788 /// Returns a place for insertion at the front of the `VecDeque`.
1790 /// Using this method with placement syntax is equivalent to [`push_front`](#method.push_front),
1791 /// but may be more efficient.
1796 /// #![feature(collection_placement)]
1797 /// #![feature(placement_in_syntax)]
1799 /// use std::collections::VecDeque;
1801 /// let mut buf = VecDeque::new();
1802 /// buf.place_front() <- 3;
1803 /// buf.place_front() <- 4;
1804 /// assert_eq!(&buf, &[4, 3]);
1806 #[unstable(feature = "collection_placement",
1807 reason = "placement protocol is subject to change",
1809 pub fn place_front(&mut self) -> PlaceFront<T> {
1810 PlaceFront { vec_deque: self }
1814 impl<T: Clone> VecDeque<T> {
1815 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1816 /// either by removing excess elements or by appending clones of `value` to the back.
1821 /// use std::collections::VecDeque;
1823 /// let mut buf = VecDeque::new();
1824 /// buf.push_back(5);
1825 /// buf.push_back(10);
1826 /// buf.push_back(15);
1827 /// assert_eq!(buf, [5, 10, 15]);
1829 /// buf.resize(2, 0);
1830 /// assert_eq!(buf, [5, 10]);
1832 /// buf.resize(5, 20);
1833 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
1835 #[stable(feature = "deque_extras", since = "1.16.0")]
1836 pub fn resize(&mut self, new_len: usize, value: T) {
1837 let len = self.len();
1840 self.extend(repeat(value).take(new_len - len))
1842 self.truncate(new_len);
1847 /// Returns the index in the underlying buffer for a given logical element index.
1849 fn wrap_index(index: usize, size: usize) -> usize {
1850 // size is always a power of 2
1851 debug_assert!(size.is_power_of_two());
1855 /// Returns the two slices that cover the `VecDeque`'s valid range
1856 trait RingSlices: Sized {
1857 fn slice(self, from: usize, to: usize) -> Self;
1858 fn split_at(self, i: usize) -> (Self, Self);
1860 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
1861 let contiguous = tail <= head;
1863 let (empty, buf) = buf.split_at(0);
1864 (buf.slice(tail, head), empty)
1866 let (mid, right) = buf.split_at(tail);
1867 let (left, _) = mid.split_at(head);
1873 impl<'a, T> RingSlices for &'a [T] {
1874 fn slice(self, from: usize, to: usize) -> Self {
1877 fn split_at(self, i: usize) -> (Self, Self) {
1882 impl<'a, T> RingSlices for &'a mut [T] {
1883 fn slice(self, from: usize, to: usize) -> Self {
1886 fn split_at(self, i: usize) -> (Self, Self) {
1887 (*self).split_at_mut(i)
1891 /// Calculate the number of elements left to be read in the buffer
1893 fn count(tail: usize, head: usize, size: usize) -> usize {
1894 // size is always a power of 2
1895 (head.wrapping_sub(tail)) & (size - 1)
1898 /// An iterator over the elements of a `VecDeque`.
1900 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
1901 /// documentation for more.
1903 /// [`iter`]: struct.VecDeque.html#method.iter
1904 /// [`VecDeque`]: struct.VecDeque.html
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 pub struct Iter<'a, T: 'a> {
1912 #[stable(feature = "collection_debug", since = "1.17.0")]
1913 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1914 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1915 f.debug_tuple("Iter")
1923 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 impl<'a, T> Clone for Iter<'a, T> {
1926 fn clone(&self) -> Iter<'a, T> {
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 impl<'a, T> Iterator for Iter<'a, T> {
1940 fn next(&mut self) -> Option<&'a T> {
1941 if self.tail == self.head {
1944 let tail = self.tail;
1945 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1946 unsafe { Some(self.ring.get_unchecked(tail)) }
1950 fn size_hint(&self) -> (usize, Option<usize>) {
1951 let len = count(self.tail, self.head, self.ring.len());
1955 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
1956 where F: FnMut(Acc, Self::Item) -> Acc
1958 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
1959 accum = front.iter().fold(accum, &mut f);
1960 back.iter().fold(accum, &mut f)
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1967 fn next_back(&mut self) -> Option<&'a T> {
1968 if self.tail == self.head {
1971 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1972 unsafe { Some(self.ring.get_unchecked(self.head)) }
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1978 fn is_empty(&self) -> bool {
1979 self.head == self.tail
1983 #[unstable(feature = "fused", issue = "35602")]
1984 impl<'a, T> FusedIterator for Iter<'a, T> {}
1987 /// A mutable iterator over the elements of a `VecDeque`.
1989 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
1990 /// documentation for more.
1992 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
1993 /// [`VecDeque`]: struct.VecDeque.html
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 pub struct IterMut<'a, T: 'a> {
2001 #[stable(feature = "collection_debug", since = "1.17.0")]
2002 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2003 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2004 f.debug_tuple("IterMut")
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl<'a, T> Iterator for IterMut<'a, T> {
2014 type Item = &'a mut T;
2017 fn next(&mut self) -> Option<&'a mut T> {
2018 if self.tail == self.head {
2021 let tail = self.tail;
2022 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2025 let elem = self.ring.get_unchecked_mut(tail);
2026 Some(&mut *(elem as *mut _))
2031 fn size_hint(&self) -> (usize, Option<usize>) {
2032 let len = count(self.tail, self.head, self.ring.len());
2036 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2037 where F: FnMut(Acc, Self::Item) -> Acc
2039 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2040 accum = front.iter_mut().fold(accum, &mut f);
2041 back.iter_mut().fold(accum, &mut f)
2045 #[stable(feature = "rust1", since = "1.0.0")]
2046 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2048 fn next_back(&mut self) -> Option<&'a mut T> {
2049 if self.tail == self.head {
2052 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2055 let elem = self.ring.get_unchecked_mut(self.head);
2056 Some(&mut *(elem as *mut _))
2061 #[stable(feature = "rust1", since = "1.0.0")]
2062 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
2063 fn is_empty(&self) -> bool {
2064 self.head == self.tail
2068 #[unstable(feature = "fused", issue = "35602")]
2069 impl<'a, T> FusedIterator for IterMut<'a, T> {}
2071 /// An owning iterator over the elements of a `VecDeque`.
2073 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`][`VecDeque`]
2074 /// (provided by the `IntoIterator` trait). See its documentation for more.
2076 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2077 /// [`VecDeque`]: struct.VecDeque.html
2079 #[stable(feature = "rust1", since = "1.0.0")]
2080 pub struct IntoIter<T> {
2084 #[stable(feature = "collection_debug", since = "1.17.0")]
2085 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2086 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2087 f.debug_tuple("IntoIter")
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 impl<T> Iterator for IntoIter<T> {
2098 fn next(&mut self) -> Option<T> {
2099 self.inner.pop_front()
2103 fn size_hint(&self) -> (usize, Option<usize>) {
2104 let len = self.inner.len();
2109 #[stable(feature = "rust1", since = "1.0.0")]
2110 impl<T> DoubleEndedIterator for IntoIter<T> {
2112 fn next_back(&mut self) -> Option<T> {
2113 self.inner.pop_back()
2117 #[stable(feature = "rust1", since = "1.0.0")]
2118 impl<T> ExactSizeIterator for IntoIter<T> {
2119 fn is_empty(&self) -> bool {
2120 self.inner.is_empty()
2124 #[unstable(feature = "fused", issue = "35602")]
2125 impl<T> FusedIterator for IntoIter<T> {}
2127 /// A draining iterator over the elements of a `VecDeque`.
2129 /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its
2130 /// documentation for more.
2132 /// [`drain`]: struct.VecDeque.html#method.drain
2133 /// [`VecDeque`]: struct.VecDeque.html
2134 #[stable(feature = "drain", since = "1.6.0")]
2135 pub struct Drain<'a, T: 'a> {
2139 deque: Shared<VecDeque<T>>,
2142 #[stable(feature = "collection_debug", since = "1.17.0")]
2143 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2144 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2145 f.debug_tuple("Drain")
2146 .field(&self.after_tail)
2147 .field(&self.after_head)
2153 #[stable(feature = "drain", since = "1.6.0")]
2154 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2155 #[stable(feature = "drain", since = "1.6.0")]
2156 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2158 #[stable(feature = "drain", since = "1.6.0")]
2159 impl<'a, T: 'a> Drop for Drain<'a, T> {
2160 fn drop(&mut self) {
2161 for _ in self.by_ref() {}
2163 let source_deque = unsafe { self.deque.as_mut() };
2165 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2168 // [. . . o o x x o o . . .]
2170 let orig_tail = source_deque.tail;
2171 let drain_tail = source_deque.head;
2172 let drain_head = self.after_tail;
2173 let orig_head = self.after_head;
2175 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2176 let head_len = count(drain_head, orig_head, source_deque.cap());
2178 // Restore the original head value
2179 source_deque.head = orig_head;
2181 match (tail_len, head_len) {
2183 source_deque.head = 0;
2184 source_deque.tail = 0;
2187 source_deque.tail = drain_head;
2190 source_deque.head = drain_tail;
2193 if tail_len <= head_len {
2194 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2195 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2197 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2198 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2205 #[stable(feature = "drain", since = "1.6.0")]
2206 impl<'a, T: 'a> Iterator for Drain<'a, T> {
2210 fn next(&mut self) -> Option<T> {
2211 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2215 fn size_hint(&self) -> (usize, Option<usize>) {
2216 self.iter.size_hint()
2220 #[stable(feature = "drain", since = "1.6.0")]
2221 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
2223 fn next_back(&mut self) -> Option<T> {
2224 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2228 #[stable(feature = "drain", since = "1.6.0")]
2229 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
2231 #[unstable(feature = "fused", issue = "35602")]
2232 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
2234 #[stable(feature = "rust1", since = "1.0.0")]
2235 impl<A: PartialEq> PartialEq for VecDeque<A> {
2236 fn eq(&self, other: &VecDeque<A>) -> bool {
2237 if self.len() != other.len() {
2240 let (sa, sb) = self.as_slices();
2241 let (oa, ob) = other.as_slices();
2242 if sa.len() == oa.len() {
2243 sa == oa && sb == ob
2244 } else if sa.len() < oa.len() {
2245 // Always divisible in three sections, for example:
2246 // self: [a b c|d e f]
2247 // other: [0 1 2 3|4 5]
2248 // front = 3, mid = 1,
2249 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2250 let front = sa.len();
2251 let mid = oa.len() - front;
2253 let (oa_front, oa_mid) = oa.split_at(front);
2254 let (sb_mid, sb_back) = sb.split_at(mid);
2255 debug_assert_eq!(sa.len(), oa_front.len());
2256 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2257 debug_assert_eq!(sb_back.len(), ob.len());
2258 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2260 let front = oa.len();
2261 let mid = sa.len() - front;
2263 let (sa_front, sa_mid) = sa.split_at(front);
2264 let (ob_mid, ob_back) = ob.split_at(mid);
2265 debug_assert_eq!(sa_front.len(), oa.len());
2266 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2267 debug_assert_eq!(sb.len(), ob_back.len());
2268 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2273 #[stable(feature = "rust1", since = "1.0.0")]
2274 impl<A: Eq> Eq for VecDeque<A> {}
2276 macro_rules! __impl_slice_eq1 {
2277 ($Lhs: ty, $Rhs: ty) => {
2278 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2280 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2281 #[stable(feature = "vec-deque-partial-eq-slice", since = "1.17.0")]
2282 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2283 fn eq(&self, other: &$Rhs) -> bool {
2284 if self.len() != other.len() {
2287 let (sa, sb) = self.as_slices();
2288 let (oa, ob) = other[..].split_at(sa.len());
2289 sa == oa && sb == ob
2295 __impl_slice_eq1! { VecDeque<A>, Vec<B> }
2296 __impl_slice_eq1! { VecDeque<A>, &'b [B] }
2297 __impl_slice_eq1! { VecDeque<A>, &'b mut [B] }
2299 macro_rules! array_impls {
2302 __impl_slice_eq1! { VecDeque<A>, [B; $N] }
2303 __impl_slice_eq1! { VecDeque<A>, &'b [B; $N] }
2304 __impl_slice_eq1! { VecDeque<A>, &'b mut [B; $N] }
2311 10 11 12 13 14 15 16 17 18 19
2312 20 21 22 23 24 25 26 27 28 29
2316 #[stable(feature = "rust1", since = "1.0.0")]
2317 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2318 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2319 self.iter().partial_cmp(other.iter())
2323 #[stable(feature = "rust1", since = "1.0.0")]
2324 impl<A: Ord> Ord for VecDeque<A> {
2326 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2327 self.iter().cmp(other.iter())
2331 #[stable(feature = "rust1", since = "1.0.0")]
2332 impl<A: Hash> Hash for VecDeque<A> {
2333 fn hash<H: Hasher>(&self, state: &mut H) {
2334 self.len().hash(state);
2335 let (a, b) = self.as_slices();
2336 Hash::hash_slice(a, state);
2337 Hash::hash_slice(b, state);
2341 #[stable(feature = "rust1", since = "1.0.0")]
2342 impl<A> Index<usize> for VecDeque<A> {
2346 fn index(&self, index: usize) -> &A {
2347 self.get(index).expect("Out of bounds access")
2351 #[stable(feature = "rust1", since = "1.0.0")]
2352 impl<A> IndexMut<usize> for VecDeque<A> {
2354 fn index_mut(&mut self, index: usize) -> &mut A {
2355 self.get_mut(index).expect("Out of bounds access")
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 impl<A> FromIterator<A> for VecDeque<A> {
2361 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2362 let iterator = iter.into_iter();
2363 let (lower, _) = iterator.size_hint();
2364 let mut deq = VecDeque::with_capacity(lower);
2365 deq.extend(iterator);
2370 #[stable(feature = "rust1", since = "1.0.0")]
2371 impl<T> IntoIterator for VecDeque<T> {
2373 type IntoIter = IntoIter<T>;
2375 /// Consumes the list into a front-to-back iterator yielding elements by
2377 fn into_iter(self) -> IntoIter<T> {
2378 IntoIter { inner: self }
2382 #[stable(feature = "rust1", since = "1.0.0")]
2383 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2385 type IntoIter = Iter<'a, T>;
2387 fn into_iter(self) -> Iter<'a, T> {
2392 #[stable(feature = "rust1", since = "1.0.0")]
2393 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2394 type Item = &'a mut T;
2395 type IntoIter = IterMut<'a, T>;
2397 fn into_iter(self) -> IterMut<'a, T> {
2402 #[stable(feature = "rust1", since = "1.0.0")]
2403 impl<A> Extend<A> for VecDeque<A> {
2404 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2406 self.push_back(elt);
2411 #[stable(feature = "extend_ref", since = "1.2.0")]
2412 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2413 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2414 self.extend(iter.into_iter().cloned());
2418 #[stable(feature = "rust1", since = "1.0.0")]
2419 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2420 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2421 f.debug_list().entries(self).finish()
2425 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2426 impl<T> From<Vec<T>> for VecDeque<T> {
2427 fn from(mut other: Vec<T>) -> Self {
2429 let other_buf = other.as_mut_ptr();
2430 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2431 let len = other.len();
2434 // We need to extend the buf if it's not a power of two, too small
2435 // or doesn't have at least one free space
2436 if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) ||
2437 (buf.cap() == len) {
2438 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2439 buf.reserve_exact(len, cap - len);
2451 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2452 impl<T> From<VecDeque<T>> for Vec<T> {
2453 fn from(other: VecDeque<T>) -> Self {
2455 let buf = other.buf.ptr();
2456 let len = other.len();
2457 let tail = other.tail;
2458 let head = other.head;
2459 let cap = other.cap();
2461 // Need to move the ring to the front of the buffer, as vec will expect this.
2462 if other.is_contiguous() {
2463 ptr::copy(buf.offset(tail as isize), buf, len);
2465 if (tail - head) >= cmp::min((cap - tail), head) {
2466 // There is enough free space in the centre for the shortest block so we can
2467 // do this in at most three copy moves.
2468 if (cap - tail) > head {
2469 // right hand block is the long one; move that enough for the left
2470 ptr::copy(buf.offset(tail as isize),
2471 buf.offset((tail - head) as isize),
2473 // copy left in the end
2474 ptr::copy(buf, buf.offset((cap - head) as isize), head);
2475 // shift the new thing to the start
2476 ptr::copy(buf.offset((tail - head) as isize), buf, len);
2478 // left hand block is the long one, we can do it in two!
2479 ptr::copy(buf, buf.offset((cap - tail) as isize), head);
2480 ptr::copy(buf.offset(tail as isize), buf, cap - tail);
2483 // Need to use N swaps to move the ring
2484 // We can use the space at the end of the ring as a temp store
2486 let mut left_edge: usize = 0;
2487 let mut right_edge: usize = tail;
2489 // The general problem looks like this
2490 // GHIJKLM...ABCDEF - before any swaps
2491 // ABCDEFM...GHIJKL - after 1 pass of swaps
2492 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2493 // - then restart the algorithm with a new (smaller) store
2494 // Sometimes the temp store is reached when the right edge is at the end
2495 // of the buffer - this means we've hit the right order with fewer swaps!
2498 // ABCDEF.. - after four only swaps we've finished
2500 while left_edge < len && right_edge != cap {
2501 let mut right_offset = 0;
2502 for i in left_edge..right_edge {
2503 right_offset = (i - left_edge) % (cap - right_edge);
2504 let src: isize = (right_edge + right_offset) as isize;
2505 ptr::swap(buf.offset(i as isize), buf.offset(src));
2507 let n_ops = right_edge - left_edge;
2509 right_edge += right_offset + 1;
2515 let out = Vec::from_raw_parts(buf, len, cap);
2522 /// A place for insertion at the back of a `VecDeque`.
2524 /// See [`VecDeque::place_back`](struct.VecDeque.html#method.place_back) for details.
2525 #[must_use = "places do nothing unless written to with `<-` syntax"]
2526 #[unstable(feature = "collection_placement",
2527 reason = "struct name and placement protocol are subject to change",
2530 pub struct PlaceBack<'a, T: 'a> {
2531 vec_deque: &'a mut VecDeque<T>,
2534 #[unstable(feature = "collection_placement",
2535 reason = "placement protocol is subject to change",
2537 impl<'a, T> Placer<T> for PlaceBack<'a, T> {
2538 type Place = PlaceBack<'a, T>;
2540 fn make_place(self) -> Self {
2541 self.vec_deque.grow_if_necessary();
2546 #[unstable(feature = "collection_placement",
2547 reason = "placement protocol is subject to change",
2549 impl<'a, T> Place<T> for PlaceBack<'a, T> {
2550 fn pointer(&mut self) -> *mut T {
2551 unsafe { self.vec_deque.ptr().offset(self.vec_deque.head as isize) }
2555 #[unstable(feature = "collection_placement",
2556 reason = "placement protocol is subject to change",
2558 impl<'a, T> InPlace<T> for PlaceBack<'a, T> {
2559 type Owner = &'a mut T;
2561 unsafe fn finalize(mut self) -> &'a mut T {
2562 let head = self.vec_deque.head;
2563 self.vec_deque.head = self.vec_deque.wrap_add(head, 1);
2564 &mut *(self.vec_deque.ptr().offset(head as isize))
2568 /// A place for insertion at the front of a `VecDeque`.
2570 /// See [`VecDeque::place_front`](struct.VecDeque.html#method.place_front) for details.
2571 #[must_use = "places do nothing unless written to with `<-` syntax"]
2572 #[unstable(feature = "collection_placement",
2573 reason = "struct name and placement protocol are subject to change",
2576 pub struct PlaceFront<'a, T: 'a> {
2577 vec_deque: &'a mut VecDeque<T>,
2580 #[unstable(feature = "collection_placement",
2581 reason = "placement protocol is subject to change",
2583 impl<'a, T> Placer<T> for PlaceFront<'a, T> {
2584 type Place = PlaceFront<'a, T>;
2586 fn make_place(self) -> Self {
2587 self.vec_deque.grow_if_necessary();
2592 #[unstable(feature = "collection_placement",
2593 reason = "placement protocol is subject to change",
2595 impl<'a, T> Place<T> for PlaceFront<'a, T> {
2596 fn pointer(&mut self) -> *mut T {
2597 let tail = self.vec_deque.wrap_sub(self.vec_deque.tail, 1);
2598 unsafe { self.vec_deque.ptr().offset(tail as isize) }
2602 #[unstable(feature = "collection_placement",
2603 reason = "placement protocol is subject to change",
2605 impl<'a, T> InPlace<T> for PlaceFront<'a, T> {
2606 type Owner = &'a mut T;
2608 unsafe fn finalize(mut self) -> &'a mut T {
2609 self.vec_deque.tail = self.vec_deque.wrap_sub(self.vec_deque.tail, 1);
2610 &mut *(self.vec_deque.ptr().offset(self.vec_deque.tail as isize))
2618 use super::VecDeque;
2621 fn bench_push_back_100(b: &mut test::Bencher) {
2622 let mut deq = VecDeque::with_capacity(101);
2633 fn bench_push_front_100(b: &mut test::Bencher) {
2634 let mut deq = VecDeque::with_capacity(101);
2645 fn bench_pop_back_100(b: &mut test::Bencher) {
2646 let mut deq = VecDeque::<i32>::with_capacity(101);
2651 while !deq.is_empty() {
2652 test::black_box(deq.pop_back());
2658 fn bench_pop_front_100(b: &mut test::Bencher) {
2659 let mut deq = VecDeque::<i32>::with_capacity(101);
2664 while !deq.is_empty() {
2665 test::black_box(deq.pop_front());
2671 fn test_swap_front_back_remove() {
2672 fn test(back: bool) {
2673 // This test checks that every single combination of tail position and length is tested.
2674 // Capacity 15 should be large enough to cover every case.
2675 let mut tester = VecDeque::with_capacity(15);
2676 let usable_cap = tester.capacity();
2677 let final_len = usable_cap / 2;
2679 for len in 0..final_len {
2680 let expected: VecDeque<_> = if back {
2683 (0..len).rev().collect()
2685 for tail_pos in 0..usable_cap {
2686 tester.tail = tail_pos;
2687 tester.head = tail_pos;
2689 for i in 0..len * 2 {
2690 tester.push_front(i);
2693 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2696 for i in 0..len * 2 {
2697 tester.push_back(i);
2700 let idx = tester.len() - 1 - i;
2701 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2704 assert!(tester.tail < tester.cap());
2705 assert!(tester.head < tester.cap());
2706 assert_eq!(tester, expected);
2716 // This test checks that every single combination of tail position, length, and
2717 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2719 let mut tester = VecDeque::with_capacity(15);
2720 // can't guarantee we got 15, so have to get what we got.
2721 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2722 // this test isn't covering what it wants to
2723 let cap = tester.capacity();
2726 // len is the length *after* insertion
2728 // 0, 1, 2, .., len - 1
2729 let expected = (0..).take(len).collect::<VecDeque<_>>();
2730 for tail_pos in 0..cap {
2731 for to_insert in 0..len {
2732 tester.tail = tail_pos;
2733 tester.head = tail_pos;
2736 tester.push_back(i);
2739 tester.insert(to_insert, to_insert);
2740 assert!(tester.tail < tester.cap());
2741 assert!(tester.head < tester.cap());
2742 assert_eq!(tester, expected);
2750 // This test checks that every single combination of tail position, length, and
2751 // removal position is tested. Capacity 15 should be large enough to cover every case.
2753 let mut tester = VecDeque::with_capacity(15);
2754 // can't guarantee we got 15, so have to get what we got.
2755 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2756 // this test isn't covering what it wants to
2757 let cap = tester.capacity();
2759 // len is the length *after* removal
2760 for len in 0..cap - 1 {
2761 // 0, 1, 2, .., len - 1
2762 let expected = (0..).take(len).collect::<VecDeque<_>>();
2763 for tail_pos in 0..cap {
2764 for to_remove in 0..len + 1 {
2765 tester.tail = tail_pos;
2766 tester.head = tail_pos;
2769 tester.push_back(1234);
2771 tester.push_back(i);
2773 if to_remove == len {
2774 tester.push_back(1234);
2776 tester.remove(to_remove);
2777 assert!(tester.tail < tester.cap());
2778 assert!(tester.head < tester.cap());
2779 assert_eq!(tester, expected);
2787 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2789 let cap = tester.capacity();
2790 for len in 0..cap + 1 {
2791 for tail in 0..cap + 1 {
2792 for drain_start in 0..len + 1 {
2793 for drain_end in drain_start..len + 1 {
2797 tester.push_back(i);
2800 // Check that we drain the correct values
2801 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2802 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2803 assert_eq!(drained, drained_expected);
2805 // We shouldn't have changed the capacity or made the
2806 // head or tail out of bounds
2807 assert_eq!(tester.capacity(), cap);
2808 assert!(tester.tail < tester.cap());
2809 assert!(tester.head < tester.cap());
2811 // We should see the correct values in the VecDeque
2812 let expected: VecDeque<_> = (0..drain_start)
2813 .chain(drain_end..len)
2815 assert_eq!(expected, tester);
2823 fn test_shrink_to_fit() {
2824 // This test checks that every single combination of head and tail position,
2825 // is tested. Capacity 15 should be large enough to cover every case.
2827 let mut tester = VecDeque::with_capacity(15);
2828 // can't guarantee we got 15, so have to get what we got.
2829 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2830 // this test isn't covering what it wants to
2831 let cap = tester.capacity();
2833 let max_cap = tester.capacity();
2835 for len in 0..cap + 1 {
2836 // 0, 1, 2, .., len - 1
2837 let expected = (0..).take(len).collect::<VecDeque<_>>();
2838 for tail_pos in 0..max_cap + 1 {
2839 tester.tail = tail_pos;
2840 tester.head = tail_pos;
2843 tester.push_back(i);
2845 tester.shrink_to_fit();
2846 assert!(tester.capacity() <= cap);
2847 assert!(tester.tail < tester.cap());
2848 assert!(tester.head < tester.cap());
2849 assert_eq!(tester, expected);
2855 fn test_split_off() {
2856 // This test checks that every single combination of tail position, length, and
2857 // split position is tested. Capacity 15 should be large enough to cover every case.
2859 let mut tester = VecDeque::with_capacity(15);
2860 // can't guarantee we got 15, so have to get what we got.
2861 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2862 // this test isn't covering what it wants to
2863 let cap = tester.capacity();
2865 // len is the length *before* splitting
2867 // index to split at
2868 for at in 0..len + 1 {
2869 // 0, 1, 2, .., at - 1 (may be empty)
2870 let expected_self = (0..).take(at).collect::<VecDeque<_>>();
2871 // at, at + 1, .., len - 1 (may be empty)
2872 let expected_other = (at..).take(len - at).collect::<VecDeque<_>>();
2874 for tail_pos in 0..cap {
2875 tester.tail = tail_pos;
2876 tester.head = tail_pos;
2878 tester.push_back(i);
2880 let result = tester.split_off(at);
2881 assert!(tester.tail < tester.cap());
2882 assert!(tester.head < tester.cap());
2883 assert!(result.tail < result.cap());
2884 assert!(result.head < result.cap());
2885 assert_eq!(tester, expected_self);
2886 assert_eq!(result, expected_other);
2893 fn test_from_vec() {
2894 use super::super::vec::Vec;
2896 for len in 0..cap + 1 {
2897 let mut vec = Vec::with_capacity(cap);
2900 let vd = VecDeque::from(vec.clone());
2901 assert!(vd.cap().is_power_of_two());
2902 assert_eq!(vd.len(), vec.len());
2903 assert!(vd.into_iter().eq(vec));
2909 fn test_vec_from_vecdeque() {
2910 use super::super::vec::Vec;
2912 fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
2913 let mut vd = VecDeque::with_capacity(cap);
2914 for _ in 0..offset {
2920 let vec: Vec<_> = Vec::from(vd.clone());
2921 assert_eq!(vec.len(), vd.len());
2922 assert!(vec.into_iter().eq(vd));
2925 for cap_pwr in 0..7 {
2926 // Make capacity as a (2^x)-1, so that the ring size is 2^x
2927 let cap = (2i32.pow(cap_pwr) - 1) as usize;
2929 // In these cases there is enough free space to solve it with copies
2930 for len in 0..((cap + 1) / 2) {
2931 // Test contiguous cases
2932 for offset in 0..(cap - len) {
2933 create_vec_and_test_convert(cap, offset, len)
2936 // Test cases where block at end of buffer is bigger than block at start
2937 for offset in (cap - len)..(cap - (len / 2)) {
2938 create_vec_and_test_convert(cap, offset, len)
2941 // Test cases where block at start of buffer is bigger than block at end
2942 for offset in (cap - (len / 2))..cap {
2943 create_vec_and_test_convert(cap, offset, len)
2947 // Now there's not (necessarily) space to straighten the ring with simple copies,
2948 // the ring will use swapping when:
2949 // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
2950 // right block size > free space && left block size > free space
2951 for len in ((cap + 1) / 2)..cap {
2952 // Test contiguous cases
2953 for offset in 0..(cap - len) {
2954 create_vec_and_test_convert(cap, offset, len)
2957 // Test cases where block at end of buffer is bigger than block at start
2958 for offset in (cap - len)..(cap - (len / 2)) {
2959 create_vec_and_test_convert(cap, offset, len)
2962 // Test cases where block at start of buffer is bigger than block at end
2963 for offset in (cap - (len / 2))..cap {
2964 create_vec_and_test_convert(cap, offset, len)