1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A double-ended queue implemented with a growable ring buffer.
13 //! This queue has `O(1)` amortized inserts and removals from both ends of the
14 //! container. It also has `O(1)` indexing like a vector. The contained elements
15 //! are not required to be copyable, and the queue will be sendable if the
16 //! contained type is sendable.
18 #![stable(feature = "rust1", since = "1.0.0")]
20 use core::cmp::Ordering;
22 use core::iter::{repeat, FromIterator, FusedIterator};
24 use core::ops::Bound::{Excluded, Included, Unbounded};
25 use core::ops::{Index, IndexMut, RangeBounds};
27 use core::ptr::NonNull;
30 use core::hash::{Hash, Hasher};
33 use collections::CollectionAllocErr;
37 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
38 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
39 #[cfg(target_pointer_width = "32")]
40 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
41 #[cfg(target_pointer_width = "64")]
42 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
44 /// A double-ended queue implemented with a growable ring buffer.
46 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
47 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
48 /// push onto the back in this manner, and iterating over `VecDeque` goes front
51 /// [`push_back`]: #method.push_back
52 /// [`pop_front`]: #method.pop_front
53 /// [`extend`]: #method.extend
54 /// [`append`]: #method.append
55 #[stable(feature = "rust1", since = "1.0.0")]
56 pub struct VecDeque<T> {
57 // tail and head are pointers into the buffer. Tail always points
58 // to the first element that could be read, Head always points
59 // to where data should be written.
60 // If tail == head the buffer is empty. The length of the ringbuffer
61 // is defined as the distance between the two.
67 #[stable(feature = "rust1", since = "1.0.0")]
68 impl<T: Clone> Clone for VecDeque<T> {
69 fn clone(&self) -> VecDeque<T> {
70 self.iter().cloned().collect()
74 #[stable(feature = "rust1", since = "1.0.0")]
75 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
77 let (front, back) = self.as_mut_slices();
80 ptr::drop_in_place(front);
81 ptr::drop_in_place(back);
83 // RawVec handles deallocation
87 #[stable(feature = "rust1", since = "1.0.0")]
88 impl<T> Default for VecDeque<T> {
89 /// Creates an empty `VecDeque<T>`.
91 fn default() -> VecDeque<T> {
97 /// Marginally more convenient
99 fn ptr(&self) -> *mut T {
103 /// Marginally more convenient
105 fn cap(&self) -> usize {
106 if mem::size_of::<T>() == 0 {
107 // For zero sized types, we are always at maximum capacity
114 /// Turn ptr into a slice
116 unsafe fn buffer_as_slice(&self) -> &[T] {
117 slice::from_raw_parts(self.ptr(), self.cap())
120 /// Turn ptr into a mut slice
122 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
123 slice::from_raw_parts_mut(self.ptr(), self.cap())
126 /// Moves an element out of the buffer
128 unsafe fn buffer_read(&mut self, off: usize) -> T {
129 ptr::read(self.ptr().add(off))
132 /// Writes an element into the buffer, moving it.
134 unsafe fn buffer_write(&mut self, off: usize, value: T) {
135 ptr::write(self.ptr().add(off), value);
138 /// Returns `true` if and only if the buffer is at full capacity.
140 fn is_full(&self) -> bool {
141 self.cap() - self.len() == 1
144 /// Returns the index in the underlying buffer for a given logical element
147 fn wrap_index(&self, idx: usize) -> usize {
148 wrap_index(idx, self.cap())
151 /// Returns the index in the underlying buffer for a given logical element
154 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
155 wrap_index(idx.wrapping_add(addend), self.cap())
158 /// Returns the index in the underlying buffer for a given logical element
159 /// index - subtrahend.
161 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
162 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
165 /// Copies a contiguous block of memory len long from src to dst
167 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
168 debug_assert!(dst + len <= self.cap(),
169 "cpy dst={} src={} len={} cap={}",
174 debug_assert!(src + len <= self.cap(),
175 "cpy dst={} src={} len={} cap={}",
180 ptr::copy(self.ptr().add(src),
185 /// Copies a contiguous block of memory len long from src to dst
187 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
188 debug_assert!(dst + len <= self.cap(),
189 "cno dst={} src={} len={} cap={}",
194 debug_assert!(src + len <= self.cap(),
195 "cno dst={} src={} len={} cap={}",
200 ptr::copy_nonoverlapping(self.ptr().add(src),
205 /// Copies a potentially wrapping block of memory len long from src to dest.
206 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
207 /// most one continuous overlapping region between src and dest).
208 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
210 fn diff(a: usize, b: usize) -> usize {
211 if a <= b { b - a } else { a - b }
213 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
214 "wrc dst={} src={} len={} cap={}",
220 if src == dst || len == 0 {
224 let dst_after_src = self.wrap_sub(dst, src) < len;
226 let src_pre_wrap_len = self.cap() - src;
227 let dst_pre_wrap_len = self.cap() - dst;
228 let src_wraps = src_pre_wrap_len < len;
229 let dst_wraps = dst_pre_wrap_len < len;
231 match (dst_after_src, src_wraps, dst_wraps) {
232 (_, false, false) => {
233 // src doesn't wrap, dst doesn't wrap
236 // 1 [_ _ A A B B C C _]
237 // 2 [_ _ A A A A B B _]
240 self.copy(dst, src, len);
242 (false, false, true) => {
243 // dst before src, src doesn't wrap, dst wraps
246 // 1 [A A B B _ _ _ C C]
247 // 2 [A A B B _ _ _ A A]
248 // 3 [B B B B _ _ _ A A]
251 self.copy(dst, src, dst_pre_wrap_len);
252 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
254 (true, false, true) => {
255 // src before dst, src doesn't wrap, dst wraps
258 // 1 [C C _ _ _ A A B B]
259 // 2 [B B _ _ _ A A B B]
260 // 3 [B B _ _ _ A A A A]
263 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
264 self.copy(dst, src, dst_pre_wrap_len);
266 (false, true, false) => {
267 // dst before src, src wraps, dst doesn't wrap
270 // 1 [C C _ _ _ A A B B]
271 // 2 [C C _ _ _ B B B B]
272 // 3 [C C _ _ _ B B C C]
275 self.copy(dst, src, src_pre_wrap_len);
276 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
278 (true, true, false) => {
279 // src before dst, src wraps, dst doesn't wrap
282 // 1 [A A B B _ _ _ C C]
283 // 2 [A A A A _ _ _ C C]
284 // 3 [C C A A _ _ _ C C]
287 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
288 self.copy(dst, src, src_pre_wrap_len);
290 (false, true, true) => {
291 // dst before src, src wraps, dst wraps
294 // 1 [A B C D _ E F G H]
295 // 2 [A B C D _ E G H H]
296 // 3 [A B C D _ E G H A]
297 // 4 [B C C D _ E G H A]
300 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
301 let delta = dst_pre_wrap_len - src_pre_wrap_len;
302 self.copy(dst, src, src_pre_wrap_len);
303 self.copy(dst + src_pre_wrap_len, 0, delta);
304 self.copy(0, delta, len - dst_pre_wrap_len);
306 (true, true, true) => {
307 // src before dst, src wraps, dst wraps
310 // 1 [A B C D _ E F G H]
311 // 2 [A A B D _ E F G H]
312 // 3 [H A B D _ E F G H]
313 // 4 [H A B D _ E F F G]
316 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
317 let delta = src_pre_wrap_len - dst_pre_wrap_len;
318 self.copy(delta, 0, len - src_pre_wrap_len);
319 self.copy(0, self.cap() - delta, delta);
320 self.copy(dst, src, dst_pre_wrap_len);
325 /// Frobs the head and tail sections around to handle the fact that we
326 /// just reallocated. Unsafe because it trusts old_cap.
328 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
329 let new_cap = self.cap();
331 // Move the shortest contiguous section of the ring buffer
333 // [o o o o o o o . ]
335 // A [o o o o o o o . . . . . . . . . ]
337 // [o o . o o o o o ]
339 // B [. . . o o o o o o o . . . . . . ]
341 // [o o o o o . o o ]
343 // C [o o o o o . . . . . . . . . o o ]
345 if self.tail <= self.head {
348 } else if self.head < old_cap - self.tail {
350 self.copy_nonoverlapping(old_cap, 0, self.head);
351 self.head += old_cap;
352 debug_assert!(self.head > self.tail);
355 let new_tail = new_cap - (old_cap - self.tail);
356 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
357 self.tail = new_tail;
358 debug_assert!(self.head < self.tail);
360 debug_assert!(self.head < self.cap());
361 debug_assert!(self.tail < self.cap());
362 debug_assert!(self.cap().count_ones() == 1);
366 impl<T> VecDeque<T> {
367 /// Creates an empty `VecDeque`.
372 /// use std::collections::VecDeque;
374 /// let vector: VecDeque<u32> = VecDeque::new();
376 #[stable(feature = "rust1", since = "1.0.0")]
377 pub fn new() -> VecDeque<T> {
378 VecDeque::with_capacity(INITIAL_CAPACITY)
381 /// Creates an empty `VecDeque` with space for at least `n` elements.
386 /// use std::collections::VecDeque;
388 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn with_capacity(n: usize) -> VecDeque<T> {
392 // +1 since the ringbuffer always leaves one space empty
393 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
394 assert!(cap > n, "capacity overflow");
399 buf: RawVec::with_capacity(cap),
403 /// Retrieves an element in the `VecDeque` by index.
405 /// Element at index 0 is the front of the queue.
410 /// use std::collections::VecDeque;
412 /// let mut buf = VecDeque::new();
413 /// buf.push_back(3);
414 /// buf.push_back(4);
415 /// buf.push_back(5);
416 /// assert_eq!(buf.get(1), Some(&4));
418 #[stable(feature = "rust1", since = "1.0.0")]
419 pub fn get(&self, index: usize) -> Option<&T> {
420 if index < self.len() {
421 let idx = self.wrap_add(self.tail, index);
422 unsafe { Some(&*self.ptr().add(idx)) }
428 /// Retrieves an element in the `VecDeque` mutably by index.
430 /// Element at index 0 is the front of the queue.
435 /// use std::collections::VecDeque;
437 /// let mut buf = VecDeque::new();
438 /// buf.push_back(3);
439 /// buf.push_back(4);
440 /// buf.push_back(5);
441 /// if let Some(elem) = buf.get_mut(1) {
445 /// assert_eq!(buf[1], 7);
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
449 if index < self.len() {
450 let idx = self.wrap_add(self.tail, index);
451 unsafe { Some(&mut *self.ptr().add(idx)) }
457 /// Swaps elements at indices `i` and `j`.
459 /// `i` and `j` may be equal.
461 /// Element at index 0 is the front of the queue.
465 /// Panics if either index is out of bounds.
470 /// use std::collections::VecDeque;
472 /// let mut buf = VecDeque::new();
473 /// buf.push_back(3);
474 /// buf.push_back(4);
475 /// buf.push_back(5);
476 /// assert_eq!(buf, [3, 4, 5]);
478 /// assert_eq!(buf, [5, 4, 3]);
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn swap(&mut self, i: usize, j: usize) {
482 assert!(i < self.len());
483 assert!(j < self.len());
484 let ri = self.wrap_add(self.tail, i);
485 let rj = self.wrap_add(self.tail, j);
487 ptr::swap(self.ptr().add(ri),
492 /// Returns the number of elements the `VecDeque` can hold without
498 /// use std::collections::VecDeque;
500 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
501 /// assert!(buf.capacity() >= 10);
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn capacity(&self) -> usize {
509 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
510 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
512 /// Note that the allocator may give the collection more space than it requests. Therefore
513 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
514 /// insertions are expected.
518 /// Panics if the new capacity overflows `usize`.
523 /// use std::collections::VecDeque;
525 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
526 /// buf.reserve_exact(10);
527 /// assert!(buf.capacity() >= 11);
530 /// [`reserve`]: #method.reserve
531 #[stable(feature = "rust1", since = "1.0.0")]
532 pub fn reserve_exact(&mut self, additional: usize) {
533 self.reserve(additional);
536 /// Reserves capacity for at least `additional` more elements to be inserted in the given
537 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
541 /// Panics if the new capacity overflows `usize`.
546 /// use std::collections::VecDeque;
548 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
550 /// assert!(buf.capacity() >= 11);
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn reserve(&mut self, additional: usize) {
554 let old_cap = self.cap();
555 let used_cap = self.len() + 1;
556 let new_cap = used_cap.checked_add(additional)
557 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
558 .expect("capacity overflow");
560 if new_cap > old_cap {
561 self.buf.reserve_exact(used_cap, new_cap - used_cap);
563 self.handle_cap_increase(old_cap);
568 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
569 /// be inserted in the given `VecDeque<T>`. After calling `reserve_exact`,
570 /// capacity will be greater than or equal to `self.len() + additional`.
571 /// Does nothing if the capacity is already sufficient.
573 /// Note that the allocator may give the collection more space than it
574 /// requests. Therefore capacity can not be relied upon to be precisely
575 /// minimal. Prefer `reserve` if future insertions are expected.
579 /// If the capacity overflows, or the allocator reports a failure, then an error
585 /// #![feature(try_reserve)]
586 /// use std::collections::CollectionAllocErr;
587 /// use std::collections::VecDeque;
589 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
590 /// let mut output = VecDeque::new();
592 /// // Pre-reserve the memory, exiting if we can't
593 /// output.try_reserve_exact(data.len())?;
595 /// // Now we know this can't OOM in the middle of our complex work
596 /// output.extend(data.iter().map(|&val| {
597 /// val * 2 + 5 // very complicated
602 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
604 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
605 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
606 self.try_reserve(additional)
609 /// Tries to reserve capacity for at least `additional` more elements to be inserted
610 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
611 /// frequent reallocations. After calling `reserve`, capacity will be
612 /// greater than or equal to `self.len() + additional`. Does nothing if
613 /// capacity is already sufficient.
617 /// If the capacity overflows, or the allocator reports a failure, then an error
623 /// #![feature(try_reserve)]
624 /// use std::collections::CollectionAllocErr;
625 /// use std::collections::VecDeque;
627 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
628 /// let mut output = VecDeque::new();
630 /// // Pre-reserve the memory, exiting if we can't
631 /// output.try_reserve(data.len())?;
633 /// // Now we know this can't OOM in the middle of our complex work
634 /// output.extend(data.iter().map(|&val| {
635 /// val * 2 + 5 // very complicated
640 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
642 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
643 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
644 let old_cap = self.cap();
645 let used_cap = self.len() + 1;
646 let new_cap = used_cap.checked_add(additional)
647 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
648 .ok_or(CollectionAllocErr::CapacityOverflow)?;
650 if new_cap > old_cap {
651 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
653 self.handle_cap_increase(old_cap);
659 /// Shrinks the capacity of the `VecDeque` as much as possible.
661 /// It will drop down as close as possible to the length but the allocator may still inform the
662 /// `VecDeque` that there is space for a few more elements.
667 /// use std::collections::VecDeque;
669 /// let mut buf = VecDeque::with_capacity(15);
670 /// buf.extend(0..4);
671 /// assert_eq!(buf.capacity(), 15);
672 /// buf.shrink_to_fit();
673 /// assert!(buf.capacity() >= 4);
675 #[stable(feature = "deque_extras_15", since = "1.5.0")]
676 pub fn shrink_to_fit(&mut self) {
680 /// Shrinks the capacity of the `VecDeque` with a lower bound.
682 /// The capacity will remain at least as large as both the length
683 /// and the supplied value.
685 /// Panics if the current capacity is smaller than the supplied
686 /// minimum capacity.
691 /// #![feature(shrink_to)]
692 /// use std::collections::VecDeque;
694 /// let mut buf = VecDeque::with_capacity(15);
695 /// buf.extend(0..4);
696 /// assert_eq!(buf.capacity(), 15);
697 /// buf.shrink_to(6);
698 /// assert!(buf.capacity() >= 6);
699 /// buf.shrink_to(0);
700 /// assert!(buf.capacity() >= 4);
702 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
703 pub fn shrink_to(&mut self, min_capacity: usize) {
704 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
706 // +1 since the ringbuffer always leaves one space empty
707 // len + 1 can't overflow for an existing, well-formed ringbuffer.
708 let target_cap = cmp::max(
709 cmp::max(min_capacity, self.len()) + 1,
711 ).next_power_of_two();
713 if target_cap < self.cap() {
714 // There are three cases of interest:
715 // All elements are out of desired bounds
716 // Elements are contiguous, and head is out of desired bounds
717 // Elements are discontiguous, and tail is out of desired bounds
719 // At all other times, element positions are unaffected.
721 // Indicates that elements at the head should be moved.
722 let head_outside = self.head == 0 || self.head >= target_cap;
723 // Move elements from out of desired bounds (positions after target_cap)
724 if self.tail >= target_cap && head_outside {
726 // [. . . . . . . . o o o o o o o . ]
728 // [o o o o o o o . ]
730 self.copy_nonoverlapping(0, self.tail, self.len());
732 self.head = self.len();
734 } else if self.tail != 0 && self.tail < target_cap && head_outside {
736 // [. . . o o o o o o o . . . . . . ]
738 // [o o . o o o o o ]
739 let len = self.wrap_sub(self.head, target_cap);
741 self.copy_nonoverlapping(0, target_cap, len);
744 debug_assert!(self.head < self.tail);
745 } else if self.tail >= target_cap {
747 // [o o o o o . . . . . . . . . o o ]
749 // [o o o o o . o o ]
750 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
751 let len = self.cap() - self.tail;
752 let new_tail = target_cap - len;
754 self.copy_nonoverlapping(new_tail, self.tail, len);
756 self.tail = new_tail;
757 debug_assert!(self.head < self.tail);
760 self.buf.shrink_to_fit(target_cap);
762 debug_assert!(self.head < self.cap());
763 debug_assert!(self.tail < self.cap());
764 debug_assert!(self.cap().count_ones() == 1);
768 /// Shortens the `VecDeque`, dropping excess elements from the back.
770 /// If `len` is greater than the `VecDeque`'s current length, this has no
776 /// use std::collections::VecDeque;
778 /// let mut buf = VecDeque::new();
779 /// buf.push_back(5);
780 /// buf.push_back(10);
781 /// buf.push_back(15);
782 /// assert_eq!(buf, [5, 10, 15]);
784 /// assert_eq!(buf, [5]);
786 #[stable(feature = "deque_extras", since = "1.16.0")]
787 pub fn truncate(&mut self, len: usize) {
788 for _ in len..self.len() {
793 /// Returns a front-to-back iterator.
798 /// use std::collections::VecDeque;
800 /// let mut buf = VecDeque::new();
801 /// buf.push_back(5);
802 /// buf.push_back(3);
803 /// buf.push_back(4);
804 /// let b: &[_] = &[&5, &3, &4];
805 /// let c: Vec<&i32> = buf.iter().collect();
806 /// assert_eq!(&c[..], b);
808 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn iter(&self) -> Iter<T> {
813 ring: unsafe { self.buffer_as_slice() },
817 /// Returns a front-to-back iterator that returns mutable references.
822 /// use std::collections::VecDeque;
824 /// let mut buf = VecDeque::new();
825 /// buf.push_back(5);
826 /// buf.push_back(3);
827 /// buf.push_back(4);
828 /// for num in buf.iter_mut() {
831 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
832 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
834 #[stable(feature = "rust1", since = "1.0.0")]
835 pub fn iter_mut(&mut self) -> IterMut<T> {
839 ring: unsafe { self.buffer_as_mut_slice() },
843 /// Returns a pair of slices which contain, in order, the contents of the
849 /// use std::collections::VecDeque;
851 /// let mut vector = VecDeque::new();
853 /// vector.push_back(0);
854 /// vector.push_back(1);
855 /// vector.push_back(2);
857 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
859 /// vector.push_front(10);
860 /// vector.push_front(9);
862 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
865 #[stable(feature = "deque_extras_15", since = "1.5.0")]
866 pub fn as_slices(&self) -> (&[T], &[T]) {
868 let buf = self.buffer_as_slice();
869 RingSlices::ring_slices(buf, self.head, self.tail)
873 /// Returns a pair of slices which contain, in order, the contents of the
879 /// use std::collections::VecDeque;
881 /// let mut vector = VecDeque::new();
883 /// vector.push_back(0);
884 /// vector.push_back(1);
886 /// vector.push_front(10);
887 /// vector.push_front(9);
889 /// vector.as_mut_slices().0[0] = 42;
890 /// vector.as_mut_slices().1[0] = 24;
891 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
894 #[stable(feature = "deque_extras_15", since = "1.5.0")]
895 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
897 let head = self.head;
898 let tail = self.tail;
899 let buf = self.buffer_as_mut_slice();
900 RingSlices::ring_slices(buf, head, tail)
904 /// Returns the number of elements in the `VecDeque`.
909 /// use std::collections::VecDeque;
911 /// let mut v = VecDeque::new();
912 /// assert_eq!(v.len(), 0);
914 /// assert_eq!(v.len(), 1);
916 #[stable(feature = "rust1", since = "1.0.0")]
917 pub fn len(&self) -> usize {
918 count(self.tail, self.head, self.cap())
921 /// Returns `true` if the `VecDeque` is empty.
926 /// use std::collections::VecDeque;
928 /// let mut v = VecDeque::new();
929 /// assert!(v.is_empty());
931 /// assert!(!v.is_empty());
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn is_empty(&self) -> bool {
935 self.tail == self.head
938 /// Create a draining iterator that removes the specified range in the
939 /// `VecDeque` and yields the removed items.
941 /// Note 1: The element range is removed even if the iterator is not
942 /// consumed until the end.
944 /// Note 2: It is unspecified how many elements are removed from the deque,
945 /// if the `Drain` value is not dropped, but the borrow it holds expires
946 /// (eg. due to mem::forget).
950 /// Panics if the starting point is greater than the end point or if
951 /// the end point is greater than the length of the vector.
956 /// use std::collections::VecDeque;
958 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
959 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
960 /// assert_eq!(drained, [3]);
961 /// assert_eq!(v, [1, 2]);
963 /// // A full range clears all contents
965 /// assert!(v.is_empty());
968 #[stable(feature = "drain", since = "1.6.0")]
969 pub fn drain<R>(&mut self, range: R) -> Drain<T>
970 where R: RangeBounds<usize>
974 // When the Drain is first created, the source deque is shortened to
975 // make sure no uninitialized or moved-from elements are accessible at
976 // all if the Drain's destructor never gets to run.
978 // Drain will ptr::read out the values to remove.
979 // When finished, the remaining data will be copied back to cover the hole,
980 // and the head/tail values will be restored correctly.
982 let len = self.len();
983 let start = match range.start_bound() {
985 Excluded(&n) => n + 1,
988 let end = match range.end_bound() {
989 Included(&n) => n + 1,
993 assert!(start <= end, "drain lower bound was too large");
994 assert!(end <= len, "drain upper bound was too large");
996 // The deque's elements are parted into three segments:
997 // * self.tail -> drain_tail
998 // * drain_tail -> drain_head
999 // * drain_head -> self.head
1001 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1003 // We store drain_tail as self.head, and drain_head and self.head as
1004 // after_tail and after_head respectively on the Drain. This also
1005 // truncates the effective array such that if the Drain is leaked, we
1006 // have forgotten about the potentially moved values after the start of
1010 // [. . . o o x x o o . . .]
1012 let drain_tail = self.wrap_add(self.tail, start);
1013 let drain_head = self.wrap_add(self.tail, end);
1014 let head = self.head;
1016 // "forget" about the values after the start of the drain until after
1017 // the drain is complete and the Drain destructor is run.
1018 self.head = drain_tail;
1021 deque: NonNull::from(&mut *self),
1022 after_tail: drain_head,
1027 ring: unsafe { self.buffer_as_slice() },
1032 /// Clears the `VecDeque`, removing all values.
1037 /// use std::collections::VecDeque;
1039 /// let mut v = VecDeque::new();
1042 /// assert!(v.is_empty());
1044 #[stable(feature = "rust1", since = "1.0.0")]
1046 pub fn clear(&mut self) {
1050 /// Returns `true` if the `VecDeque` contains an element equal to the
1056 /// use std::collections::VecDeque;
1058 /// let mut vector: VecDeque<u32> = VecDeque::new();
1060 /// vector.push_back(0);
1061 /// vector.push_back(1);
1063 /// assert_eq!(vector.contains(&1), true);
1064 /// assert_eq!(vector.contains(&10), false);
1066 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1067 pub fn contains(&self, x: &T) -> bool
1068 where T: PartialEq<T>
1070 let (a, b) = self.as_slices();
1071 a.contains(x) || b.contains(x)
1074 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1080 /// use std::collections::VecDeque;
1082 /// let mut d = VecDeque::new();
1083 /// assert_eq!(d.front(), None);
1087 /// assert_eq!(d.front(), Some(&1));
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 pub fn front(&self) -> Option<&T> {
1091 if !self.is_empty() {
1098 /// Provides a mutable reference to the front element, or `None` if the
1099 /// `VecDeque` is empty.
1104 /// use std::collections::VecDeque;
1106 /// let mut d = VecDeque::new();
1107 /// assert_eq!(d.front_mut(), None);
1111 /// match d.front_mut() {
1112 /// Some(x) => *x = 9,
1115 /// assert_eq!(d.front(), Some(&9));
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 pub fn front_mut(&mut self) -> Option<&mut T> {
1119 if !self.is_empty() {
1126 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1132 /// use std::collections::VecDeque;
1134 /// let mut d = VecDeque::new();
1135 /// assert_eq!(d.back(), None);
1139 /// assert_eq!(d.back(), Some(&2));
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 pub fn back(&self) -> Option<&T> {
1143 if !self.is_empty() {
1144 Some(&self[self.len() - 1])
1150 /// Provides a mutable reference to the back element, or `None` if the
1151 /// `VecDeque` is empty.
1156 /// use std::collections::VecDeque;
1158 /// let mut d = VecDeque::new();
1159 /// assert_eq!(d.back(), None);
1163 /// match d.back_mut() {
1164 /// Some(x) => *x = 9,
1167 /// assert_eq!(d.back(), Some(&9));
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 pub fn back_mut(&mut self) -> Option<&mut T> {
1171 let len = self.len();
1172 if !self.is_empty() {
1173 Some(&mut self[len - 1])
1179 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1185 /// use std::collections::VecDeque;
1187 /// let mut d = VecDeque::new();
1191 /// assert_eq!(d.pop_front(), Some(1));
1192 /// assert_eq!(d.pop_front(), Some(2));
1193 /// assert_eq!(d.pop_front(), None);
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 pub fn pop_front(&mut self) -> Option<T> {
1197 if self.is_empty() {
1200 let tail = self.tail;
1201 self.tail = self.wrap_add(self.tail, 1);
1202 unsafe { Some(self.buffer_read(tail)) }
1206 /// Prepends an element to the `VecDeque`.
1211 /// use std::collections::VecDeque;
1213 /// let mut d = VecDeque::new();
1214 /// d.push_front(1);
1215 /// d.push_front(2);
1216 /// assert_eq!(d.front(), Some(&2));
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub fn push_front(&mut self, value: T) {
1220 self.grow_if_necessary();
1222 self.tail = self.wrap_sub(self.tail, 1);
1223 let tail = self.tail;
1225 self.buffer_write(tail, value);
1229 /// Appends an element to the back of the `VecDeque`.
1234 /// use std::collections::VecDeque;
1236 /// let mut buf = VecDeque::new();
1237 /// buf.push_back(1);
1238 /// buf.push_back(3);
1239 /// assert_eq!(3, *buf.back().unwrap());
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 pub fn push_back(&mut self, value: T) {
1243 self.grow_if_necessary();
1245 let head = self.head;
1246 self.head = self.wrap_add(self.head, 1);
1247 unsafe { self.buffer_write(head, value) }
1250 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1256 /// use std::collections::VecDeque;
1258 /// let mut buf = VecDeque::new();
1259 /// assert_eq!(buf.pop_back(), None);
1260 /// buf.push_back(1);
1261 /// buf.push_back(3);
1262 /// assert_eq!(buf.pop_back(), Some(3));
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 pub fn pop_back(&mut self) -> Option<T> {
1266 if self.is_empty() {
1269 self.head = self.wrap_sub(self.head, 1);
1270 let head = self.head;
1271 unsafe { Some(self.buffer_read(head)) }
1276 fn is_contiguous(&self) -> bool {
1277 self.tail <= self.head
1280 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1283 /// This does not preserve ordering, but is O(1).
1285 /// Returns `None` if `index` is out of bounds.
1287 /// Element at index 0 is the front of the queue.
1292 /// use std::collections::VecDeque;
1294 /// let mut buf = VecDeque::new();
1295 /// assert_eq!(buf.swap_remove_back(0), None);
1296 /// buf.push_back(1);
1297 /// buf.push_back(2);
1298 /// buf.push_back(3);
1299 /// assert_eq!(buf, [1, 2, 3]);
1301 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1302 /// assert_eq!(buf, [3, 2]);
1304 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1305 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1306 let length = self.len();
1307 if length > 0 && index < length - 1 {
1308 self.swap(index, length - 1);
1309 } else if index >= length {
1315 /// Removes an element from anywhere in the `VecDeque` and returns it,
1316 /// replacing it with the first element.
1318 /// This does not preserve ordering, but is O(1).
1320 /// Returns `None` if `index` is out of bounds.
1322 /// Element at index 0 is the front of the queue.
1327 /// use std::collections::VecDeque;
1329 /// let mut buf = VecDeque::new();
1330 /// assert_eq!(buf.swap_remove_front(0), None);
1331 /// buf.push_back(1);
1332 /// buf.push_back(2);
1333 /// buf.push_back(3);
1334 /// assert_eq!(buf, [1, 2, 3]);
1336 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1337 /// assert_eq!(buf, [2, 1]);
1339 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1340 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1341 let length = self.len();
1342 if length > 0 && index < length && index != 0 {
1343 self.swap(index, 0);
1344 } else if index >= length {
1350 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1351 /// greater than or equal to `index` towards the back.
1353 /// Element at index 0 is the front of the queue.
1357 /// Panics if `index` is greater than `VecDeque`'s length
1362 /// use std::collections::VecDeque;
1364 /// let mut vec_deque = VecDeque::new();
1365 /// vec_deque.push_back('a');
1366 /// vec_deque.push_back('b');
1367 /// vec_deque.push_back('c');
1368 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1370 /// vec_deque.insert(1, 'd');
1371 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1373 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1374 pub fn insert(&mut self, index: usize, value: T) {
1375 assert!(index <= self.len(), "index out of bounds");
1376 self.grow_if_necessary();
1378 // Move the least number of elements in the ring buffer and insert
1381 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1383 // There are three main cases:
1384 // Elements are contiguous
1385 // - special case when tail is 0
1386 // Elements are discontiguous and the insert is in the tail section
1387 // Elements are discontiguous and the insert is in the head section
1389 // For each of those there are two more cases:
1390 // Insert is closer to tail
1391 // Insert is closer to head
1393 // Key: H - self.head
1395 // o - Valid element
1396 // I - Insertion element
1397 // A - The element that should be after the insertion point
1398 // M - Indicates element was moved
1400 let idx = self.wrap_add(self.tail, index);
1402 let distance_to_tail = index;
1403 let distance_to_head = self.len() - index;
1405 let contiguous = self.is_contiguous();
1407 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1408 (true, true, _) if index == 0 => {
1413 // [A o o o o o o . . . . . . . . .]
1416 // [A o o o o o o o . . . . . I]
1419 self.tail = self.wrap_sub(self.tail, 1);
1421 (true, true, _) => {
1423 // contiguous, insert closer to tail:
1426 // [. . . o o A o o o o . . . . . .]
1429 // [. . o o I A o o o o . . . . . .]
1432 // contiguous, insert closer to tail and tail is 0:
1436 // [o o A o o o o . . . . . . . . .]
1439 // [o I A o o o o o . . . . . . . o]
1442 let new_tail = self.wrap_sub(self.tail, 1);
1444 self.copy(new_tail, self.tail, 1);
1445 // Already moved the tail, so we only copy `index - 1` elements.
1446 self.copy(self.tail, self.tail + 1, index - 1);
1448 self.tail = new_tail;
1451 (true, false, _) => {
1453 // contiguous, insert closer to head:
1456 // [. . . o o o o A o o . . . . . .]
1459 // [. . . o o o o I A o o . . . . .]
1462 self.copy(idx + 1, idx, self.head - idx);
1463 self.head = self.wrap_add(self.head, 1);
1466 (false, true, true) => {
1468 // discontiguous, insert closer to tail, tail section:
1471 // [o o o o o o . . . . . o o A o o]
1474 // [o o o o o o . . . . o o I A o o]
1477 self.copy(self.tail - 1, self.tail, index);
1481 (false, false, true) => {
1483 // discontiguous, insert closer to head, tail section:
1486 // [o o . . . . . . . o o o o o A o]
1489 // [o o o . . . . . . o o o o o I A]
1492 // copy elements up to new head
1493 self.copy(1, 0, self.head);
1495 // copy last element into empty spot at bottom of buffer
1496 self.copy(0, self.cap() - 1, 1);
1498 // move elements from idx to end forward not including ^ element
1499 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1504 (false, true, false) if idx == 0 => {
1506 // discontiguous, insert is closer to tail, head section,
1507 // and is at index zero in the internal buffer:
1510 // [A o o o o o o o o o . . . o o o]
1513 // [A o o o o o o o o o . . o o o I]
1516 // copy elements up to new tail
1517 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1519 // copy last element into empty spot at bottom of buffer
1520 self.copy(self.cap() - 1, 0, 1);
1525 (false, true, false) => {
1527 // discontiguous, insert closer to tail, head section:
1530 // [o o o A o o o o o o . . . o o o]
1533 // [o o I A o o o o o o . . o o o o]
1536 // copy elements up to new tail
1537 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1539 // copy last element into empty spot at bottom of buffer
1540 self.copy(self.cap() - 1, 0, 1);
1542 // move elements from idx-1 to end forward not including ^ element
1543 self.copy(0, 1, idx - 1);
1548 (false, false, false) => {
1550 // discontiguous, insert closer to head, head section:
1553 // [o o o o A o o . . . . . . o o o]
1556 // [o o o o I A o o . . . . . o o o]
1559 self.copy(idx + 1, idx, self.head - idx);
1565 // tail might've been changed so we need to recalculate
1566 let new_idx = self.wrap_add(self.tail, index);
1568 self.buffer_write(new_idx, value);
1572 /// Removes and returns the element at `index` from the `VecDeque`.
1573 /// Whichever end is closer to the removal point will be moved to make
1574 /// room, and all the affected elements will be moved to new positions.
1575 /// Returns `None` if `index` is out of bounds.
1577 /// Element at index 0 is the front of the queue.
1582 /// use std::collections::VecDeque;
1584 /// let mut buf = VecDeque::new();
1585 /// buf.push_back(1);
1586 /// buf.push_back(2);
1587 /// buf.push_back(3);
1588 /// assert_eq!(buf, [1, 2, 3]);
1590 /// assert_eq!(buf.remove(1), Some(2));
1591 /// assert_eq!(buf, [1, 3]);
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 pub fn remove(&mut self, index: usize) -> Option<T> {
1595 if self.is_empty() || self.len() <= index {
1599 // There are three main cases:
1600 // Elements are contiguous
1601 // Elements are discontiguous and the removal is in the tail section
1602 // Elements are discontiguous and the removal is in the head section
1603 // - special case when elements are technically contiguous,
1604 // but self.head = 0
1606 // For each of those there are two more cases:
1607 // Insert is closer to tail
1608 // Insert is closer to head
1610 // Key: H - self.head
1612 // o - Valid element
1613 // x - Element marked for removal
1614 // R - Indicates element that is being removed
1615 // M - Indicates element was moved
1617 let idx = self.wrap_add(self.tail, index);
1619 let elem = unsafe { Some(self.buffer_read(idx)) };
1621 let distance_to_tail = index;
1622 let distance_to_head = self.len() - index;
1624 let contiguous = self.is_contiguous();
1626 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1627 (true, true, _) => {
1629 // contiguous, remove closer to tail:
1632 // [. . . o o x o o o o . . . . . .]
1635 // [. . . . o o o o o o . . . . . .]
1638 self.copy(self.tail + 1, self.tail, index);
1642 (true, false, _) => {
1644 // contiguous, remove closer to head:
1647 // [. . . o o o o x o o . . . . . .]
1650 // [. . . o o o o o o . . . . . . .]
1653 self.copy(idx, idx + 1, self.head - idx - 1);
1657 (false, true, true) => {
1659 // discontiguous, remove closer to tail, tail section:
1662 // [o o o o o o . . . . . o o x o o]
1665 // [o o o o o o . . . . . . o o o o]
1668 self.copy(self.tail + 1, self.tail, index);
1669 self.tail = self.wrap_add(self.tail, 1);
1672 (false, false, false) => {
1674 // discontiguous, remove closer to head, head section:
1677 // [o o o o x o o . . . . . . o o o]
1680 // [o o o o o o . . . . . . . o o o]
1683 self.copy(idx, idx + 1, self.head - idx - 1);
1687 (false, false, true) => {
1689 // discontiguous, remove closer to head, tail section:
1692 // [o o o . . . . . . o o o o o x o]
1695 // [o o . . . . . . . o o o o o o o]
1698 // or quasi-discontiguous, remove next to head, tail section:
1701 // [. . . . . . . . . o o o o o x o]
1704 // [. . . . . . . . . o o o o o o .]
1707 // draw in elements in the tail section
1708 self.copy(idx, idx + 1, self.cap() - idx - 1);
1710 // Prevents underflow.
1712 // copy first element into empty spot
1713 self.copy(self.cap() - 1, 0, 1);
1715 // move elements in the head section backwards
1716 self.copy(0, 1, self.head - 1);
1719 self.head = self.wrap_sub(self.head, 1);
1722 (false, true, false) => {
1724 // discontiguous, remove closer to tail, head section:
1727 // [o o x o o o o o o o . . . o o o]
1730 // [o o o o o o o o o o . . . . o o]
1733 // draw in elements up to idx
1734 self.copy(1, 0, idx);
1736 // copy last element into empty spot
1737 self.copy(0, self.cap() - 1, 1);
1739 // move elements from tail to end forward, excluding the last one
1740 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1742 self.tail = self.wrap_add(self.tail, 1);
1750 /// Splits the `VecDeque` into two at the given index.
1752 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1753 /// and the returned `VecDeque` contains elements `[at, len)`.
1755 /// Note that the capacity of `self` does not change.
1757 /// Element at index 0 is the front of the queue.
1761 /// Panics if `at > len`.
1766 /// use std::collections::VecDeque;
1768 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1769 /// let buf2 = buf.split_off(1);
1770 /// assert_eq!(buf, [1]);
1771 /// assert_eq!(buf2, [2, 3]);
1774 #[stable(feature = "split_off", since = "1.4.0")]
1775 pub fn split_off(&mut self, at: usize) -> Self {
1776 let len = self.len();
1777 assert!(at <= len, "`at` out of bounds");
1779 let other_len = len - at;
1780 let mut other = VecDeque::with_capacity(other_len);
1783 let (first_half, second_half) = self.as_slices();
1785 let first_len = first_half.len();
1786 let second_len = second_half.len();
1788 // `at` lies in the first half.
1789 let amount_in_first = first_len - at;
1791 ptr::copy_nonoverlapping(first_half.as_ptr().add(at),
1795 // just take all of the second half.
1796 ptr::copy_nonoverlapping(second_half.as_ptr(),
1797 other.ptr().add(amount_in_first),
1800 // `at` lies in the second half, need to factor in the elements we skipped
1801 // in the first half.
1802 let offset = at - first_len;
1803 let amount_in_second = second_len - offset;
1804 ptr::copy_nonoverlapping(second_half.as_ptr().add(offset),
1810 // Cleanup where the ends of the buffers are
1811 self.head = self.wrap_sub(self.head, other_len);
1812 other.head = other.wrap_index(other_len);
1817 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1821 /// Panics if the new number of elements in self overflows a `usize`.
1826 /// use std::collections::VecDeque;
1828 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1829 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1830 /// buf.append(&mut buf2);
1831 /// assert_eq!(buf, [1, 2, 3, 4]);
1832 /// assert_eq!(buf2, []);
1835 #[stable(feature = "append", since = "1.4.0")]
1836 pub fn append(&mut self, other: &mut Self) {
1838 self.extend(other.drain(..));
1841 /// Retains only the elements specified by the predicate.
1843 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1844 /// This method operates in place and preserves the order of the retained
1850 /// use std::collections::VecDeque;
1852 /// let mut buf = VecDeque::new();
1853 /// buf.extend(1..5);
1854 /// buf.retain(|&x| x%2 == 0);
1855 /// assert_eq!(buf, [2, 4]);
1857 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1858 pub fn retain<F>(&mut self, mut f: F)
1859 where F: FnMut(&T) -> bool
1861 let len = self.len();
1867 self.swap(i - del, i);
1871 self.truncate(len - del);
1875 // This may panic or abort
1877 fn grow_if_necessary(&mut self) {
1879 let old_cap = self.cap();
1882 self.handle_cap_increase(old_cap);
1884 debug_assert!(!self.is_full());
1889 impl<T: Clone> VecDeque<T> {
1890 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1891 /// either by removing excess elements from the back or by appending clones of `value`
1897 /// use std::collections::VecDeque;
1899 /// let mut buf = VecDeque::new();
1900 /// buf.push_back(5);
1901 /// buf.push_back(10);
1902 /// buf.push_back(15);
1903 /// assert_eq!(buf, [5, 10, 15]);
1905 /// buf.resize(2, 0);
1906 /// assert_eq!(buf, [5, 10]);
1908 /// buf.resize(5, 20);
1909 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
1911 #[stable(feature = "deque_extras", since = "1.16.0")]
1912 pub fn resize(&mut self, new_len: usize, value: T) {
1913 let len = self.len();
1916 self.extend(repeat(value).take(new_len - len))
1918 self.truncate(new_len);
1923 /// Returns the index in the underlying buffer for a given logical element index.
1925 fn wrap_index(index: usize, size: usize) -> usize {
1926 // size is always a power of 2
1927 debug_assert!(size.is_power_of_two());
1931 /// Returns the two slices that cover the `VecDeque`'s valid range
1932 trait RingSlices: Sized {
1933 fn slice(self, from: usize, to: usize) -> Self;
1934 fn split_at(self, i: usize) -> (Self, Self);
1936 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
1937 let contiguous = tail <= head;
1939 let (empty, buf) = buf.split_at(0);
1940 (buf.slice(tail, head), empty)
1942 let (mid, right) = buf.split_at(tail);
1943 let (left, _) = mid.split_at(head);
1949 impl<'a, T> RingSlices for &'a [T] {
1950 fn slice(self, from: usize, to: usize) -> Self {
1953 fn split_at(self, i: usize) -> (Self, Self) {
1958 impl<'a, T> RingSlices for &'a mut [T] {
1959 fn slice(self, from: usize, to: usize) -> Self {
1962 fn split_at(self, i: usize) -> (Self, Self) {
1963 (*self).split_at_mut(i)
1967 /// Calculate the number of elements left to be read in the buffer
1969 fn count(tail: usize, head: usize, size: usize) -> usize {
1970 // size is always a power of 2
1971 (head.wrapping_sub(tail)) & (size - 1)
1974 /// An iterator over the elements of a `VecDeque`.
1976 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
1977 /// documentation for more.
1979 /// [`iter`]: struct.VecDeque.html#method.iter
1980 /// [`VecDeque`]: struct.VecDeque.html
1981 #[stable(feature = "rust1", since = "1.0.0")]
1982 pub struct Iter<'a, T: 'a> {
1988 #[stable(feature = "collection_debug", since = "1.17.0")]
1989 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1990 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1991 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
1992 f.debug_tuple("Iter")
1999 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl<'a, T> Clone for Iter<'a, T> {
2002 fn clone(&self) -> Iter<'a, T> {
2011 #[stable(feature = "rust1", since = "1.0.0")]
2012 impl<'a, T> Iterator for Iter<'a, T> {
2016 fn next(&mut self) -> Option<&'a T> {
2017 if self.tail == self.head {
2020 let tail = self.tail;
2021 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2022 unsafe { Some(self.ring.get_unchecked(tail)) }
2026 fn size_hint(&self) -> (usize, Option<usize>) {
2027 let len = count(self.tail, self.head, self.ring.len());
2031 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2032 where F: FnMut(Acc, Self::Item) -> Acc
2034 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2035 accum = front.iter().fold(accum, &mut f);
2036 back.iter().fold(accum, &mut f)
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2043 fn next_back(&mut self) -> Option<&'a T> {
2044 if self.tail == self.head {
2047 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2048 unsafe { Some(self.ring.get_unchecked(self.head)) }
2051 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2052 where F: FnMut(Acc, Self::Item) -> Acc
2054 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2055 accum = back.iter().rfold(accum, &mut f);
2056 front.iter().rfold(accum, &mut f)
2060 #[stable(feature = "rust1", since = "1.0.0")]
2061 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
2062 fn is_empty(&self) -> bool {
2063 self.head == self.tail
2067 #[stable(feature = "fused", since = "1.26.0")]
2068 impl<'a, T> FusedIterator for Iter<'a, T> {}
2071 /// A mutable iterator over the elements of a `VecDeque`.
2073 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2074 /// documentation for more.
2076 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2077 /// [`VecDeque`]: struct.VecDeque.html
2078 #[stable(feature = "rust1", since = "1.0.0")]
2079 pub struct IterMut<'a, T: 'a> {
2085 #[stable(feature = "collection_debug", since = "1.17.0")]
2086 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2087 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2088 let (front, back) = RingSlices::ring_slices(&*self.ring, self.head, self.tail);
2089 f.debug_tuple("IterMut")
2096 #[stable(feature = "rust1", since = "1.0.0")]
2097 impl<'a, T> Iterator for IterMut<'a, T> {
2098 type Item = &'a mut T;
2101 fn next(&mut self) -> Option<&'a mut T> {
2102 if self.tail == self.head {
2105 let tail = self.tail;
2106 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2109 let elem = self.ring.get_unchecked_mut(tail);
2110 Some(&mut *(elem as *mut _))
2115 fn size_hint(&self) -> (usize, Option<usize>) {
2116 let len = count(self.tail, self.head, self.ring.len());
2120 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2121 where F: FnMut(Acc, Self::Item) -> Acc
2123 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2124 accum = front.iter_mut().fold(accum, &mut f);
2125 back.iter_mut().fold(accum, &mut f)
2129 #[stable(feature = "rust1", since = "1.0.0")]
2130 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2132 fn next_back(&mut self) -> Option<&'a mut T> {
2133 if self.tail == self.head {
2136 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2139 let elem = self.ring.get_unchecked_mut(self.head);
2140 Some(&mut *(elem as *mut _))
2144 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2145 where F: FnMut(Acc, Self::Item) -> Acc
2147 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2148 accum = back.iter_mut().rfold(accum, &mut f);
2149 front.iter_mut().rfold(accum, &mut f)
2153 #[stable(feature = "rust1", since = "1.0.0")]
2154 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
2155 fn is_empty(&self) -> bool {
2156 self.head == self.tail
2160 #[stable(feature = "fused", since = "1.26.0")]
2161 impl<'a, T> FusedIterator for IterMut<'a, T> {}
2163 /// An owning iterator over the elements of a `VecDeque`.
2165 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`][`VecDeque`]
2166 /// (provided by the `IntoIterator` trait). See its documentation for more.
2168 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2169 /// [`VecDeque`]: struct.VecDeque.html
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 pub struct IntoIter<T> {
2176 #[stable(feature = "collection_debug", since = "1.17.0")]
2177 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2178 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2179 f.debug_tuple("IntoIter")
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 impl<T> Iterator for IntoIter<T> {
2190 fn next(&mut self) -> Option<T> {
2191 self.inner.pop_front()
2195 fn size_hint(&self) -> (usize, Option<usize>) {
2196 let len = self.inner.len();
2201 #[stable(feature = "rust1", since = "1.0.0")]
2202 impl<T> DoubleEndedIterator for IntoIter<T> {
2204 fn next_back(&mut self) -> Option<T> {
2205 self.inner.pop_back()
2209 #[stable(feature = "rust1", since = "1.0.0")]
2210 impl<T> ExactSizeIterator for IntoIter<T> {
2211 fn is_empty(&self) -> bool {
2212 self.inner.is_empty()
2216 #[stable(feature = "fused", since = "1.26.0")]
2217 impl<T> FusedIterator for IntoIter<T> {}
2219 /// A draining iterator over the elements of a `VecDeque`.
2221 /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its
2222 /// documentation for more.
2224 /// [`drain`]: struct.VecDeque.html#method.drain
2225 /// [`VecDeque`]: struct.VecDeque.html
2226 #[stable(feature = "drain", since = "1.6.0")]
2227 pub struct Drain<'a, T: 'a> {
2231 deque: NonNull<VecDeque<T>>,
2234 #[stable(feature = "collection_debug", since = "1.17.0")]
2235 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2236 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2237 f.debug_tuple("Drain")
2238 .field(&self.after_tail)
2239 .field(&self.after_head)
2245 #[stable(feature = "drain", since = "1.6.0")]
2246 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2247 #[stable(feature = "drain", since = "1.6.0")]
2248 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2250 #[stable(feature = "drain", since = "1.6.0")]
2251 impl<'a, T: 'a> Drop for Drain<'a, T> {
2252 fn drop(&mut self) {
2253 self.for_each(drop);
2255 let source_deque = unsafe { self.deque.as_mut() };
2257 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2260 // [. . . o o x x o o . . .]
2262 let orig_tail = source_deque.tail;
2263 let drain_tail = source_deque.head;
2264 let drain_head = self.after_tail;
2265 let orig_head = self.after_head;
2267 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2268 let head_len = count(drain_head, orig_head, source_deque.cap());
2270 // Restore the original head value
2271 source_deque.head = orig_head;
2273 match (tail_len, head_len) {
2275 source_deque.head = 0;
2276 source_deque.tail = 0;
2279 source_deque.tail = drain_head;
2282 source_deque.head = drain_tail;
2285 if tail_len <= head_len {
2286 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2287 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2289 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2290 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2297 #[stable(feature = "drain", since = "1.6.0")]
2298 impl<'a, T: 'a> Iterator for Drain<'a, T> {
2302 fn next(&mut self) -> Option<T> {
2303 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2307 fn size_hint(&self) -> (usize, Option<usize>) {
2308 self.iter.size_hint()
2312 #[stable(feature = "drain", since = "1.6.0")]
2313 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
2315 fn next_back(&mut self) -> Option<T> {
2316 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2320 #[stable(feature = "drain", since = "1.6.0")]
2321 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
2323 #[stable(feature = "fused", since = "1.26.0")]
2324 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
2326 #[stable(feature = "rust1", since = "1.0.0")]
2327 impl<A: PartialEq> PartialEq for VecDeque<A> {
2328 fn eq(&self, other: &VecDeque<A>) -> bool {
2329 if self.len() != other.len() {
2332 let (sa, sb) = self.as_slices();
2333 let (oa, ob) = other.as_slices();
2334 if sa.len() == oa.len() {
2335 sa == oa && sb == ob
2336 } else if sa.len() < oa.len() {
2337 // Always divisible in three sections, for example:
2338 // self: [a b c|d e f]
2339 // other: [0 1 2 3|4 5]
2340 // front = 3, mid = 1,
2341 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2342 let front = sa.len();
2343 let mid = oa.len() - front;
2345 let (oa_front, oa_mid) = oa.split_at(front);
2346 let (sb_mid, sb_back) = sb.split_at(mid);
2347 debug_assert_eq!(sa.len(), oa_front.len());
2348 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2349 debug_assert_eq!(sb_back.len(), ob.len());
2350 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2352 let front = oa.len();
2353 let mid = sa.len() - front;
2355 let (sa_front, sa_mid) = sa.split_at(front);
2356 let (ob_mid, ob_back) = ob.split_at(mid);
2357 debug_assert_eq!(sa_front.len(), oa.len());
2358 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2359 debug_assert_eq!(sb.len(), ob_back.len());
2360 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2365 #[stable(feature = "rust1", since = "1.0.0")]
2366 impl<A: Eq> Eq for VecDeque<A> {}
2368 macro_rules! __impl_slice_eq1 {
2369 ($Lhs: ty, $Rhs: ty) => {
2370 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2372 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2373 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2374 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2375 fn eq(&self, other: &$Rhs) -> bool {
2376 if self.len() != other.len() {
2379 let (sa, sb) = self.as_slices();
2380 let (oa, ob) = other[..].split_at(sa.len());
2381 sa == oa && sb == ob
2387 __impl_slice_eq1! { VecDeque<A>, Vec<B> }
2388 __impl_slice_eq1! { VecDeque<A>, &'b [B] }
2389 __impl_slice_eq1! { VecDeque<A>, &'b mut [B] }
2391 macro_rules! array_impls {
2394 __impl_slice_eq1! { VecDeque<A>, [B; $N] }
2395 __impl_slice_eq1! { VecDeque<A>, &'b [B; $N] }
2396 __impl_slice_eq1! { VecDeque<A>, &'b mut [B; $N] }
2403 10 11 12 13 14 15 16 17 18 19
2404 20 21 22 23 24 25 26 27 28 29
2408 #[stable(feature = "rust1", since = "1.0.0")]
2409 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2410 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2411 self.iter().partial_cmp(other.iter())
2415 #[stable(feature = "rust1", since = "1.0.0")]
2416 impl<A: Ord> Ord for VecDeque<A> {
2418 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2419 self.iter().cmp(other.iter())
2423 #[stable(feature = "rust1", since = "1.0.0")]
2424 impl<A: Hash> Hash for VecDeque<A> {
2425 fn hash<H: Hasher>(&self, state: &mut H) {
2426 self.len().hash(state);
2427 let (a, b) = self.as_slices();
2428 Hash::hash_slice(a, state);
2429 Hash::hash_slice(b, state);
2433 #[stable(feature = "rust1", since = "1.0.0")]
2434 impl<A> Index<usize> for VecDeque<A> {
2438 fn index(&self, index: usize) -> &A {
2439 self.get(index).expect("Out of bounds access")
2443 #[stable(feature = "rust1", since = "1.0.0")]
2444 impl<A> IndexMut<usize> for VecDeque<A> {
2446 fn index_mut(&mut self, index: usize) -> &mut A {
2447 self.get_mut(index).expect("Out of bounds access")
2451 #[stable(feature = "rust1", since = "1.0.0")]
2452 impl<A> FromIterator<A> for VecDeque<A> {
2453 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2454 let iterator = iter.into_iter();
2455 let (lower, _) = iterator.size_hint();
2456 let mut deq = VecDeque::with_capacity(lower);
2457 deq.extend(iterator);
2462 #[stable(feature = "rust1", since = "1.0.0")]
2463 impl<T> IntoIterator for VecDeque<T> {
2465 type IntoIter = IntoIter<T>;
2467 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2469 fn into_iter(self) -> IntoIter<T> {
2470 IntoIter { inner: self }
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2477 type IntoIter = Iter<'a, T>;
2479 fn into_iter(self) -> Iter<'a, T> {
2484 #[stable(feature = "rust1", since = "1.0.0")]
2485 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2486 type Item = &'a mut T;
2487 type IntoIter = IterMut<'a, T>;
2489 fn into_iter(self) -> IterMut<'a, T> {
2494 #[stable(feature = "rust1", since = "1.0.0")]
2495 impl<A> Extend<A> for VecDeque<A> {
2496 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2498 self.push_back(elt);
2503 #[stable(feature = "extend_ref", since = "1.2.0")]
2504 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2505 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2506 self.extend(iter.into_iter().cloned());
2510 #[stable(feature = "rust1", since = "1.0.0")]
2511 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2513 f.debug_list().entries(self).finish()
2517 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2518 impl<T> From<Vec<T>> for VecDeque<T> {
2519 fn from(mut other: Vec<T>) -> Self {
2521 let other_buf = other.as_mut_ptr();
2522 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2523 let len = other.len();
2526 // We need to extend the buf if it's not a power of two, too small
2527 // or doesn't have at least one free space
2528 if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) ||
2529 (buf.cap() == len) {
2530 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2531 buf.reserve_exact(len, cap - len);
2543 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2544 impl<T> From<VecDeque<T>> for Vec<T> {
2545 fn from(other: VecDeque<T>) -> Self {
2547 let buf = other.buf.ptr();
2548 let len = other.len();
2549 let tail = other.tail;
2550 let head = other.head;
2551 let cap = other.cap();
2553 // Need to move the ring to the front of the buffer, as vec will expect this.
2554 if other.is_contiguous() {
2555 ptr::copy(buf.add(tail), buf, len);
2557 if (tail - head) >= cmp::min(cap - tail, head) {
2558 // There is enough free space in the centre for the shortest block so we can
2559 // do this in at most three copy moves.
2560 if (cap - tail) > head {
2561 // right hand block is the long one; move that enough for the left
2562 ptr::copy(buf.add(tail),
2563 buf.add(tail - head),
2565 // copy left in the end
2566 ptr::copy(buf, buf.add(cap - head), head);
2567 // shift the new thing to the start
2568 ptr::copy(buf.add(tail - head), buf, len);
2570 // left hand block is the long one, we can do it in two!
2571 ptr::copy(buf, buf.add(cap - tail), head);
2572 ptr::copy(buf.add(tail), buf, cap - tail);
2575 // Need to use N swaps to move the ring
2576 // We can use the space at the end of the ring as a temp store
2578 let mut left_edge: usize = 0;
2579 let mut right_edge: usize = tail;
2581 // The general problem looks like this
2582 // GHIJKLM...ABCDEF - before any swaps
2583 // ABCDEFM...GHIJKL - after 1 pass of swaps
2584 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2585 // - then restart the algorithm with a new (smaller) store
2586 // Sometimes the temp store is reached when the right edge is at the end
2587 // of the buffer - this means we've hit the right order with fewer swaps!
2590 // ABCDEF.. - after four only swaps we've finished
2592 while left_edge < len && right_edge != cap {
2593 let mut right_offset = 0;
2594 for i in left_edge..right_edge {
2595 right_offset = (i - left_edge) % (cap - right_edge);
2596 let src = right_edge + right_offset;
2597 ptr::swap(buf.add(i), buf.add(src));
2599 let n_ops = right_edge - left_edge;
2601 right_edge += right_offset + 1;
2607 let out = Vec::from_raw_parts(buf, len, cap);
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() {
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() {
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)
2974 let mut dst = VecDeque::new();
2975 dst.push_front(Box::new(1));
2976 dst.push_front(Box::new(2));
2977 assert_eq!(*dst.pop_back().unwrap(), 1);
2979 let mut src = VecDeque::new();
2980 src.push_front(Box::new(2));
2981 dst.append(&mut src);