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 /// Element at index 0 is the front of the queue.
466 /// Panics if either index is out of bounds.
471 /// use std::collections::VecDeque;
473 /// let mut buf = VecDeque::new();
474 /// buf.push_back(3);
475 /// buf.push_back(4);
476 /// buf.push_back(5);
477 /// assert_eq!(buf, [3, 4, 5]);
479 /// assert_eq!(buf, [5, 4, 3]);
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn swap(&mut self, i: usize, j: usize) {
483 assert!(i < self.len());
484 assert!(j < self.len());
485 let ri = self.wrap_add(self.tail, i);
486 let rj = self.wrap_add(self.tail, j);
488 ptr::swap(self.ptr().offset(ri as isize),
489 self.ptr().offset(rj as isize))
493 /// Returns the number of elements the `VecDeque` can hold without
499 /// use std::collections::VecDeque;
501 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
502 /// assert!(buf.capacity() >= 10);
505 #[stable(feature = "rust1", since = "1.0.0")]
506 pub fn capacity(&self) -> usize {
510 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
511 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
513 /// Note that the allocator may give the collection more space than it requests. Therefore
514 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
515 /// insertions are expected.
519 /// Panics if the new capacity overflows `usize`.
524 /// use std::collections::VecDeque;
526 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
527 /// buf.reserve_exact(10);
528 /// assert!(buf.capacity() >= 11);
531 /// [`reserve`]: #method.reserve
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn reserve_exact(&mut self, additional: usize) {
534 self.reserve(additional);
537 /// Reserves capacity for at least `additional` more elements to be inserted in the given
538 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
542 /// Panics if the new capacity overflows `usize`.
547 /// use std::collections::VecDeque;
549 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
551 /// assert!(buf.capacity() >= 11);
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn reserve(&mut self, additional: usize) {
555 let old_cap = self.cap();
556 let used_cap = self.len() + 1;
557 let new_cap = used_cap.checked_add(additional)
558 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
559 .expect("capacity overflow");
561 if new_cap > old_cap {
562 self.buf.reserve_exact(used_cap, new_cap - used_cap);
564 self.handle_cap_increase(old_cap);
569 /// Shrinks the capacity of the `VecDeque` as much as possible.
571 /// It will drop down as close as possible to the length but the allocator may still inform the
572 /// `VecDeque` that there is space for a few more elements.
577 /// use std::collections::VecDeque;
579 /// let mut buf = VecDeque::with_capacity(15);
580 /// buf.extend(0..4);
581 /// assert_eq!(buf.capacity(), 15);
582 /// buf.shrink_to_fit();
583 /// assert!(buf.capacity() >= 4);
585 #[stable(feature = "deque_extras_15", since = "1.5.0")]
586 pub fn shrink_to_fit(&mut self) {
587 // +1 since the ringbuffer always leaves one space empty
588 // len + 1 can't overflow for an existing, well-formed ringbuffer.
589 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
590 if target_cap < self.cap() {
591 // There are three cases of interest:
592 // All elements are out of desired bounds
593 // Elements are contiguous, and head is out of desired bounds
594 // Elements are discontiguous, and tail is out of desired bounds
596 // At all other times, element positions are unaffected.
598 // Indicates that elements at the head should be moved.
599 let head_outside = self.head == 0 || self.head >= target_cap;
600 // Move elements from out of desired bounds (positions after target_cap)
601 if self.tail >= target_cap && head_outside {
603 // [. . . . . . . . o o o o o o o . ]
605 // [o o o o o o o . ]
607 self.copy_nonoverlapping(0, self.tail, self.len());
609 self.head = self.len();
611 } else if self.tail != 0 && self.tail < target_cap && head_outside {
613 // [. . . o o o o o o o . . . . . . ]
615 // [o o . o o o o o ]
616 let len = self.wrap_sub(self.head, target_cap);
618 self.copy_nonoverlapping(0, target_cap, len);
621 debug_assert!(self.head < self.tail);
622 } else if self.tail >= target_cap {
624 // [o o o o o . . . . . . . . . o o ]
626 // [o o o o o . o o ]
627 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
628 let len = self.cap() - self.tail;
629 let new_tail = target_cap - len;
631 self.copy_nonoverlapping(new_tail, self.tail, len);
633 self.tail = new_tail;
634 debug_assert!(self.head < self.tail);
637 self.buf.shrink_to_fit(target_cap);
639 debug_assert!(self.head < self.cap());
640 debug_assert!(self.tail < self.cap());
641 debug_assert!(self.cap().count_ones() == 1);
645 /// Shortens the `VecDeque`, dropping excess elements from the back.
647 /// If `len` is greater than the `VecDeque`'s current length, this has no
653 /// use std::collections::VecDeque;
655 /// let mut buf = VecDeque::new();
656 /// buf.push_back(5);
657 /// buf.push_back(10);
658 /// buf.push_back(15);
659 /// assert_eq!(buf, [5, 10, 15]);
661 /// assert_eq!(buf, [5]);
663 #[stable(feature = "deque_extras", since = "1.16.0")]
664 pub fn truncate(&mut self, len: usize) {
665 for _ in len..self.len() {
670 /// Returns a front-to-back iterator.
675 /// use std::collections::VecDeque;
677 /// let mut buf = VecDeque::new();
678 /// buf.push_back(5);
679 /// buf.push_back(3);
680 /// buf.push_back(4);
681 /// let b: &[_] = &[&5, &3, &4];
682 /// let c: Vec<&i32> = buf.iter().collect();
683 /// assert_eq!(&c[..], b);
685 #[stable(feature = "rust1", since = "1.0.0")]
686 pub fn iter(&self) -> Iter<T> {
690 ring: unsafe { self.buffer_as_slice() },
694 /// Returns a front-to-back iterator that returns mutable references.
699 /// use std::collections::VecDeque;
701 /// let mut buf = VecDeque::new();
702 /// buf.push_back(5);
703 /// buf.push_back(3);
704 /// buf.push_back(4);
705 /// for num in buf.iter_mut() {
708 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
709 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn iter_mut(&mut self) -> IterMut<T> {
716 ring: unsafe { self.buffer_as_mut_slice() },
720 /// Returns a pair of slices which contain, in order, the contents of the
726 /// use std::collections::VecDeque;
728 /// let mut vector = VecDeque::new();
730 /// vector.push_back(0);
731 /// vector.push_back(1);
732 /// vector.push_back(2);
734 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
736 /// vector.push_front(10);
737 /// vector.push_front(9);
739 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
742 #[stable(feature = "deque_extras_15", since = "1.5.0")]
743 pub fn as_slices(&self) -> (&[T], &[T]) {
745 let buf = self.buffer_as_slice();
746 RingSlices::ring_slices(buf, self.head, self.tail)
750 /// Returns a pair of slices which contain, in order, the contents of the
756 /// use std::collections::VecDeque;
758 /// let mut vector = VecDeque::new();
760 /// vector.push_back(0);
761 /// vector.push_back(1);
763 /// vector.push_front(10);
764 /// vector.push_front(9);
766 /// vector.as_mut_slices().0[0] = 42;
767 /// vector.as_mut_slices().1[0] = 24;
768 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
771 #[stable(feature = "deque_extras_15", since = "1.5.0")]
772 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
774 let head = self.head;
775 let tail = self.tail;
776 let buf = self.buffer_as_mut_slice();
777 RingSlices::ring_slices(buf, head, tail)
781 /// Returns the number of elements in the `VecDeque`.
786 /// use std::collections::VecDeque;
788 /// let mut v = VecDeque::new();
789 /// assert_eq!(v.len(), 0);
791 /// assert_eq!(v.len(), 1);
793 #[stable(feature = "rust1", since = "1.0.0")]
794 pub fn len(&self) -> usize {
795 count(self.tail, self.head, self.cap())
798 /// Returns `true` if the `VecDeque` is empty.
803 /// use std::collections::VecDeque;
805 /// let mut v = VecDeque::new();
806 /// assert!(v.is_empty());
808 /// assert!(!v.is_empty());
810 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn is_empty(&self) -> bool {
812 self.tail == self.head
815 /// Create a draining iterator that removes the specified range in the
816 /// `VecDeque` and yields the removed items.
818 /// Note 1: The element range is removed even if the iterator is not
819 /// consumed until the end.
821 /// Note 2: It is unspecified how many elements are removed from the deque,
822 /// if the `Drain` value is not dropped, but the borrow it holds expires
823 /// (eg. due to mem::forget).
827 /// Panics if the starting point is greater than the end point or if
828 /// the end point is greater than the length of the vector.
833 /// use std::collections::VecDeque;
835 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
836 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
837 /// assert_eq!(drained, [3]);
838 /// assert_eq!(v, [1, 2]);
840 /// // A full range clears all contents
842 /// assert!(v.is_empty());
845 #[stable(feature = "drain", since = "1.6.0")]
846 pub fn drain<R>(&mut self, range: R) -> Drain<T>
847 where R: RangeArgument<usize>
851 // When the Drain is first created, the source deque is shortened to
852 // make sure no uninitialized or moved-from elements are accessible at
853 // all if the Drain's destructor never gets to run.
855 // Drain will ptr::read out the values to remove.
856 // When finished, the remaining data will be copied back to cover the hole,
857 // and the head/tail values will be restored correctly.
859 let len = self.len();
860 let start = match range.start() {
862 Excluded(&n) => n + 1,
865 let end = match range.end() {
866 Included(&n) => n + 1,
870 assert!(start <= end, "drain lower bound was too large");
871 assert!(end <= len, "drain upper bound was too large");
873 // The deque's elements are parted into three segments:
874 // * self.tail -> drain_tail
875 // * drain_tail -> drain_head
876 // * drain_head -> self.head
878 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
880 // We store drain_tail as self.head, and drain_head and self.head as
881 // after_tail and after_head respectively on the Drain. This also
882 // truncates the effective array such that if the Drain is leaked, we
883 // have forgotten about the potentially moved values after the start of
887 // [. . . o o x x o o . . .]
889 let drain_tail = self.wrap_add(self.tail, start);
890 let drain_head = self.wrap_add(self.tail, end);
891 let head = self.head;
893 // "forget" about the values after the start of the drain until after
894 // the drain is complete and the Drain destructor is run.
895 self.head = drain_tail;
898 deque: Shared::from(&mut *self),
899 after_tail: drain_head,
904 ring: unsafe { self.buffer_as_mut_slice() },
909 /// Clears the buffer, removing all values.
914 /// use std::collections::VecDeque;
916 /// let mut v = VecDeque::new();
919 /// assert!(v.is_empty());
921 #[stable(feature = "rust1", since = "1.0.0")]
923 pub fn clear(&mut self) {
927 /// Returns `true` if the `VecDeque` contains an element equal to the
933 /// use std::collections::VecDeque;
935 /// let mut vector: VecDeque<u32> = VecDeque::new();
937 /// vector.push_back(0);
938 /// vector.push_back(1);
940 /// assert_eq!(vector.contains(&1), true);
941 /// assert_eq!(vector.contains(&10), false);
943 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
944 pub fn contains(&self, x: &T) -> bool
945 where T: PartialEq<T>
947 let (a, b) = self.as_slices();
948 a.contains(x) || b.contains(x)
951 /// Provides a reference to the front element, or `None` if the `VecDeque` is
957 /// use std::collections::VecDeque;
959 /// let mut d = VecDeque::new();
960 /// assert_eq!(d.front(), None);
964 /// assert_eq!(d.front(), Some(&1));
966 #[stable(feature = "rust1", since = "1.0.0")]
967 pub fn front(&self) -> Option<&T> {
968 if !self.is_empty() {
975 /// Provides a mutable reference to the front element, or `None` if the
976 /// `VecDeque` is empty.
981 /// use std::collections::VecDeque;
983 /// let mut d = VecDeque::new();
984 /// assert_eq!(d.front_mut(), None);
988 /// match d.front_mut() {
989 /// Some(x) => *x = 9,
992 /// assert_eq!(d.front(), Some(&9));
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub fn front_mut(&mut self) -> Option<&mut T> {
996 if !self.is_empty() {
1003 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1009 /// use std::collections::VecDeque;
1011 /// let mut d = VecDeque::new();
1012 /// assert_eq!(d.back(), None);
1016 /// assert_eq!(d.back(), Some(&2));
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 pub fn back(&self) -> Option<&T> {
1020 if !self.is_empty() {
1021 Some(&self[self.len() - 1])
1027 /// Provides a mutable reference to the back element, or `None` if the
1028 /// `VecDeque` is empty.
1033 /// use std::collections::VecDeque;
1035 /// let mut d = VecDeque::new();
1036 /// assert_eq!(d.back(), None);
1040 /// match d.back_mut() {
1041 /// Some(x) => *x = 9,
1044 /// assert_eq!(d.back(), Some(&9));
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 pub fn back_mut(&mut self) -> Option<&mut T> {
1048 let len = self.len();
1049 if !self.is_empty() {
1050 Some(&mut self[len - 1])
1056 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1062 /// use std::collections::VecDeque;
1064 /// let mut d = VecDeque::new();
1068 /// assert_eq!(d.pop_front(), Some(1));
1069 /// assert_eq!(d.pop_front(), Some(2));
1070 /// assert_eq!(d.pop_front(), None);
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 pub fn pop_front(&mut self) -> Option<T> {
1074 if self.is_empty() {
1077 let tail = self.tail;
1078 self.tail = self.wrap_add(self.tail, 1);
1079 unsafe { Some(self.buffer_read(tail)) }
1083 /// Prepends an element to the `VecDeque`.
1088 /// use std::collections::VecDeque;
1090 /// let mut d = VecDeque::new();
1091 /// d.push_front(1);
1092 /// d.push_front(2);
1093 /// assert_eq!(d.front(), Some(&2));
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub fn push_front(&mut self, value: T) {
1097 self.grow_if_necessary();
1099 self.tail = self.wrap_sub(self.tail, 1);
1100 let tail = self.tail;
1102 self.buffer_write(tail, value);
1106 /// Appends an element to the back of the `VecDeque`.
1111 /// use std::collections::VecDeque;
1113 /// let mut buf = VecDeque::new();
1114 /// buf.push_back(1);
1115 /// buf.push_back(3);
1116 /// assert_eq!(3, *buf.back().unwrap());
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 pub fn push_back(&mut self, value: T) {
1120 self.grow_if_necessary();
1122 let head = self.head;
1123 self.head = self.wrap_add(self.head, 1);
1124 unsafe { self.buffer_write(head, value) }
1127 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1133 /// use std::collections::VecDeque;
1135 /// let mut buf = VecDeque::new();
1136 /// assert_eq!(buf.pop_back(), None);
1137 /// buf.push_back(1);
1138 /// buf.push_back(3);
1139 /// assert_eq!(buf.pop_back(), Some(3));
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 pub fn pop_back(&mut self) -> Option<T> {
1143 if self.is_empty() {
1146 self.head = self.wrap_sub(self.head, 1);
1147 let head = self.head;
1148 unsafe { Some(self.buffer_read(head)) }
1153 fn is_contiguous(&self) -> bool {
1154 self.tail <= self.head
1157 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1160 /// This does not preserve ordering, but is O(1).
1162 /// Returns `None` if `index` is out of bounds.
1164 /// Element at index 0 is the front of the queue.
1169 /// use std::collections::VecDeque;
1171 /// let mut buf = VecDeque::new();
1172 /// assert_eq!(buf.swap_remove_back(0), None);
1173 /// buf.push_back(1);
1174 /// buf.push_back(2);
1175 /// buf.push_back(3);
1176 /// assert_eq!(buf, [1, 2, 3]);
1178 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1179 /// assert_eq!(buf, [3, 2]);
1181 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1182 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1183 let length = self.len();
1184 if length > 0 && index < length - 1 {
1185 self.swap(index, length - 1);
1186 } else if index >= length {
1192 /// Removes an element from anywhere in the `VecDeque` and returns it,
1193 /// replacing it with the first element.
1195 /// This does not preserve ordering, but is O(1).
1197 /// Returns `None` if `index` is out of bounds.
1199 /// Element at index 0 is the front of the queue.
1204 /// use std::collections::VecDeque;
1206 /// let mut buf = VecDeque::new();
1207 /// assert_eq!(buf.swap_remove_front(0), None);
1208 /// buf.push_back(1);
1209 /// buf.push_back(2);
1210 /// buf.push_back(3);
1211 /// assert_eq!(buf, [1, 2, 3]);
1213 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1214 /// assert_eq!(buf, [2, 1]);
1216 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1217 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1218 let length = self.len();
1219 if length > 0 && index < length && index != 0 {
1220 self.swap(index, 0);
1221 } else if index >= length {
1227 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1228 /// greater than or equal to `index` towards the back.
1230 /// Element at index 0 is the front of the queue.
1234 /// Panics if `index` is greater than `VecDeque`'s length
1239 /// use std::collections::VecDeque;
1241 /// let mut vec_deque = VecDeque::new();
1242 /// vec_deque.push_back('a');
1243 /// vec_deque.push_back('b');
1244 /// vec_deque.push_back('c');
1245 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1247 /// vec_deque.insert(1, 'd');
1248 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1250 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1251 pub fn insert(&mut self, index: usize, value: T) {
1252 assert!(index <= self.len(), "index out of bounds");
1253 self.grow_if_necessary();
1255 // Move the least number of elements in the ring buffer and insert
1258 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1260 // There are three main cases:
1261 // Elements are contiguous
1262 // - special case when tail is 0
1263 // Elements are discontiguous and the insert is in the tail section
1264 // Elements are discontiguous and the insert is in the head section
1266 // For each of those there are two more cases:
1267 // Insert is closer to tail
1268 // Insert is closer to head
1270 // Key: H - self.head
1272 // o - Valid element
1273 // I - Insertion element
1274 // A - The element that should be after the insertion point
1275 // M - Indicates element was moved
1277 let idx = self.wrap_add(self.tail, index);
1279 let distance_to_tail = index;
1280 let distance_to_head = self.len() - index;
1282 let contiguous = self.is_contiguous();
1284 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1285 (true, true, _) if index == 0 => {
1290 // [A o o o o o o . . . . . . . . .]
1293 // [A o o o o o o o . . . . . I]
1296 self.tail = self.wrap_sub(self.tail, 1);
1298 (true, true, _) => {
1300 // contiguous, insert closer to tail:
1303 // [. . . o o A o o o o . . . . . .]
1306 // [. . o o I A o o o o . . . . . .]
1309 // contiguous, insert closer to tail and tail is 0:
1313 // [o o A o o o o . . . . . . . . .]
1316 // [o I A o o o o o . . . . . . . o]
1319 let new_tail = self.wrap_sub(self.tail, 1);
1321 self.copy(new_tail, self.tail, 1);
1322 // Already moved the tail, so we only copy `index - 1` elements.
1323 self.copy(self.tail, self.tail + 1, index - 1);
1325 self.tail = new_tail;
1328 (true, false, _) => {
1330 // contiguous, insert closer to head:
1333 // [. . . o o o o A o o . . . . . .]
1336 // [. . . o o o o I A o o . . . . .]
1339 self.copy(idx + 1, idx, self.head - idx);
1340 self.head = self.wrap_add(self.head, 1);
1343 (false, true, true) => {
1345 // discontiguous, insert closer to tail, tail section:
1348 // [o o o o o o . . . . . o o A o o]
1351 // [o o o o o o . . . . o o I A o o]
1354 self.copy(self.tail - 1, self.tail, index);
1358 (false, false, true) => {
1360 // discontiguous, insert closer to head, tail section:
1363 // [o o . . . . . . . o o o o o A o]
1366 // [o o o . . . . . . o o o o o I A]
1369 // copy elements up to new head
1370 self.copy(1, 0, self.head);
1372 // copy last element into empty spot at bottom of buffer
1373 self.copy(0, self.cap() - 1, 1);
1375 // move elements from idx to end forward not including ^ element
1376 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1381 (false, true, false) if idx == 0 => {
1383 // discontiguous, insert is closer to tail, head section,
1384 // and is at index zero in the internal buffer:
1387 // [A o o o o o o o o o . . . o o o]
1390 // [A o o o o o o o o o . . o o o I]
1393 // copy elements up to new tail
1394 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1396 // copy last element into empty spot at bottom of buffer
1397 self.copy(self.cap() - 1, 0, 1);
1402 (false, true, false) => {
1404 // discontiguous, insert closer to tail, head section:
1407 // [o o o A o o o o o o . . . o o o]
1410 // [o o I A o o o o o o . . o o o o]
1413 // copy elements up to new tail
1414 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1416 // copy last element into empty spot at bottom of buffer
1417 self.copy(self.cap() - 1, 0, 1);
1419 // move elements from idx-1 to end forward not including ^ element
1420 self.copy(0, 1, idx - 1);
1425 (false, false, false) => {
1427 // discontiguous, insert closer to head, head section:
1430 // [o o o o A o o . . . . . . o o o]
1433 // [o o o o I A o o . . . . . o o o]
1436 self.copy(idx + 1, idx, self.head - idx);
1442 // tail might've been changed so we need to recalculate
1443 let new_idx = self.wrap_add(self.tail, index);
1445 self.buffer_write(new_idx, value);
1449 /// Removes and returns the element at `index` from the `VecDeque`.
1450 /// Whichever end is closer to the removal point will be moved to make
1451 /// room, and all the affected elements will be moved to new positions.
1452 /// Returns `None` if `index` is out of bounds.
1454 /// Element at index 0 is the front of the queue.
1459 /// use std::collections::VecDeque;
1461 /// let mut buf = VecDeque::new();
1462 /// buf.push_back(1);
1463 /// buf.push_back(2);
1464 /// buf.push_back(3);
1465 /// assert_eq!(buf, [1, 2, 3]);
1467 /// assert_eq!(buf.remove(1), Some(2));
1468 /// assert_eq!(buf, [1, 3]);
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 pub fn remove(&mut self, index: usize) -> Option<T> {
1472 if self.is_empty() || self.len() <= index {
1476 // There are three main cases:
1477 // Elements are contiguous
1478 // Elements are discontiguous and the removal is in the tail section
1479 // Elements are discontiguous and the removal is in the head section
1480 // - special case when elements are technically contiguous,
1481 // but self.head = 0
1483 // For each of those there are two more cases:
1484 // Insert is closer to tail
1485 // Insert is closer to head
1487 // Key: H - self.head
1489 // o - Valid element
1490 // x - Element marked for removal
1491 // R - Indicates element that is being removed
1492 // M - Indicates element was moved
1494 let idx = self.wrap_add(self.tail, index);
1496 let elem = unsafe { Some(self.buffer_read(idx)) };
1498 let distance_to_tail = index;
1499 let distance_to_head = self.len() - index;
1501 let contiguous = self.is_contiguous();
1503 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1504 (true, true, _) => {
1506 // contiguous, remove closer to tail:
1509 // [. . . o o x o o o o . . . . . .]
1512 // [. . . . o o o o o o . . . . . .]
1515 self.copy(self.tail + 1, self.tail, index);
1519 (true, false, _) => {
1521 // contiguous, remove closer to head:
1524 // [. . . o o o o x o o . . . . . .]
1527 // [. . . o o o o o o . . . . . . .]
1530 self.copy(idx, idx + 1, self.head - idx - 1);
1534 (false, true, true) => {
1536 // discontiguous, remove closer to tail, tail section:
1539 // [o o o o o o . . . . . o o x o o]
1542 // [o o o o o o . . . . . . o o o o]
1545 self.copy(self.tail + 1, self.tail, index);
1546 self.tail = self.wrap_add(self.tail, 1);
1549 (false, false, false) => {
1551 // discontiguous, remove closer to head, head section:
1554 // [o o o o x o o . . . . . . o o o]
1557 // [o o o o o o . . . . . . . o o o]
1560 self.copy(idx, idx + 1, self.head - idx - 1);
1564 (false, false, true) => {
1566 // discontiguous, remove closer to head, tail section:
1569 // [o o o . . . . . . o o o o o x o]
1572 // [o o . . . . . . . o o o o o o o]
1575 // or quasi-discontiguous, remove next to head, tail section:
1578 // [. . . . . . . . . o o o o o x o]
1581 // [. . . . . . . . . o o o o o o .]
1584 // draw in elements in the tail section
1585 self.copy(idx, idx + 1, self.cap() - idx - 1);
1587 // Prevents underflow.
1589 // copy first element into empty spot
1590 self.copy(self.cap() - 1, 0, 1);
1592 // move elements in the head section backwards
1593 self.copy(0, 1, self.head - 1);
1596 self.head = self.wrap_sub(self.head, 1);
1599 (false, true, false) => {
1601 // discontiguous, remove closer to tail, head section:
1604 // [o o x o o o o o o o . . . o o o]
1607 // [o o o o o o o o o o . . . . o o]
1610 // draw in elements up to idx
1611 self.copy(1, 0, idx);
1613 // copy last element into empty spot
1614 self.copy(0, self.cap() - 1, 1);
1616 // move elements from tail to end forward, excluding the last one
1617 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1619 self.tail = self.wrap_add(self.tail, 1);
1627 /// Splits the collection into two at the given index.
1629 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1630 /// and the returned `Self` contains elements `[at, len)`.
1632 /// Note that the capacity of `self` does not change.
1634 /// Element at index 0 is the front of the queue.
1638 /// Panics if `at > len`
1643 /// use std::collections::VecDeque;
1645 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1646 /// let buf2 = buf.split_off(1);
1647 /// assert_eq!(buf, [1]);
1648 /// assert_eq!(buf2, [2, 3]);
1651 #[stable(feature = "split_off", since = "1.4.0")]
1652 pub fn split_off(&mut self, at: usize) -> Self {
1653 let len = self.len();
1654 assert!(at <= len, "`at` out of bounds");
1656 let other_len = len - at;
1657 let mut other = VecDeque::with_capacity(other_len);
1660 let (first_half, second_half) = self.as_slices();
1662 let first_len = first_half.len();
1663 let second_len = second_half.len();
1665 // `at` lies in the first half.
1666 let amount_in_first = first_len - at;
1668 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1672 // just take all of the second half.
1673 ptr::copy_nonoverlapping(second_half.as_ptr(),
1674 other.ptr().offset(amount_in_first as isize),
1677 // `at` lies in the second half, need to factor in the elements we skipped
1678 // in the first half.
1679 let offset = at - first_len;
1680 let amount_in_second = second_len - offset;
1681 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1687 // Cleanup where the ends of the buffers are
1688 self.head = self.wrap_sub(self.head, other_len);
1689 other.head = other.wrap_index(other_len);
1694 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1698 /// Panics if the new number of elements in self overflows a `usize`.
1703 /// use std::collections::VecDeque;
1705 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1706 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1707 /// buf.append(&mut buf2);
1708 /// assert_eq!(buf, [1, 2, 3, 4]);
1709 /// assert_eq!(buf2, []);
1712 #[stable(feature = "append", since = "1.4.0")]
1713 pub fn append(&mut self, other: &mut Self) {
1715 self.extend(other.drain(..));
1718 /// Retains only the elements specified by the predicate.
1720 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1721 /// This method operates in place and preserves the order of the retained
1727 /// use std::collections::VecDeque;
1729 /// let mut buf = VecDeque::new();
1730 /// buf.extend(1..5);
1731 /// buf.retain(|&x| x%2 == 0);
1732 /// assert_eq!(buf, [2, 4]);
1734 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1735 pub fn retain<F>(&mut self, mut f: F)
1736 where F: FnMut(&T) -> bool
1738 let len = self.len();
1744 self.swap(i - del, i);
1748 self.truncate(len - del);
1752 // This may panic or abort
1754 fn grow_if_necessary(&mut self) {
1756 let old_cap = self.cap();
1759 self.handle_cap_increase(old_cap);
1761 debug_assert!(!self.is_full());
1765 /// Returns a place for insertion at the back of the `VecDeque`.
1767 /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back),
1768 /// but may be more efficient.
1773 /// #![feature(collection_placement)]
1774 /// #![feature(placement_in_syntax)]
1776 /// use std::collections::VecDeque;
1778 /// let mut buf = VecDeque::new();
1779 /// buf.place_back() <- 3;
1780 /// buf.place_back() <- 4;
1781 /// assert_eq!(&buf, &[3, 4]);
1783 #[unstable(feature = "collection_placement",
1784 reason = "placement protocol is subject to change",
1786 pub fn place_back(&mut self) -> PlaceBack<T> {
1787 PlaceBack { vec_deque: self }
1790 /// Returns a place for insertion at the front of the `VecDeque`.
1792 /// Using this method with placement syntax is equivalent to [`push_front`](#method.push_front),
1793 /// but may be more efficient.
1798 /// #![feature(collection_placement)]
1799 /// #![feature(placement_in_syntax)]
1801 /// use std::collections::VecDeque;
1803 /// let mut buf = VecDeque::new();
1804 /// buf.place_front() <- 3;
1805 /// buf.place_front() <- 4;
1806 /// assert_eq!(&buf, &[4, 3]);
1808 #[unstable(feature = "collection_placement",
1809 reason = "placement protocol is subject to change",
1811 pub fn place_front(&mut self) -> PlaceFront<T> {
1812 PlaceFront { vec_deque: self }
1816 impl<T: Clone> VecDeque<T> {
1817 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1818 /// either by removing excess elements or by appending clones of `value` to the back.
1823 /// use std::collections::VecDeque;
1825 /// let mut buf = VecDeque::new();
1826 /// buf.push_back(5);
1827 /// buf.push_back(10);
1828 /// buf.push_back(15);
1829 /// assert_eq!(buf, [5, 10, 15]);
1831 /// buf.resize(2, 0);
1832 /// assert_eq!(buf, [5, 10]);
1834 /// buf.resize(5, 20);
1835 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
1837 #[stable(feature = "deque_extras", since = "1.16.0")]
1838 pub fn resize(&mut self, new_len: usize, value: T) {
1839 let len = self.len();
1842 self.extend(repeat(value).take(new_len - len))
1844 self.truncate(new_len);
1849 /// Returns the index in the underlying buffer for a given logical element index.
1851 fn wrap_index(index: usize, size: usize) -> usize {
1852 // size is always a power of 2
1853 debug_assert!(size.is_power_of_two());
1857 /// Returns the two slices that cover the `VecDeque`'s valid range
1858 trait RingSlices: Sized {
1859 fn slice(self, from: usize, to: usize) -> Self;
1860 fn split_at(self, i: usize) -> (Self, Self);
1862 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
1863 let contiguous = tail <= head;
1865 let (empty, buf) = buf.split_at(0);
1866 (buf.slice(tail, head), empty)
1868 let (mid, right) = buf.split_at(tail);
1869 let (left, _) = mid.split_at(head);
1875 impl<'a, T> RingSlices for &'a [T] {
1876 fn slice(self, from: usize, to: usize) -> Self {
1879 fn split_at(self, i: usize) -> (Self, Self) {
1884 impl<'a, T> RingSlices for &'a mut [T] {
1885 fn slice(self, from: usize, to: usize) -> Self {
1888 fn split_at(self, i: usize) -> (Self, Self) {
1889 (*self).split_at_mut(i)
1893 /// Calculate the number of elements left to be read in the buffer
1895 fn count(tail: usize, head: usize, size: usize) -> usize {
1896 // size is always a power of 2
1897 (head.wrapping_sub(tail)) & (size - 1)
1900 /// An iterator over the elements of a `VecDeque`.
1902 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
1903 /// documentation for more.
1905 /// [`iter`]: struct.VecDeque.html#method.iter
1906 /// [`VecDeque`]: struct.VecDeque.html
1907 #[stable(feature = "rust1", since = "1.0.0")]
1908 pub struct Iter<'a, T: 'a> {
1914 #[stable(feature = "collection_debug", since = "1.17.0")]
1915 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1916 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1917 f.debug_tuple("Iter")
1925 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 impl<'a, T> Clone for Iter<'a, T> {
1928 fn clone(&self) -> Iter<'a, T> {
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl<'a, T> Iterator for Iter<'a, T> {
1942 fn next(&mut self) -> Option<&'a T> {
1943 if self.tail == self.head {
1946 let tail = self.tail;
1947 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1948 unsafe { Some(self.ring.get_unchecked(tail)) }
1952 fn size_hint(&self) -> (usize, Option<usize>) {
1953 let len = count(self.tail, self.head, self.ring.len());
1957 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
1958 where F: FnMut(Acc, Self::Item) -> Acc
1960 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
1961 accum = front.iter().fold(accum, &mut f);
1962 back.iter().fold(accum, &mut f)
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1969 fn next_back(&mut self) -> Option<&'a T> {
1970 if self.tail == self.head {
1973 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1974 unsafe { Some(self.ring.get_unchecked(self.head)) }
1977 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
1978 where F: FnMut(Acc, Self::Item) -> Acc
1980 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
1981 accum = back.iter().rfold(accum, &mut f);
1982 front.iter().rfold(accum, &mut f)
1986 #[stable(feature = "rust1", since = "1.0.0")]
1987 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1988 fn is_empty(&self) -> bool {
1989 self.head == self.tail
1993 #[unstable(feature = "fused", issue = "35602")]
1994 impl<'a, T> FusedIterator for Iter<'a, T> {}
1997 /// A mutable iterator over the elements of a `VecDeque`.
1999 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2000 /// documentation for more.
2002 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2003 /// [`VecDeque`]: struct.VecDeque.html
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 pub struct IterMut<'a, T: 'a> {
2011 #[stable(feature = "collection_debug", since = "1.17.0")]
2012 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2013 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2014 f.debug_tuple("IterMut")
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl<'a, T> Iterator for IterMut<'a, T> {
2024 type Item = &'a mut T;
2027 fn next(&mut self) -> Option<&'a mut T> {
2028 if self.tail == self.head {
2031 let tail = self.tail;
2032 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2035 let elem = self.ring.get_unchecked_mut(tail);
2036 Some(&mut *(elem as *mut _))
2041 fn size_hint(&self) -> (usize, Option<usize>) {
2042 let len = count(self.tail, self.head, self.ring.len());
2046 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2047 where F: FnMut(Acc, Self::Item) -> Acc
2049 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2050 accum = front.iter_mut().fold(accum, &mut f);
2051 back.iter_mut().fold(accum, &mut f)
2055 #[stable(feature = "rust1", since = "1.0.0")]
2056 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2058 fn next_back(&mut self) -> Option<&'a mut T> {
2059 if self.tail == self.head {
2062 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2065 let elem = self.ring.get_unchecked_mut(self.head);
2066 Some(&mut *(elem as *mut _))
2070 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2071 where F: FnMut(Acc, Self::Item) -> Acc
2073 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2074 accum = back.iter_mut().rfold(accum, &mut f);
2075 front.iter_mut().rfold(accum, &mut f)
2079 #[stable(feature = "rust1", since = "1.0.0")]
2080 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
2081 fn is_empty(&self) -> bool {
2082 self.head == self.tail
2086 #[unstable(feature = "fused", issue = "35602")]
2087 impl<'a, T> FusedIterator for IterMut<'a, T> {}
2089 /// An owning iterator over the elements of a `VecDeque`.
2091 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`][`VecDeque`]
2092 /// (provided by the `IntoIterator` trait). See its documentation for more.
2094 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2095 /// [`VecDeque`]: struct.VecDeque.html
2097 #[stable(feature = "rust1", since = "1.0.0")]
2098 pub struct IntoIter<T> {
2102 #[stable(feature = "collection_debug", since = "1.17.0")]
2103 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2105 f.debug_tuple("IntoIter")
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 impl<T> Iterator for IntoIter<T> {
2116 fn next(&mut self) -> Option<T> {
2117 self.inner.pop_front()
2121 fn size_hint(&self) -> (usize, Option<usize>) {
2122 let len = self.inner.len();
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 impl<T> DoubleEndedIterator for IntoIter<T> {
2130 fn next_back(&mut self) -> Option<T> {
2131 self.inner.pop_back()
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 impl<T> ExactSizeIterator for IntoIter<T> {
2137 fn is_empty(&self) -> bool {
2138 self.inner.is_empty()
2142 #[unstable(feature = "fused", issue = "35602")]
2143 impl<T> FusedIterator for IntoIter<T> {}
2145 /// A draining iterator over the elements of a `VecDeque`.
2147 /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its
2148 /// documentation for more.
2150 /// [`drain`]: struct.VecDeque.html#method.drain
2151 /// [`VecDeque`]: struct.VecDeque.html
2152 #[stable(feature = "drain", since = "1.6.0")]
2153 pub struct Drain<'a, T: 'a> {
2157 deque: Shared<VecDeque<T>>,
2160 #[stable(feature = "collection_debug", since = "1.17.0")]
2161 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2162 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2163 f.debug_tuple("Drain")
2164 .field(&self.after_tail)
2165 .field(&self.after_head)
2171 #[stable(feature = "drain", since = "1.6.0")]
2172 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2173 #[stable(feature = "drain", since = "1.6.0")]
2174 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2176 #[stable(feature = "drain", since = "1.6.0")]
2177 impl<'a, T: 'a> Drop for Drain<'a, T> {
2178 fn drop(&mut self) {
2179 for _ in self.by_ref() {}
2181 let source_deque = unsafe { self.deque.as_mut() };
2183 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2186 // [. . . o o x x o o . . .]
2188 let orig_tail = source_deque.tail;
2189 let drain_tail = source_deque.head;
2190 let drain_head = self.after_tail;
2191 let orig_head = self.after_head;
2193 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2194 let head_len = count(drain_head, orig_head, source_deque.cap());
2196 // Restore the original head value
2197 source_deque.head = orig_head;
2199 match (tail_len, head_len) {
2201 source_deque.head = 0;
2202 source_deque.tail = 0;
2205 source_deque.tail = drain_head;
2208 source_deque.head = drain_tail;
2211 if tail_len <= head_len {
2212 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2213 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2215 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2216 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2223 #[stable(feature = "drain", since = "1.6.0")]
2224 impl<'a, T: 'a> Iterator for Drain<'a, T> {
2228 fn next(&mut self) -> Option<T> {
2229 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2233 fn size_hint(&self) -> (usize, Option<usize>) {
2234 self.iter.size_hint()
2238 #[stable(feature = "drain", since = "1.6.0")]
2239 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
2241 fn next_back(&mut self) -> Option<T> {
2242 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2246 #[stable(feature = "drain", since = "1.6.0")]
2247 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
2249 #[unstable(feature = "fused", issue = "35602")]
2250 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
2252 #[stable(feature = "rust1", since = "1.0.0")]
2253 impl<A: PartialEq> PartialEq for VecDeque<A> {
2254 fn eq(&self, other: &VecDeque<A>) -> bool {
2255 if self.len() != other.len() {
2258 let (sa, sb) = self.as_slices();
2259 let (oa, ob) = other.as_slices();
2260 if sa.len() == oa.len() {
2261 sa == oa && sb == ob
2262 } else if sa.len() < oa.len() {
2263 // Always divisible in three sections, for example:
2264 // self: [a b c|d e f]
2265 // other: [0 1 2 3|4 5]
2266 // front = 3, mid = 1,
2267 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2268 let front = sa.len();
2269 let mid = oa.len() - front;
2271 let (oa_front, oa_mid) = oa.split_at(front);
2272 let (sb_mid, sb_back) = sb.split_at(mid);
2273 debug_assert_eq!(sa.len(), oa_front.len());
2274 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2275 debug_assert_eq!(sb_back.len(), ob.len());
2276 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2278 let front = oa.len();
2279 let mid = sa.len() - front;
2281 let (sa_front, sa_mid) = sa.split_at(front);
2282 let (ob_mid, ob_back) = ob.split_at(mid);
2283 debug_assert_eq!(sa_front.len(), oa.len());
2284 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2285 debug_assert_eq!(sb.len(), ob_back.len());
2286 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2291 #[stable(feature = "rust1", since = "1.0.0")]
2292 impl<A: Eq> Eq for VecDeque<A> {}
2294 macro_rules! __impl_slice_eq1 {
2295 ($Lhs: ty, $Rhs: ty) => {
2296 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2298 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2299 #[stable(feature = "vec-deque-partial-eq-slice", since = "1.17.0")]
2300 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2301 fn eq(&self, other: &$Rhs) -> bool {
2302 if self.len() != other.len() {
2305 let (sa, sb) = self.as_slices();
2306 let (oa, ob) = other[..].split_at(sa.len());
2307 sa == oa && sb == ob
2313 __impl_slice_eq1! { VecDeque<A>, Vec<B> }
2314 __impl_slice_eq1! { VecDeque<A>, &'b [B] }
2315 __impl_slice_eq1! { VecDeque<A>, &'b mut [B] }
2317 macro_rules! array_impls {
2320 __impl_slice_eq1! { VecDeque<A>, [B; $N] }
2321 __impl_slice_eq1! { VecDeque<A>, &'b [B; $N] }
2322 __impl_slice_eq1! { VecDeque<A>, &'b mut [B; $N] }
2329 10 11 12 13 14 15 16 17 18 19
2330 20 21 22 23 24 25 26 27 28 29
2334 #[stable(feature = "rust1", since = "1.0.0")]
2335 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2336 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2337 self.iter().partial_cmp(other.iter())
2341 #[stable(feature = "rust1", since = "1.0.0")]
2342 impl<A: Ord> Ord for VecDeque<A> {
2344 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2345 self.iter().cmp(other.iter())
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 impl<A: Hash> Hash for VecDeque<A> {
2351 fn hash<H: Hasher>(&self, state: &mut H) {
2352 self.len().hash(state);
2353 let (a, b) = self.as_slices();
2354 Hash::hash_slice(a, state);
2355 Hash::hash_slice(b, state);
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 impl<A> Index<usize> for VecDeque<A> {
2364 fn index(&self, index: usize) -> &A {
2365 self.get(index).expect("Out of bounds access")
2369 #[stable(feature = "rust1", since = "1.0.0")]
2370 impl<A> IndexMut<usize> for VecDeque<A> {
2372 fn index_mut(&mut self, index: usize) -> &mut A {
2373 self.get_mut(index).expect("Out of bounds access")
2377 #[stable(feature = "rust1", since = "1.0.0")]
2378 impl<A> FromIterator<A> for VecDeque<A> {
2379 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2380 let iterator = iter.into_iter();
2381 let (lower, _) = iterator.size_hint();
2382 let mut deq = VecDeque::with_capacity(lower);
2383 deq.extend(iterator);
2388 #[stable(feature = "rust1", since = "1.0.0")]
2389 impl<T> IntoIterator for VecDeque<T> {
2391 type IntoIter = IntoIter<T>;
2393 /// Consumes the list into a front-to-back iterator yielding elements by
2395 fn into_iter(self) -> IntoIter<T> {
2396 IntoIter { inner: self }
2400 #[stable(feature = "rust1", since = "1.0.0")]
2401 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2403 type IntoIter = Iter<'a, T>;
2405 fn into_iter(self) -> Iter<'a, T> {
2410 #[stable(feature = "rust1", since = "1.0.0")]
2411 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2412 type Item = &'a mut T;
2413 type IntoIter = IterMut<'a, T>;
2415 fn into_iter(self) -> IterMut<'a, T> {
2420 #[stable(feature = "rust1", since = "1.0.0")]
2421 impl<A> Extend<A> for VecDeque<A> {
2422 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2424 self.push_back(elt);
2429 #[stable(feature = "extend_ref", since = "1.2.0")]
2430 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2431 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2432 self.extend(iter.into_iter().cloned());
2436 #[stable(feature = "rust1", since = "1.0.0")]
2437 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2438 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2439 f.debug_list().entries(self).finish()
2443 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2444 impl<T> From<Vec<T>> for VecDeque<T> {
2445 fn from(mut other: Vec<T>) -> Self {
2447 let other_buf = other.as_mut_ptr();
2448 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2449 let len = other.len();
2452 // We need to extend the buf if it's not a power of two, too small
2453 // or doesn't have at least one free space
2454 if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) ||
2455 (buf.cap() == len) {
2456 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2457 buf.reserve_exact(len, cap - len);
2469 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2470 impl<T> From<VecDeque<T>> for Vec<T> {
2471 fn from(other: VecDeque<T>) -> Self {
2473 let buf = other.buf.ptr();
2474 let len = other.len();
2475 let tail = other.tail;
2476 let head = other.head;
2477 let cap = other.cap();
2479 // Need to move the ring to the front of the buffer, as vec will expect this.
2480 if other.is_contiguous() {
2481 ptr::copy(buf.offset(tail as isize), buf, len);
2483 if (tail - head) >= cmp::min((cap - tail), head) {
2484 // There is enough free space in the centre for the shortest block so we can
2485 // do this in at most three copy moves.
2486 if (cap - tail) > head {
2487 // right hand block is the long one; move that enough for the left
2488 ptr::copy(buf.offset(tail as isize),
2489 buf.offset((tail - head) as isize),
2491 // copy left in the end
2492 ptr::copy(buf, buf.offset((cap - head) as isize), head);
2493 // shift the new thing to the start
2494 ptr::copy(buf.offset((tail - head) as isize), buf, len);
2496 // left hand block is the long one, we can do it in two!
2497 ptr::copy(buf, buf.offset((cap - tail) as isize), head);
2498 ptr::copy(buf.offset(tail as isize), buf, cap - tail);
2501 // Need to use N swaps to move the ring
2502 // We can use the space at the end of the ring as a temp store
2504 let mut left_edge: usize = 0;
2505 let mut right_edge: usize = tail;
2507 // The general problem looks like this
2508 // GHIJKLM...ABCDEF - before any swaps
2509 // ABCDEFM...GHIJKL - after 1 pass of swaps
2510 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2511 // - then restart the algorithm with a new (smaller) store
2512 // Sometimes the temp store is reached when the right edge is at the end
2513 // of the buffer - this means we've hit the right order with fewer swaps!
2516 // ABCDEF.. - after four only swaps we've finished
2518 while left_edge < len && right_edge != cap {
2519 let mut right_offset = 0;
2520 for i in left_edge..right_edge {
2521 right_offset = (i - left_edge) % (cap - right_edge);
2522 let src: isize = (right_edge + right_offset) as isize;
2523 ptr::swap(buf.offset(i as isize), buf.offset(src));
2525 let n_ops = right_edge - left_edge;
2527 right_edge += right_offset + 1;
2533 let out = Vec::from_raw_parts(buf, len, cap);
2540 /// A place for insertion at the back of a `VecDeque`.
2542 /// See [`VecDeque::place_back`](struct.VecDeque.html#method.place_back) for details.
2543 #[must_use = "places do nothing unless written to with `<-` syntax"]
2544 #[unstable(feature = "collection_placement",
2545 reason = "struct name and placement protocol are subject to change",
2548 pub struct PlaceBack<'a, T: 'a> {
2549 vec_deque: &'a mut VecDeque<T>,
2552 #[unstable(feature = "collection_placement",
2553 reason = "placement protocol is subject to change",
2555 impl<'a, T> Placer<T> for PlaceBack<'a, T> {
2556 type Place = PlaceBack<'a, T>;
2558 fn make_place(self) -> Self {
2559 self.vec_deque.grow_if_necessary();
2564 #[unstable(feature = "collection_placement",
2565 reason = "placement protocol is subject to change",
2567 impl<'a, T> Place<T> for PlaceBack<'a, T> {
2568 fn pointer(&mut self) -> *mut T {
2569 unsafe { self.vec_deque.ptr().offset(self.vec_deque.head as isize) }
2573 #[unstable(feature = "collection_placement",
2574 reason = "placement protocol is subject to change",
2576 impl<'a, T> InPlace<T> for PlaceBack<'a, T> {
2577 type Owner = &'a mut T;
2579 unsafe fn finalize(self) -> &'a mut T {
2580 let head = self.vec_deque.head;
2581 self.vec_deque.head = self.vec_deque.wrap_add(head, 1);
2582 &mut *(self.vec_deque.ptr().offset(head as isize))
2586 /// A place for insertion at the front of a `VecDeque`.
2588 /// See [`VecDeque::place_front`](struct.VecDeque.html#method.place_front) for details.
2589 #[must_use = "places do nothing unless written to with `<-` syntax"]
2590 #[unstable(feature = "collection_placement",
2591 reason = "struct name and placement protocol are subject to change",
2594 pub struct PlaceFront<'a, T: 'a> {
2595 vec_deque: &'a mut VecDeque<T>,
2598 #[unstable(feature = "collection_placement",
2599 reason = "placement protocol is subject to change",
2601 impl<'a, T> Placer<T> for PlaceFront<'a, T> {
2602 type Place = PlaceFront<'a, T>;
2604 fn make_place(self) -> Self {
2605 self.vec_deque.grow_if_necessary();
2610 #[unstable(feature = "collection_placement",
2611 reason = "placement protocol is subject to change",
2613 impl<'a, T> Place<T> for PlaceFront<'a, T> {
2614 fn pointer(&mut self) -> *mut T {
2615 let tail = self.vec_deque.wrap_sub(self.vec_deque.tail, 1);
2616 unsafe { self.vec_deque.ptr().offset(tail as isize) }
2620 #[unstable(feature = "collection_placement",
2621 reason = "placement protocol is subject to change",
2623 impl<'a, T> InPlace<T> for PlaceFront<'a, T> {
2624 type Owner = &'a mut T;
2626 unsafe fn finalize(self) -> &'a mut T {
2627 self.vec_deque.tail = self.vec_deque.wrap_sub(self.vec_deque.tail, 1);
2628 &mut *(self.vec_deque.ptr().offset(self.vec_deque.tail as isize))
2636 use super::VecDeque;
2639 fn bench_push_back_100(b: &mut test::Bencher) {
2640 let mut deq = VecDeque::with_capacity(101);
2651 fn bench_push_front_100(b: &mut test::Bencher) {
2652 let mut deq = VecDeque::with_capacity(101);
2663 fn bench_pop_back_100(b: &mut test::Bencher) {
2664 let mut deq = VecDeque::<i32>::with_capacity(101);
2669 while !deq.is_empty() {
2670 test::black_box(deq.pop_back());
2676 fn bench_pop_front_100(b: &mut test::Bencher) {
2677 let mut deq = VecDeque::<i32>::with_capacity(101);
2682 while !deq.is_empty() {
2683 test::black_box(deq.pop_front());
2689 fn test_swap_front_back_remove() {
2690 fn test(back: bool) {
2691 // This test checks that every single combination of tail position and length is tested.
2692 // Capacity 15 should be large enough to cover every case.
2693 let mut tester = VecDeque::with_capacity(15);
2694 let usable_cap = tester.capacity();
2695 let final_len = usable_cap / 2;
2697 for len in 0..final_len {
2698 let expected: VecDeque<_> = if back {
2701 (0..len).rev().collect()
2703 for tail_pos in 0..usable_cap {
2704 tester.tail = tail_pos;
2705 tester.head = tail_pos;
2707 for i in 0..len * 2 {
2708 tester.push_front(i);
2711 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2714 for i in 0..len * 2 {
2715 tester.push_back(i);
2718 let idx = tester.len() - 1 - i;
2719 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2722 assert!(tester.tail < tester.cap());
2723 assert!(tester.head < tester.cap());
2724 assert_eq!(tester, expected);
2734 // This test checks that every single combination of tail position, length, and
2735 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2737 let mut tester = VecDeque::with_capacity(15);
2738 // can't guarantee we got 15, so have to get what we got.
2739 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2740 // this test isn't covering what it wants to
2741 let cap = tester.capacity();
2744 // len is the length *after* insertion
2746 // 0, 1, 2, .., len - 1
2747 let expected = (0..).take(len).collect::<VecDeque<_>>();
2748 for tail_pos in 0..cap {
2749 for to_insert in 0..len {
2750 tester.tail = tail_pos;
2751 tester.head = tail_pos;
2754 tester.push_back(i);
2757 tester.insert(to_insert, to_insert);
2758 assert!(tester.tail < tester.cap());
2759 assert!(tester.head < tester.cap());
2760 assert_eq!(tester, expected);
2768 // This test checks that every single combination of tail position, length, and
2769 // removal position is tested. Capacity 15 should be large enough to cover every case.
2771 let mut tester = VecDeque::with_capacity(15);
2772 // can't guarantee we got 15, so have to get what we got.
2773 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2774 // this test isn't covering what it wants to
2775 let cap = tester.capacity();
2777 // len is the length *after* removal
2778 for len in 0..cap - 1 {
2779 // 0, 1, 2, .., len - 1
2780 let expected = (0..).take(len).collect::<VecDeque<_>>();
2781 for tail_pos in 0..cap {
2782 for to_remove in 0..len + 1 {
2783 tester.tail = tail_pos;
2784 tester.head = tail_pos;
2787 tester.push_back(1234);
2789 tester.push_back(i);
2791 if to_remove == len {
2792 tester.push_back(1234);
2794 tester.remove(to_remove);
2795 assert!(tester.tail < tester.cap());
2796 assert!(tester.head < tester.cap());
2797 assert_eq!(tester, expected);
2805 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2807 let cap = tester.capacity();
2808 for len in 0..cap + 1 {
2809 for tail in 0..cap + 1 {
2810 for drain_start in 0..len + 1 {
2811 for drain_end in drain_start..len + 1 {
2815 tester.push_back(i);
2818 // Check that we drain the correct values
2819 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2820 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2821 assert_eq!(drained, drained_expected);
2823 // We shouldn't have changed the capacity or made the
2824 // head or tail out of bounds
2825 assert_eq!(tester.capacity(), cap);
2826 assert!(tester.tail < tester.cap());
2827 assert!(tester.head < tester.cap());
2829 // We should see the correct values in the VecDeque
2830 let expected: VecDeque<_> = (0..drain_start)
2831 .chain(drain_end..len)
2833 assert_eq!(expected, tester);
2841 fn test_shrink_to_fit() {
2842 // This test checks that every single combination of head and tail position,
2843 // is tested. Capacity 15 should be large enough to cover every case.
2845 let mut tester = VecDeque::with_capacity(15);
2846 // can't guarantee we got 15, so have to get what we got.
2847 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2848 // this test isn't covering what it wants to
2849 let cap = tester.capacity();
2851 let max_cap = tester.capacity();
2853 for len in 0..cap + 1 {
2854 // 0, 1, 2, .., len - 1
2855 let expected = (0..).take(len).collect::<VecDeque<_>>();
2856 for tail_pos in 0..max_cap + 1 {
2857 tester.tail = tail_pos;
2858 tester.head = tail_pos;
2861 tester.push_back(i);
2863 tester.shrink_to_fit();
2864 assert!(tester.capacity() <= cap);
2865 assert!(tester.tail < tester.cap());
2866 assert!(tester.head < tester.cap());
2867 assert_eq!(tester, expected);
2873 fn test_split_off() {
2874 // This test checks that every single combination of tail position, length, and
2875 // split position is tested. Capacity 15 should be large enough to cover every case.
2877 let mut tester = VecDeque::with_capacity(15);
2878 // can't guarantee we got 15, so have to get what we got.
2879 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2880 // this test isn't covering what it wants to
2881 let cap = tester.capacity();
2883 // len is the length *before* splitting
2885 // index to split at
2886 for at in 0..len + 1 {
2887 // 0, 1, 2, .., at - 1 (may be empty)
2888 let expected_self = (0..).take(at).collect::<VecDeque<_>>();
2889 // at, at + 1, .., len - 1 (may be empty)
2890 let expected_other = (at..).take(len - at).collect::<VecDeque<_>>();
2892 for tail_pos in 0..cap {
2893 tester.tail = tail_pos;
2894 tester.head = tail_pos;
2896 tester.push_back(i);
2898 let result = tester.split_off(at);
2899 assert!(tester.tail < tester.cap());
2900 assert!(tester.head < tester.cap());
2901 assert!(result.tail < result.cap());
2902 assert!(result.head < result.cap());
2903 assert_eq!(tester, expected_self);
2904 assert_eq!(result, expected_other);
2911 fn test_from_vec() {
2912 use super::super::vec::Vec;
2914 for len in 0..cap + 1 {
2915 let mut vec = Vec::with_capacity(cap);
2918 let vd = VecDeque::from(vec.clone());
2919 assert!(vd.cap().is_power_of_two());
2920 assert_eq!(vd.len(), vec.len());
2921 assert!(vd.into_iter().eq(vec));
2927 fn test_vec_from_vecdeque() {
2928 use super::super::vec::Vec;
2930 fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
2931 let mut vd = VecDeque::with_capacity(cap);
2932 for _ in 0..offset {
2938 let vec: Vec<_> = Vec::from(vd.clone());
2939 assert_eq!(vec.len(), vd.len());
2940 assert!(vec.into_iter().eq(vd));
2943 for cap_pwr in 0..7 {
2944 // Make capacity as a (2^x)-1, so that the ring size is 2^x
2945 let cap = (2i32.pow(cap_pwr) - 1) as usize;
2947 // In these cases there is enough free space to solve it with copies
2948 for len in 0..((cap + 1) / 2) {
2949 // Test contiguous cases
2950 for offset in 0..(cap - len) {
2951 create_vec_and_test_convert(cap, offset, len)
2954 // Test cases where block at end of buffer is bigger than block at start
2955 for offset in (cap - len)..(cap - (len / 2)) {
2956 create_vec_and_test_convert(cap, offset, len)
2959 // Test cases where block at start of buffer is bigger than block at end
2960 for offset in (cap - (len / 2))..cap {
2961 create_vec_and_test_convert(cap, offset, len)
2965 // Now there's not (necessarily) space to straighten the ring with simple copies,
2966 // the ring will use swapping when:
2967 // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
2968 // right block size > free space && left block size > free space
2969 for len in ((cap + 1) / 2)..cap {
2970 // Test contiguous cases
2971 for offset in 0..(cap - len) {
2972 create_vec_and_test_convert(cap, offset, len)
2975 // Test cases where block at end of buffer is bigger than block at start
2976 for offset in (cap - len)..(cap - (len / 2)) {
2977 create_vec_and_test_convert(cap, offset, len)
2980 // Test cases where block at start of buffer is bigger than block at end
2981 for offset in (cap - (len / 2))..cap {
2982 create_vec_and_test_convert(cap, offset, len)