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;
23 use core::iter::{repeat, FromIterator, FusedIterator};
25 use core::ops::Bound::{Excluded, Included, Unbounded};
26 use core::ops::{Index, IndexMut, RangeBounds};
28 use core::ptr::NonNull;
31 use core::hash::{Hash, Hasher};
34 use collections::CollectionAllocErr;
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().add(off))
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().add(off), 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().add(src),
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().add(src),
206 /// Copies all values from `src` to the back of `self`, wrapping around if needed.
210 /// The capacity must be sufficient to hold self.len() + src.len() elements.
211 /// If so, this function never panics.
213 unsafe fn copy_slice(&mut self, src: &[T]) {
214 /// This is guaranteed by `RawVec`.
215 debug_assert!(self.capacity() <= isize::MAX as usize);
217 let expected_new_len = self.len() + src.len();
218 debug_assert!(self.capacity() >= expected_new_len);
220 let dst_high_ptr = self.ptr().add(self.head);
221 let dst_high_len = self.cap() - self.head;
223 let split = cmp::min(src.len(), dst_high_len);
224 let (src_high, src_low) = src.split_at(split);
226 ptr::copy_nonoverlapping(src_high.as_ptr(), dst_high_ptr, src_high.len());
227 ptr::copy_nonoverlapping(src_low.as_ptr(), self.ptr(), src_low.len());
229 self.head = self.wrap_add(self.head, src.len());
230 debug_assert!(self.len() == expected_new_len);
233 /// Copies a potentially wrapping block of memory len long from src to dest.
234 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
235 /// most one continuous overlapping region between src and dest).
236 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
238 fn diff(a: usize, b: usize) -> usize {
239 if a <= b { b - a } else { a - b }
241 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
242 "wrc dst={} src={} len={} cap={}",
248 if src == dst || len == 0 {
252 let dst_after_src = self.wrap_sub(dst, src) < len;
254 let src_pre_wrap_len = self.cap() - src;
255 let dst_pre_wrap_len = self.cap() - dst;
256 let src_wraps = src_pre_wrap_len < len;
257 let dst_wraps = dst_pre_wrap_len < len;
259 match (dst_after_src, src_wraps, dst_wraps) {
260 (_, false, false) => {
261 // src doesn't wrap, dst doesn't wrap
264 // 1 [_ _ A A B B C C _]
265 // 2 [_ _ A A A A B B _]
268 self.copy(dst, src, len);
270 (false, false, true) => {
271 // dst before src, src doesn't wrap, dst wraps
274 // 1 [A A B B _ _ _ C C]
275 // 2 [A A B B _ _ _ A A]
276 // 3 [B B B B _ _ _ A A]
279 self.copy(dst, src, dst_pre_wrap_len);
280 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
282 (true, false, true) => {
283 // src before dst, src doesn't wrap, dst wraps
286 // 1 [C C _ _ _ A A B B]
287 // 2 [B B _ _ _ A A B B]
288 // 3 [B B _ _ _ A A A A]
291 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
292 self.copy(dst, src, dst_pre_wrap_len);
294 (false, true, false) => {
295 // dst before src, src wraps, dst doesn't wrap
298 // 1 [C C _ _ _ A A B B]
299 // 2 [C C _ _ _ B B B B]
300 // 3 [C C _ _ _ B B C C]
303 self.copy(dst, src, src_pre_wrap_len);
304 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
306 (true, true, false) => {
307 // src before dst, src wraps, dst doesn't wrap
310 // 1 [A A B B _ _ _ C C]
311 // 2 [A A A A _ _ _ C C]
312 // 3 [C C A A _ _ _ C C]
315 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
316 self.copy(dst, src, src_pre_wrap_len);
318 (false, true, true) => {
319 // dst before src, src wraps, dst wraps
322 // 1 [A B C D _ E F G H]
323 // 2 [A B C D _ E G H H]
324 // 3 [A B C D _ E G H A]
325 // 4 [B C C D _ E G H A]
328 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
329 let delta = dst_pre_wrap_len - src_pre_wrap_len;
330 self.copy(dst, src, src_pre_wrap_len);
331 self.copy(dst + src_pre_wrap_len, 0, delta);
332 self.copy(0, delta, len - dst_pre_wrap_len);
334 (true, true, true) => {
335 // src before dst, src wraps, dst wraps
338 // 1 [A B C D _ E F G H]
339 // 2 [A A B D _ E F G H]
340 // 3 [H A B D _ E F G H]
341 // 4 [H A B D _ E F F G]
344 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
345 let delta = src_pre_wrap_len - dst_pre_wrap_len;
346 self.copy(delta, 0, len - src_pre_wrap_len);
347 self.copy(0, self.cap() - delta, delta);
348 self.copy(dst, src, dst_pre_wrap_len);
353 /// Frobs the head and tail sections around to handle the fact that we
354 /// just reallocated. Unsafe because it trusts old_cap.
356 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
357 let new_cap = self.cap();
359 // Move the shortest contiguous section of the ring buffer
361 // [o o o o o o o . ]
363 // A [o o o o o o o . . . . . . . . . ]
365 // [o o . o o o o o ]
367 // B [. . . o o o o o o o . . . . . . ]
369 // [o o o o o . o o ]
371 // C [o o o o o . . . . . . . . . o o ]
373 if self.tail <= self.head {
376 } else if self.head < old_cap - self.tail {
378 self.copy_nonoverlapping(old_cap, 0, self.head);
379 self.head += old_cap;
380 debug_assert!(self.head > self.tail);
383 let new_tail = new_cap - (old_cap - self.tail);
384 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
385 self.tail = new_tail;
386 debug_assert!(self.head < self.tail);
388 debug_assert!(self.head < self.cap());
389 debug_assert!(self.tail < self.cap());
390 debug_assert!(self.cap().count_ones() == 1);
394 impl<T> VecDeque<T> {
395 /// Creates an empty `VecDeque`.
400 /// use std::collections::VecDeque;
402 /// let vector: VecDeque<u32> = VecDeque::new();
404 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn new() -> VecDeque<T> {
406 VecDeque::with_capacity(INITIAL_CAPACITY)
409 /// Creates an empty `VecDeque` with space for at least `n` elements.
414 /// use std::collections::VecDeque;
416 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
418 #[stable(feature = "rust1", since = "1.0.0")]
419 pub fn with_capacity(n: usize) -> VecDeque<T> {
420 // +1 since the ringbuffer always leaves one space empty
421 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
422 assert!(cap > n, "capacity overflow");
427 buf: RawVec::with_capacity(cap),
431 /// Retrieves an element in the `VecDeque` by index.
433 /// Element at index 0 is the front of the queue.
438 /// use std::collections::VecDeque;
440 /// let mut buf = VecDeque::new();
441 /// buf.push_back(3);
442 /// buf.push_back(4);
443 /// buf.push_back(5);
444 /// assert_eq!(buf.get(1), Some(&4));
446 #[stable(feature = "rust1", since = "1.0.0")]
447 pub fn get(&self, index: usize) -> Option<&T> {
448 if index < self.len() {
449 let idx = self.wrap_add(self.tail, index);
450 unsafe { Some(&*self.ptr().add(idx)) }
456 /// Retrieves an element in the `VecDeque` mutably by index.
458 /// Element at index 0 is the front of the queue.
463 /// use std::collections::VecDeque;
465 /// let mut buf = VecDeque::new();
466 /// buf.push_back(3);
467 /// buf.push_back(4);
468 /// buf.push_back(5);
469 /// if let Some(elem) = buf.get_mut(1) {
473 /// assert_eq!(buf[1], 7);
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
477 if index < self.len() {
478 let idx = self.wrap_add(self.tail, index);
479 unsafe { Some(&mut *self.ptr().add(idx)) }
485 /// Swaps elements at indices `i` and `j`.
487 /// `i` and `j` may be equal.
489 /// Element at index 0 is the front of the queue.
493 /// Panics if either index is out of bounds.
498 /// use std::collections::VecDeque;
500 /// let mut buf = VecDeque::new();
501 /// buf.push_back(3);
502 /// buf.push_back(4);
503 /// buf.push_back(5);
504 /// assert_eq!(buf, [3, 4, 5]);
506 /// assert_eq!(buf, [5, 4, 3]);
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn swap(&mut self, i: usize, j: usize) {
510 assert!(i < self.len());
511 assert!(j < self.len());
512 let ri = self.wrap_add(self.tail, i);
513 let rj = self.wrap_add(self.tail, j);
515 ptr::swap(self.ptr().add(ri),
520 /// Returns the number of elements the `VecDeque` can hold without
526 /// use std::collections::VecDeque;
528 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
529 /// assert!(buf.capacity() >= 10);
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn capacity(&self) -> usize {
537 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
538 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
540 /// Note that the allocator may give the collection more space than it requests. Therefore
541 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
542 /// insertions are expected.
546 /// Panics if the new capacity overflows `usize`.
551 /// use std::collections::VecDeque;
553 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
554 /// buf.reserve_exact(10);
555 /// assert!(buf.capacity() >= 11);
558 /// [`reserve`]: #method.reserve
559 #[stable(feature = "rust1", since = "1.0.0")]
560 pub fn reserve_exact(&mut self, additional: usize) {
561 self.reserve(additional);
564 /// Reserves capacity for at least `additional` more elements to be inserted in the given
565 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
569 /// Panics if the new capacity overflows `usize`.
574 /// use std::collections::VecDeque;
576 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
578 /// assert!(buf.capacity() >= 11);
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn reserve(&mut self, additional: usize) {
582 let old_cap = self.cap();
583 let used_cap = self.len() + 1;
584 let new_cap = used_cap.checked_add(additional)
585 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
586 .expect("capacity overflow");
588 if new_cap > old_cap {
589 self.buf.reserve_exact(used_cap, new_cap - used_cap);
591 self.handle_cap_increase(old_cap);
596 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
597 /// be inserted in the given `VecDeque<T>`. After calling `reserve_exact`,
598 /// capacity will be greater than or equal to `self.len() + additional`.
599 /// Does nothing if the capacity is already sufficient.
601 /// Note that the allocator may give the collection more space than it
602 /// requests. Therefore capacity can not be relied upon to be precisely
603 /// minimal. Prefer `reserve` if future insertions are expected.
607 /// If the capacity overflows, or the allocator reports a failure, then an error
613 /// #![feature(try_reserve)]
614 /// use std::collections::CollectionAllocErr;
615 /// use std::collections::VecDeque;
617 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
618 /// let mut output = VecDeque::new();
620 /// // Pre-reserve the memory, exiting if we can't
621 /// output.try_reserve_exact(data.len())?;
623 /// // Now we know this can't OOM in the middle of our complex work
624 /// output.extend(data.iter().map(|&val| {
625 /// val * 2 + 5 // very complicated
630 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
632 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
633 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
634 self.try_reserve(additional)
637 /// Tries to reserve capacity for at least `additional` more elements to be inserted
638 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
639 /// frequent reallocations. After calling `reserve`, capacity will be
640 /// greater than or equal to `self.len() + additional`. Does nothing if
641 /// capacity is already sufficient.
645 /// If the capacity overflows, or the allocator reports a failure, then an error
651 /// #![feature(try_reserve)]
652 /// use std::collections::CollectionAllocErr;
653 /// use std::collections::VecDeque;
655 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
656 /// let mut output = VecDeque::new();
658 /// // Pre-reserve the memory, exiting if we can't
659 /// output.try_reserve(data.len())?;
661 /// // Now we know this can't OOM in the middle of our complex work
662 /// output.extend(data.iter().map(|&val| {
663 /// val * 2 + 5 // very complicated
668 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
670 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
671 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
672 let old_cap = self.cap();
673 let used_cap = self.len() + 1;
674 let new_cap = used_cap.checked_add(additional)
675 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
676 .ok_or(CollectionAllocErr::CapacityOverflow)?;
678 if new_cap > old_cap {
679 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
681 self.handle_cap_increase(old_cap);
687 /// Shrinks the capacity of the `VecDeque` as much as possible.
689 /// It will drop down as close as possible to the length but the allocator may still inform the
690 /// `VecDeque` that there is space for a few more elements.
695 /// use std::collections::VecDeque;
697 /// let mut buf = VecDeque::with_capacity(15);
698 /// buf.extend(0..4);
699 /// assert_eq!(buf.capacity(), 15);
700 /// buf.shrink_to_fit();
701 /// assert!(buf.capacity() >= 4);
703 #[stable(feature = "deque_extras_15", since = "1.5.0")]
704 pub fn shrink_to_fit(&mut self) {
708 /// Shrinks the capacity of the `VecDeque` with a lower bound.
710 /// The capacity will remain at least as large as both the length
711 /// and the supplied value.
713 /// Panics if the current capacity is smaller than the supplied
714 /// minimum capacity.
719 /// #![feature(shrink_to)]
720 /// use std::collections::VecDeque;
722 /// let mut buf = VecDeque::with_capacity(15);
723 /// buf.extend(0..4);
724 /// assert_eq!(buf.capacity(), 15);
725 /// buf.shrink_to(6);
726 /// assert!(buf.capacity() >= 6);
727 /// buf.shrink_to(0);
728 /// assert!(buf.capacity() >= 4);
730 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
731 pub fn shrink_to(&mut self, min_capacity: usize) {
732 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
734 // +1 since the ringbuffer always leaves one space empty
735 // len + 1 can't overflow for an existing, well-formed ringbuffer.
736 let target_cap = cmp::max(
737 cmp::max(min_capacity, self.len()) + 1,
739 ).next_power_of_two();
741 if target_cap < self.cap() {
742 // There are three cases of interest:
743 // All elements are out of desired bounds
744 // Elements are contiguous, and head is out of desired bounds
745 // Elements are discontiguous, and tail is out of desired bounds
747 // At all other times, element positions are unaffected.
749 // Indicates that elements at the head should be moved.
750 let head_outside = self.head == 0 || self.head >= target_cap;
751 // Move elements from out of desired bounds (positions after target_cap)
752 if self.tail >= target_cap && head_outside {
754 // [. . . . . . . . o o o o o o o . ]
756 // [o o o o o o o . ]
758 self.copy_nonoverlapping(0, self.tail, self.len());
760 self.head = self.len();
762 } else if self.tail != 0 && self.tail < target_cap && head_outside {
764 // [. . . o o o o o o o . . . . . . ]
766 // [o o . o o o o o ]
767 let len = self.wrap_sub(self.head, target_cap);
769 self.copy_nonoverlapping(0, target_cap, len);
772 debug_assert!(self.head < self.tail);
773 } else if self.tail >= target_cap {
775 // [o o o o o . . . . . . . . . o o ]
777 // [o o o o o . o o ]
778 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
779 let len = self.cap() - self.tail;
780 let new_tail = target_cap - len;
782 self.copy_nonoverlapping(new_tail, self.tail, len);
784 self.tail = new_tail;
785 debug_assert!(self.head < self.tail);
788 self.buf.shrink_to_fit(target_cap);
790 debug_assert!(self.head < self.cap());
791 debug_assert!(self.tail < self.cap());
792 debug_assert!(self.cap().count_ones() == 1);
796 /// Shortens the `VecDeque`, dropping excess elements from the back.
798 /// If `len` is greater than the `VecDeque`'s current length, this has no
804 /// use std::collections::VecDeque;
806 /// let mut buf = VecDeque::new();
807 /// buf.push_back(5);
808 /// buf.push_back(10);
809 /// buf.push_back(15);
810 /// assert_eq!(buf, [5, 10, 15]);
812 /// assert_eq!(buf, [5]);
814 #[stable(feature = "deque_extras", since = "1.16.0")]
815 pub fn truncate(&mut self, len: usize) {
816 for _ in len..self.len() {
821 /// Returns a front-to-back iterator.
826 /// use std::collections::VecDeque;
828 /// let mut buf = VecDeque::new();
829 /// buf.push_back(5);
830 /// buf.push_back(3);
831 /// buf.push_back(4);
832 /// let b: &[_] = &[&5, &3, &4];
833 /// let c: Vec<&i32> = buf.iter().collect();
834 /// assert_eq!(&c[..], b);
836 #[stable(feature = "rust1", since = "1.0.0")]
837 pub fn iter(&self) -> Iter<T> {
841 ring: unsafe { self.buffer_as_slice() },
845 /// Returns a front-to-back iterator that returns mutable references.
850 /// use std::collections::VecDeque;
852 /// let mut buf = VecDeque::new();
853 /// buf.push_back(5);
854 /// buf.push_back(3);
855 /// buf.push_back(4);
856 /// for num in buf.iter_mut() {
859 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
860 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
862 #[stable(feature = "rust1", since = "1.0.0")]
863 pub fn iter_mut(&mut self) -> IterMut<T> {
867 ring: unsafe { self.buffer_as_mut_slice() },
871 /// Returns a pair of slices which contain, in order, the contents of the
877 /// use std::collections::VecDeque;
879 /// let mut vector = VecDeque::new();
881 /// vector.push_back(0);
882 /// vector.push_back(1);
883 /// vector.push_back(2);
885 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
887 /// vector.push_front(10);
888 /// vector.push_front(9);
890 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
893 #[stable(feature = "deque_extras_15", since = "1.5.0")]
894 pub fn as_slices(&self) -> (&[T], &[T]) {
896 let buf = self.buffer_as_slice();
897 RingSlices::ring_slices(buf, self.head, self.tail)
901 /// Returns a pair of slices which contain, in order, the contents of the
907 /// use std::collections::VecDeque;
909 /// let mut vector = VecDeque::new();
911 /// vector.push_back(0);
912 /// vector.push_back(1);
914 /// vector.push_front(10);
915 /// vector.push_front(9);
917 /// vector.as_mut_slices().0[0] = 42;
918 /// vector.as_mut_slices().1[0] = 24;
919 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
922 #[stable(feature = "deque_extras_15", since = "1.5.0")]
923 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
925 let head = self.head;
926 let tail = self.tail;
927 let buf = self.buffer_as_mut_slice();
928 RingSlices::ring_slices(buf, head, tail)
932 /// Returns the number of elements in the `VecDeque`.
937 /// use std::collections::VecDeque;
939 /// let mut v = VecDeque::new();
940 /// assert_eq!(v.len(), 0);
942 /// assert_eq!(v.len(), 1);
944 #[stable(feature = "rust1", since = "1.0.0")]
945 pub fn len(&self) -> usize {
946 count(self.tail, self.head, self.cap())
949 /// Returns `true` if the `VecDeque` is empty.
954 /// use std::collections::VecDeque;
956 /// let mut v = VecDeque::new();
957 /// assert!(v.is_empty());
959 /// assert!(!v.is_empty());
961 #[stable(feature = "rust1", since = "1.0.0")]
962 pub fn is_empty(&self) -> bool {
963 self.tail == self.head
966 /// Create a draining iterator that removes the specified range in the
967 /// `VecDeque` and yields the removed items.
969 /// Note 1: The element range is removed even if the iterator is not
970 /// consumed until the end.
972 /// Note 2: It is unspecified how many elements are removed from the deque,
973 /// if the `Drain` value is not dropped, but the borrow it holds expires
974 /// (eg. due to mem::forget).
978 /// Panics if the starting point is greater than the end point or if
979 /// the end point is greater than the length of the vector.
984 /// use std::collections::VecDeque;
986 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
987 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
988 /// assert_eq!(drained, [3]);
989 /// assert_eq!(v, [1, 2]);
991 /// // A full range clears all contents
993 /// assert!(v.is_empty());
996 #[stable(feature = "drain", since = "1.6.0")]
997 pub fn drain<R>(&mut self, range: R) -> Drain<T>
998 where R: RangeBounds<usize>
1002 // When the Drain is first created, the source deque is shortened to
1003 // make sure no uninitialized or moved-from elements are accessible at
1004 // all if the Drain's destructor never gets to run.
1006 // Drain will ptr::read out the values to remove.
1007 // When finished, the remaining data will be copied back to cover the hole,
1008 // and the head/tail values will be restored correctly.
1010 let len = self.len();
1011 let start = match range.start_bound() {
1013 Excluded(&n) => n + 1,
1016 let end = match range.end_bound() {
1017 Included(&n) => n + 1,
1021 assert!(start <= end, "drain lower bound was too large");
1022 assert!(end <= len, "drain upper bound was too large");
1024 // The deque's elements are parted into three segments:
1025 // * self.tail -> drain_tail
1026 // * drain_tail -> drain_head
1027 // * drain_head -> self.head
1029 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1031 // We store drain_tail as self.head, and drain_head and self.head as
1032 // after_tail and after_head respectively on the Drain. This also
1033 // truncates the effective array such that if the Drain is leaked, we
1034 // have forgotten about the potentially moved values after the start of
1038 // [. . . o o x x o o . . .]
1040 let drain_tail = self.wrap_add(self.tail, start);
1041 let drain_head = self.wrap_add(self.tail, end);
1042 let head = self.head;
1044 // "forget" about the values after the start of the drain until after
1045 // the drain is complete and the Drain destructor is run.
1046 self.head = drain_tail;
1049 deque: NonNull::from(&mut *self),
1050 after_tail: drain_head,
1055 ring: unsafe { self.buffer_as_slice() },
1060 /// Clears the `VecDeque`, removing all values.
1065 /// use std::collections::VecDeque;
1067 /// let mut v = VecDeque::new();
1070 /// assert!(v.is_empty());
1072 #[stable(feature = "rust1", since = "1.0.0")]
1074 pub fn clear(&mut self) {
1078 /// Returns `true` if the `VecDeque` contains an element equal to the
1084 /// use std::collections::VecDeque;
1086 /// let mut vector: VecDeque<u32> = VecDeque::new();
1088 /// vector.push_back(0);
1089 /// vector.push_back(1);
1091 /// assert_eq!(vector.contains(&1), true);
1092 /// assert_eq!(vector.contains(&10), false);
1094 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1095 pub fn contains(&self, x: &T) -> bool
1096 where T: PartialEq<T>
1098 let (a, b) = self.as_slices();
1099 a.contains(x) || b.contains(x)
1102 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1108 /// use std::collections::VecDeque;
1110 /// let mut d = VecDeque::new();
1111 /// assert_eq!(d.front(), None);
1115 /// assert_eq!(d.front(), Some(&1));
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 pub fn front(&self) -> Option<&T> {
1119 if !self.is_empty() {
1126 /// Provides a mutable reference to the front element, or `None` if the
1127 /// `VecDeque` is empty.
1132 /// use std::collections::VecDeque;
1134 /// let mut d = VecDeque::new();
1135 /// assert_eq!(d.front_mut(), None);
1139 /// match d.front_mut() {
1140 /// Some(x) => *x = 9,
1143 /// assert_eq!(d.front(), Some(&9));
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn front_mut(&mut self) -> Option<&mut T> {
1147 if !self.is_empty() {
1154 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1160 /// use std::collections::VecDeque;
1162 /// let mut d = VecDeque::new();
1163 /// assert_eq!(d.back(), None);
1167 /// assert_eq!(d.back(), Some(&2));
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 pub fn back(&self) -> Option<&T> {
1171 if !self.is_empty() {
1172 Some(&self[self.len() - 1])
1178 /// Provides a mutable reference to the back element, or `None` if the
1179 /// `VecDeque` is empty.
1184 /// use std::collections::VecDeque;
1186 /// let mut d = VecDeque::new();
1187 /// assert_eq!(d.back(), None);
1191 /// match d.back_mut() {
1192 /// Some(x) => *x = 9,
1195 /// assert_eq!(d.back(), Some(&9));
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn back_mut(&mut self) -> Option<&mut T> {
1199 let len = self.len();
1200 if !self.is_empty() {
1201 Some(&mut self[len - 1])
1207 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1213 /// use std::collections::VecDeque;
1215 /// let mut d = VecDeque::new();
1219 /// assert_eq!(d.pop_front(), Some(1));
1220 /// assert_eq!(d.pop_front(), Some(2));
1221 /// assert_eq!(d.pop_front(), None);
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 pub fn pop_front(&mut self) -> Option<T> {
1225 if self.is_empty() {
1228 let tail = self.tail;
1229 self.tail = self.wrap_add(self.tail, 1);
1230 unsafe { Some(self.buffer_read(tail)) }
1234 /// Prepends an element to the `VecDeque`.
1239 /// use std::collections::VecDeque;
1241 /// let mut d = VecDeque::new();
1242 /// d.push_front(1);
1243 /// d.push_front(2);
1244 /// assert_eq!(d.front(), Some(&2));
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 pub fn push_front(&mut self, value: T) {
1248 self.grow_if_necessary();
1250 self.tail = self.wrap_sub(self.tail, 1);
1251 let tail = self.tail;
1253 self.buffer_write(tail, value);
1257 /// Appends an element to the back of the `VecDeque`.
1262 /// use std::collections::VecDeque;
1264 /// let mut buf = VecDeque::new();
1265 /// buf.push_back(1);
1266 /// buf.push_back(3);
1267 /// assert_eq!(3, *buf.back().unwrap());
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 pub fn push_back(&mut self, value: T) {
1271 self.grow_if_necessary();
1273 let head = self.head;
1274 self.head = self.wrap_add(self.head, 1);
1275 unsafe { self.buffer_write(head, value) }
1278 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1284 /// use std::collections::VecDeque;
1286 /// let mut buf = VecDeque::new();
1287 /// assert_eq!(buf.pop_back(), None);
1288 /// buf.push_back(1);
1289 /// buf.push_back(3);
1290 /// assert_eq!(buf.pop_back(), Some(3));
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 pub fn pop_back(&mut self) -> Option<T> {
1294 if self.is_empty() {
1297 self.head = self.wrap_sub(self.head, 1);
1298 let head = self.head;
1299 unsafe { Some(self.buffer_read(head)) }
1304 fn is_contiguous(&self) -> bool {
1305 self.tail <= self.head
1308 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1311 /// This does not preserve ordering, but is O(1).
1313 /// Returns `None` if `index` is out of bounds.
1315 /// Element at index 0 is the front of the queue.
1320 /// use std::collections::VecDeque;
1322 /// let mut buf = VecDeque::new();
1323 /// assert_eq!(buf.swap_remove_back(0), None);
1324 /// buf.push_back(1);
1325 /// buf.push_back(2);
1326 /// buf.push_back(3);
1327 /// assert_eq!(buf, [1, 2, 3]);
1329 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1330 /// assert_eq!(buf, [3, 2]);
1332 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1333 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1334 let length = self.len();
1335 if length > 0 && index < length - 1 {
1336 self.swap(index, length - 1);
1337 } else if index >= length {
1343 /// Removes an element from anywhere in the `VecDeque` and returns it,
1344 /// replacing it with the first element.
1346 /// This does not preserve ordering, but is O(1).
1348 /// Returns `None` if `index` is out of bounds.
1350 /// Element at index 0 is the front of the queue.
1355 /// use std::collections::VecDeque;
1357 /// let mut buf = VecDeque::new();
1358 /// assert_eq!(buf.swap_remove_front(0), None);
1359 /// buf.push_back(1);
1360 /// buf.push_back(2);
1361 /// buf.push_back(3);
1362 /// assert_eq!(buf, [1, 2, 3]);
1364 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1365 /// assert_eq!(buf, [2, 1]);
1367 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1368 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1369 let length = self.len();
1370 if length > 0 && index < length && index != 0 {
1371 self.swap(index, 0);
1372 } else if index >= length {
1378 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1379 /// greater than or equal to `index` towards the back.
1381 /// Element at index 0 is the front of the queue.
1385 /// Panics if `index` is greater than `VecDeque`'s length
1390 /// use std::collections::VecDeque;
1392 /// let mut vec_deque = VecDeque::new();
1393 /// vec_deque.push_back('a');
1394 /// vec_deque.push_back('b');
1395 /// vec_deque.push_back('c');
1396 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1398 /// vec_deque.insert(1, 'd');
1399 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1401 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1402 pub fn insert(&mut self, index: usize, value: T) {
1403 assert!(index <= self.len(), "index out of bounds");
1404 self.grow_if_necessary();
1406 // Move the least number of elements in the ring buffer and insert
1409 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1411 // There are three main cases:
1412 // Elements are contiguous
1413 // - special case when tail is 0
1414 // Elements are discontiguous and the insert is in the tail section
1415 // Elements are discontiguous and the insert is in the head section
1417 // For each of those there are two more cases:
1418 // Insert is closer to tail
1419 // Insert is closer to head
1421 // Key: H - self.head
1423 // o - Valid element
1424 // I - Insertion element
1425 // A - The element that should be after the insertion point
1426 // M - Indicates element was moved
1428 let idx = self.wrap_add(self.tail, index);
1430 let distance_to_tail = index;
1431 let distance_to_head = self.len() - index;
1433 let contiguous = self.is_contiguous();
1435 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1436 (true, true, _) if index == 0 => {
1441 // [A o o o o o o . . . . . . . . .]
1444 // [A o o o o o o o . . . . . I]
1447 self.tail = self.wrap_sub(self.tail, 1);
1449 (true, true, _) => {
1451 // contiguous, insert closer to tail:
1454 // [. . . o o A o o o o . . . . . .]
1457 // [. . o o I A o o o o . . . . . .]
1460 // contiguous, insert closer to tail and tail is 0:
1464 // [o o A o o o o . . . . . . . . .]
1467 // [o I A o o o o o . . . . . . . o]
1470 let new_tail = self.wrap_sub(self.tail, 1);
1472 self.copy(new_tail, self.tail, 1);
1473 // Already moved the tail, so we only copy `index - 1` elements.
1474 self.copy(self.tail, self.tail + 1, index - 1);
1476 self.tail = new_tail;
1479 (true, false, _) => {
1481 // contiguous, insert closer to head:
1484 // [. . . o o o o A o o . . . . . .]
1487 // [. . . o o o o I A o o . . . . .]
1490 self.copy(idx + 1, idx, self.head - idx);
1491 self.head = self.wrap_add(self.head, 1);
1494 (false, true, true) => {
1496 // discontiguous, insert closer to tail, tail section:
1499 // [o o o o o o . . . . . o o A o o]
1502 // [o o o o o o . . . . o o I A o o]
1505 self.copy(self.tail - 1, self.tail, index);
1509 (false, false, true) => {
1511 // discontiguous, insert closer to head, tail section:
1514 // [o o . . . . . . . o o o o o A o]
1517 // [o o o . . . . . . o o o o o I A]
1520 // copy elements up to new head
1521 self.copy(1, 0, self.head);
1523 // copy last element into empty spot at bottom of buffer
1524 self.copy(0, self.cap() - 1, 1);
1526 // move elements from idx to end forward not including ^ element
1527 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1532 (false, true, false) if idx == 0 => {
1534 // discontiguous, insert is closer to tail, head section,
1535 // and is at index zero in the internal buffer:
1538 // [A o o o o o o o o o . . . o o o]
1541 // [A o o o o o o o o o . . o o o I]
1544 // copy elements up to new tail
1545 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1547 // copy last element into empty spot at bottom of buffer
1548 self.copy(self.cap() - 1, 0, 1);
1553 (false, true, false) => {
1555 // discontiguous, insert closer to tail, head section:
1558 // [o o o A o o o o o o . . . o o o]
1561 // [o o I A o o o o o o . . o o o o]
1564 // copy elements up to new tail
1565 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1567 // copy last element into empty spot at bottom of buffer
1568 self.copy(self.cap() - 1, 0, 1);
1570 // move elements from idx-1 to end forward not including ^ element
1571 self.copy(0, 1, idx - 1);
1576 (false, false, false) => {
1578 // discontiguous, insert closer to head, head section:
1581 // [o o o o A o o . . . . . . o o o]
1584 // [o o o o I A o o . . . . . o o o]
1587 self.copy(idx + 1, idx, self.head - idx);
1593 // tail might've been changed so we need to recalculate
1594 let new_idx = self.wrap_add(self.tail, index);
1596 self.buffer_write(new_idx, value);
1600 /// Removes and returns the element at `index` from the `VecDeque`.
1601 /// Whichever end is closer to the removal point will be moved to make
1602 /// room, and all the affected elements will be moved to new positions.
1603 /// Returns `None` if `index` is out of bounds.
1605 /// Element at index 0 is the front of the queue.
1610 /// use std::collections::VecDeque;
1612 /// let mut buf = VecDeque::new();
1613 /// buf.push_back(1);
1614 /// buf.push_back(2);
1615 /// buf.push_back(3);
1616 /// assert_eq!(buf, [1, 2, 3]);
1618 /// assert_eq!(buf.remove(1), Some(2));
1619 /// assert_eq!(buf, [1, 3]);
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 pub fn remove(&mut self, index: usize) -> Option<T> {
1623 if self.is_empty() || self.len() <= index {
1627 // There are three main cases:
1628 // Elements are contiguous
1629 // Elements are discontiguous and the removal is in the tail section
1630 // Elements are discontiguous and the removal is in the head section
1631 // - special case when elements are technically contiguous,
1632 // but self.head = 0
1634 // For each of those there are two more cases:
1635 // Insert is closer to tail
1636 // Insert is closer to head
1638 // Key: H - self.head
1640 // o - Valid element
1641 // x - Element marked for removal
1642 // R - Indicates element that is being removed
1643 // M - Indicates element was moved
1645 let idx = self.wrap_add(self.tail, index);
1647 let elem = unsafe { Some(self.buffer_read(idx)) };
1649 let distance_to_tail = index;
1650 let distance_to_head = self.len() - index;
1652 let contiguous = self.is_contiguous();
1654 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1655 (true, true, _) => {
1657 // contiguous, remove closer to tail:
1660 // [. . . o o x o o o o . . . . . .]
1663 // [. . . . o o o o o o . . . . . .]
1666 self.copy(self.tail + 1, self.tail, index);
1670 (true, false, _) => {
1672 // contiguous, remove closer to head:
1675 // [. . . o o o o x o o . . . . . .]
1678 // [. . . o o o o o o . . . . . . .]
1681 self.copy(idx, idx + 1, self.head - idx - 1);
1685 (false, true, true) => {
1687 // discontiguous, remove closer to tail, tail section:
1690 // [o o o o o o . . . . . o o x o o]
1693 // [o o o o o o . . . . . . o o o o]
1696 self.copy(self.tail + 1, self.tail, index);
1697 self.tail = self.wrap_add(self.tail, 1);
1700 (false, false, false) => {
1702 // discontiguous, remove closer to head, head section:
1705 // [o o o o x o o . . . . . . o o o]
1708 // [o o o o o o . . . . . . . o o o]
1711 self.copy(idx, idx + 1, self.head - idx - 1);
1715 (false, false, true) => {
1717 // discontiguous, remove closer to head, tail section:
1720 // [o o o . . . . . . o o o o o x o]
1723 // [o o . . . . . . . o o o o o o o]
1726 // or quasi-discontiguous, remove next to head, tail section:
1729 // [. . . . . . . . . o o o o o x o]
1732 // [. . . . . . . . . o o o o o o .]
1735 // draw in elements in the tail section
1736 self.copy(idx, idx + 1, self.cap() - idx - 1);
1738 // Prevents underflow.
1740 // copy first element into empty spot
1741 self.copy(self.cap() - 1, 0, 1);
1743 // move elements in the head section backwards
1744 self.copy(0, 1, self.head - 1);
1747 self.head = self.wrap_sub(self.head, 1);
1750 (false, true, false) => {
1752 // discontiguous, remove closer to tail, head section:
1755 // [o o x o o o o o o o . . . o o o]
1758 // [o o o o o o o o o o . . . . o o]
1761 // draw in elements up to idx
1762 self.copy(1, 0, idx);
1764 // copy last element into empty spot
1765 self.copy(0, self.cap() - 1, 1);
1767 // move elements from tail to end forward, excluding the last one
1768 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1770 self.tail = self.wrap_add(self.tail, 1);
1778 /// Splits the `VecDeque` into two at the given index.
1780 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1781 /// and the returned `VecDeque` contains elements `[at, len)`.
1783 /// Note that the capacity of `self` does not change.
1785 /// Element at index 0 is the front of the queue.
1789 /// Panics if `at > len`.
1794 /// use std::collections::VecDeque;
1796 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1797 /// let buf2 = buf.split_off(1);
1798 /// assert_eq!(buf, [1]);
1799 /// assert_eq!(buf2, [2, 3]);
1802 #[stable(feature = "split_off", since = "1.4.0")]
1803 pub fn split_off(&mut self, at: usize) -> Self {
1804 let len = self.len();
1805 assert!(at <= len, "`at` out of bounds");
1807 let other_len = len - at;
1808 let mut other = VecDeque::with_capacity(other_len);
1811 let (first_half, second_half) = self.as_slices();
1813 let first_len = first_half.len();
1814 let second_len = second_half.len();
1816 // `at` lies in the first half.
1817 let amount_in_first = first_len - at;
1819 ptr::copy_nonoverlapping(first_half.as_ptr().add(at),
1823 // just take all of the second half.
1824 ptr::copy_nonoverlapping(second_half.as_ptr(),
1825 other.ptr().add(amount_in_first),
1828 // `at` lies in the second half, need to factor in the elements we skipped
1829 // in the first half.
1830 let offset = at - first_len;
1831 let amount_in_second = second_len - offset;
1832 ptr::copy_nonoverlapping(second_half.as_ptr().add(offset),
1838 // Cleanup where the ends of the buffers are
1839 self.head = self.wrap_sub(self.head, other_len);
1840 other.head = other.wrap_index(other_len);
1845 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1849 /// Panics if the new number of elements in self overflows a `usize`.
1854 /// use std::collections::VecDeque;
1856 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1857 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1858 /// buf.append(&mut buf2);
1859 /// assert_eq!(buf, [1, 2, 3, 4]);
1860 /// assert_eq!(buf2, []);
1863 #[stable(feature = "append", since = "1.4.0")]
1864 pub fn append(&mut self, other: &mut Self) {
1866 // Guarantees there is space in `self` for `other`.
1867 self.reserve(other.len());
1870 let (src_high, src_low) = other.as_slices();
1872 // This is only safe because copy_slice never panics when capacity is sufficient.
1873 self.copy_slice(src_low);
1874 self.copy_slice(src_high);
1877 // Some values now exist in both `other` and `self` but are made inaccessible
1879 other.tail = other.head;
1883 /// Retains only the elements specified by the predicate.
1885 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1886 /// This method operates in place and preserves the order of the retained
1892 /// use std::collections::VecDeque;
1894 /// let mut buf = VecDeque::new();
1895 /// buf.extend(1..5);
1896 /// buf.retain(|&x| x%2 == 0);
1897 /// assert_eq!(buf, [2, 4]);
1899 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1900 pub fn retain<F>(&mut self, mut f: F)
1901 where F: FnMut(&T) -> bool
1903 let len = self.len();
1909 self.swap(i - del, i);
1913 self.truncate(len - del);
1917 // This may panic or abort
1919 fn grow_if_necessary(&mut self) {
1921 let old_cap = self.cap();
1924 self.handle_cap_increase(old_cap);
1926 debug_assert!(!self.is_full());
1931 impl<T: Clone> VecDeque<T> {
1932 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1933 /// either by removing excess elements from the back or by appending clones of `value`
1939 /// use std::collections::VecDeque;
1941 /// let mut buf = VecDeque::new();
1942 /// buf.push_back(5);
1943 /// buf.push_back(10);
1944 /// buf.push_back(15);
1945 /// assert_eq!(buf, [5, 10, 15]);
1947 /// buf.resize(2, 0);
1948 /// assert_eq!(buf, [5, 10]);
1950 /// buf.resize(5, 20);
1951 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
1953 #[stable(feature = "deque_extras", since = "1.16.0")]
1954 pub fn resize(&mut self, new_len: usize, value: T) {
1955 let len = self.len();
1958 self.extend(repeat(value).take(new_len - len))
1960 self.truncate(new_len);
1965 /// Returns the index in the underlying buffer for a given logical element index.
1967 fn wrap_index(index: usize, size: usize) -> usize {
1968 // size is always a power of 2
1969 debug_assert!(size.is_power_of_two());
1973 /// Returns the two slices that cover the `VecDeque`'s valid range
1974 trait RingSlices: Sized {
1975 fn slice(self, from: usize, to: usize) -> Self;
1976 fn split_at(self, i: usize) -> (Self, Self);
1978 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
1979 let contiguous = tail <= head;
1981 let (empty, buf) = buf.split_at(0);
1982 (buf.slice(tail, head), empty)
1984 let (mid, right) = buf.split_at(tail);
1985 let (left, _) = mid.split_at(head);
1991 impl<'a, T> RingSlices for &'a [T] {
1992 fn slice(self, from: usize, to: usize) -> Self {
1995 fn split_at(self, i: usize) -> (Self, Self) {
2000 impl<'a, T> RingSlices for &'a mut [T] {
2001 fn slice(self, from: usize, to: usize) -> Self {
2004 fn split_at(self, i: usize) -> (Self, Self) {
2005 (*self).split_at_mut(i)
2009 /// Calculate the number of elements left to be read in the buffer
2011 fn count(tail: usize, head: usize, size: usize) -> usize {
2012 // size is always a power of 2
2013 (head.wrapping_sub(tail)) & (size - 1)
2016 /// An iterator over the elements of a `VecDeque`.
2018 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
2019 /// documentation for more.
2021 /// [`iter`]: struct.VecDeque.html#method.iter
2022 /// [`VecDeque`]: struct.VecDeque.html
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 pub struct Iter<'a, T: 'a> {
2030 #[stable(feature = "collection_debug", since = "1.17.0")]
2031 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
2032 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2033 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2034 f.debug_tuple("Iter")
2041 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2042 #[stable(feature = "rust1", since = "1.0.0")]
2043 impl<'a, T> Clone for Iter<'a, T> {
2044 fn clone(&self) -> Iter<'a, T> {
2053 #[stable(feature = "rust1", since = "1.0.0")]
2054 impl<'a, T> Iterator for Iter<'a, T> {
2058 fn next(&mut self) -> Option<&'a T> {
2059 if self.tail == self.head {
2062 let tail = self.tail;
2063 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2064 unsafe { Some(self.ring.get_unchecked(tail)) }
2068 fn size_hint(&self) -> (usize, Option<usize>) {
2069 let len = count(self.tail, self.head, self.ring.len());
2073 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2074 where F: FnMut(Acc, Self::Item) -> Acc
2076 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2077 accum = front.iter().fold(accum, &mut f);
2078 back.iter().fold(accum, &mut f)
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2085 fn next_back(&mut self) -> Option<&'a T> {
2086 if self.tail == self.head {
2089 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2090 unsafe { Some(self.ring.get_unchecked(self.head)) }
2093 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2094 where F: FnMut(Acc, Self::Item) -> Acc
2096 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2097 accum = back.iter().rfold(accum, &mut f);
2098 front.iter().rfold(accum, &mut f)
2102 #[stable(feature = "rust1", since = "1.0.0")]
2103 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
2104 fn is_empty(&self) -> bool {
2105 self.head == self.tail
2109 #[stable(feature = "fused", since = "1.26.0")]
2110 impl<'a, T> FusedIterator for Iter<'a, T> {}
2113 /// A mutable iterator over the elements of a `VecDeque`.
2115 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2116 /// documentation for more.
2118 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2119 /// [`VecDeque`]: struct.VecDeque.html
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 pub struct IterMut<'a, T: 'a> {
2127 #[stable(feature = "collection_debug", since = "1.17.0")]
2128 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2129 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2130 let (front, back) = RingSlices::ring_slices(&*self.ring, self.head, self.tail);
2131 f.debug_tuple("IterMut")
2138 #[stable(feature = "rust1", since = "1.0.0")]
2139 impl<'a, T> Iterator for IterMut<'a, T> {
2140 type Item = &'a mut T;
2143 fn next(&mut self) -> Option<&'a mut T> {
2144 if self.tail == self.head {
2147 let tail = self.tail;
2148 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2151 let elem = self.ring.get_unchecked_mut(tail);
2152 Some(&mut *(elem as *mut _))
2157 fn size_hint(&self) -> (usize, Option<usize>) {
2158 let len = count(self.tail, self.head, self.ring.len());
2162 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2163 where F: FnMut(Acc, Self::Item) -> Acc
2165 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2166 accum = front.iter_mut().fold(accum, &mut f);
2167 back.iter_mut().fold(accum, &mut f)
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2174 fn next_back(&mut self) -> Option<&'a mut T> {
2175 if self.tail == self.head {
2178 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2181 let elem = self.ring.get_unchecked_mut(self.head);
2182 Some(&mut *(elem as *mut _))
2186 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2187 where F: FnMut(Acc, Self::Item) -> Acc
2189 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2190 accum = back.iter_mut().rfold(accum, &mut f);
2191 front.iter_mut().rfold(accum, &mut f)
2195 #[stable(feature = "rust1", since = "1.0.0")]
2196 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
2197 fn is_empty(&self) -> bool {
2198 self.head == self.tail
2202 #[stable(feature = "fused", since = "1.26.0")]
2203 impl<'a, T> FusedIterator for IterMut<'a, T> {}
2205 /// An owning iterator over the elements of a `VecDeque`.
2207 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`][`VecDeque`]
2208 /// (provided by the `IntoIterator` trait). See its documentation for more.
2210 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2211 /// [`VecDeque`]: struct.VecDeque.html
2213 #[stable(feature = "rust1", since = "1.0.0")]
2214 pub struct IntoIter<T> {
2218 #[stable(feature = "collection_debug", since = "1.17.0")]
2219 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2220 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2221 f.debug_tuple("IntoIter")
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 impl<T> Iterator for IntoIter<T> {
2232 fn next(&mut self) -> Option<T> {
2233 self.inner.pop_front()
2237 fn size_hint(&self) -> (usize, Option<usize>) {
2238 let len = self.inner.len();
2243 #[stable(feature = "rust1", since = "1.0.0")]
2244 impl<T> DoubleEndedIterator for IntoIter<T> {
2246 fn next_back(&mut self) -> Option<T> {
2247 self.inner.pop_back()
2251 #[stable(feature = "rust1", since = "1.0.0")]
2252 impl<T> ExactSizeIterator for IntoIter<T> {
2253 fn is_empty(&self) -> bool {
2254 self.inner.is_empty()
2258 #[stable(feature = "fused", since = "1.26.0")]
2259 impl<T> FusedIterator for IntoIter<T> {}
2261 /// A draining iterator over the elements of a `VecDeque`.
2263 /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its
2264 /// documentation for more.
2266 /// [`drain`]: struct.VecDeque.html#method.drain
2267 /// [`VecDeque`]: struct.VecDeque.html
2268 #[stable(feature = "drain", since = "1.6.0")]
2269 pub struct Drain<'a, T: 'a> {
2273 deque: NonNull<VecDeque<T>>,
2276 #[stable(feature = "collection_debug", since = "1.17.0")]
2277 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2279 f.debug_tuple("Drain")
2280 .field(&self.after_tail)
2281 .field(&self.after_head)
2287 #[stable(feature = "drain", since = "1.6.0")]
2288 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2289 #[stable(feature = "drain", since = "1.6.0")]
2290 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2292 #[stable(feature = "drain", since = "1.6.0")]
2293 impl<'a, T: 'a> Drop for Drain<'a, T> {
2294 fn drop(&mut self) {
2295 self.for_each(drop);
2297 let source_deque = unsafe { self.deque.as_mut() };
2299 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2302 // [. . . o o x x o o . . .]
2304 let orig_tail = source_deque.tail;
2305 let drain_tail = source_deque.head;
2306 let drain_head = self.after_tail;
2307 let orig_head = self.after_head;
2309 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2310 let head_len = count(drain_head, orig_head, source_deque.cap());
2312 // Restore the original head value
2313 source_deque.head = orig_head;
2315 match (tail_len, head_len) {
2317 source_deque.head = 0;
2318 source_deque.tail = 0;
2321 source_deque.tail = drain_head;
2324 source_deque.head = drain_tail;
2327 if tail_len <= head_len {
2328 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2329 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2331 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2332 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2339 #[stable(feature = "drain", since = "1.6.0")]
2340 impl<'a, T: 'a> Iterator for Drain<'a, T> {
2344 fn next(&mut self) -> Option<T> {
2345 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2349 fn size_hint(&self) -> (usize, Option<usize>) {
2350 self.iter.size_hint()
2354 #[stable(feature = "drain", since = "1.6.0")]
2355 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
2357 fn next_back(&mut self) -> Option<T> {
2358 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2362 #[stable(feature = "drain", since = "1.6.0")]
2363 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
2365 #[stable(feature = "fused", since = "1.26.0")]
2366 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
2368 #[stable(feature = "rust1", since = "1.0.0")]
2369 impl<A: PartialEq> PartialEq for VecDeque<A> {
2370 fn eq(&self, other: &VecDeque<A>) -> bool {
2371 if self.len() != other.len() {
2374 let (sa, sb) = self.as_slices();
2375 let (oa, ob) = other.as_slices();
2376 if sa.len() == oa.len() {
2377 sa == oa && sb == ob
2378 } else if sa.len() < oa.len() {
2379 // Always divisible in three sections, for example:
2380 // self: [a b c|d e f]
2381 // other: [0 1 2 3|4 5]
2382 // front = 3, mid = 1,
2383 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2384 let front = sa.len();
2385 let mid = oa.len() - front;
2387 let (oa_front, oa_mid) = oa.split_at(front);
2388 let (sb_mid, sb_back) = sb.split_at(mid);
2389 debug_assert_eq!(sa.len(), oa_front.len());
2390 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2391 debug_assert_eq!(sb_back.len(), ob.len());
2392 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2394 let front = oa.len();
2395 let mid = sa.len() - front;
2397 let (sa_front, sa_mid) = sa.split_at(front);
2398 let (ob_mid, ob_back) = ob.split_at(mid);
2399 debug_assert_eq!(sa_front.len(), oa.len());
2400 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2401 debug_assert_eq!(sb.len(), ob_back.len());
2402 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 impl<A: Eq> Eq for VecDeque<A> {}
2410 macro_rules! __impl_slice_eq1 {
2411 ($Lhs: ty, $Rhs: ty) => {
2412 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2414 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2415 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2416 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2417 fn eq(&self, other: &$Rhs) -> bool {
2418 if self.len() != other.len() {
2421 let (sa, sb) = self.as_slices();
2422 let (oa, ob) = other[..].split_at(sa.len());
2423 sa == oa && sb == ob
2429 __impl_slice_eq1! { VecDeque<A>, Vec<B> }
2430 __impl_slice_eq1! { VecDeque<A>, &'b [B] }
2431 __impl_slice_eq1! { VecDeque<A>, &'b mut [B] }
2433 macro_rules! array_impls {
2436 __impl_slice_eq1! { VecDeque<A>, [B; $N] }
2437 __impl_slice_eq1! { VecDeque<A>, &'b [B; $N] }
2438 __impl_slice_eq1! { VecDeque<A>, &'b mut [B; $N] }
2445 10 11 12 13 14 15 16 17 18 19
2446 20 21 22 23 24 25 26 27 28 29
2450 #[stable(feature = "rust1", since = "1.0.0")]
2451 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2452 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2453 self.iter().partial_cmp(other.iter())
2457 #[stable(feature = "rust1", since = "1.0.0")]
2458 impl<A: Ord> Ord for VecDeque<A> {
2460 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2461 self.iter().cmp(other.iter())
2465 #[stable(feature = "rust1", since = "1.0.0")]
2466 impl<A: Hash> Hash for VecDeque<A> {
2467 fn hash<H: Hasher>(&self, state: &mut H) {
2468 self.len().hash(state);
2469 let (a, b) = self.as_slices();
2470 Hash::hash_slice(a, state);
2471 Hash::hash_slice(b, state);
2475 #[stable(feature = "rust1", since = "1.0.0")]
2476 impl<A> Index<usize> for VecDeque<A> {
2480 fn index(&self, index: usize) -> &A {
2481 self.get(index).expect("Out of bounds access")
2485 #[stable(feature = "rust1", since = "1.0.0")]
2486 impl<A> IndexMut<usize> for VecDeque<A> {
2488 fn index_mut(&mut self, index: usize) -> &mut A {
2489 self.get_mut(index).expect("Out of bounds access")
2493 #[stable(feature = "rust1", since = "1.0.0")]
2494 impl<A> FromIterator<A> for VecDeque<A> {
2495 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2496 let iterator = iter.into_iter();
2497 let (lower, _) = iterator.size_hint();
2498 let mut deq = VecDeque::with_capacity(lower);
2499 deq.extend(iterator);
2504 #[stable(feature = "rust1", since = "1.0.0")]
2505 impl<T> IntoIterator for VecDeque<T> {
2507 type IntoIter = IntoIter<T>;
2509 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2511 fn into_iter(self) -> IntoIter<T> {
2512 IntoIter { inner: self }
2516 #[stable(feature = "rust1", since = "1.0.0")]
2517 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2519 type IntoIter = Iter<'a, T>;
2521 fn into_iter(self) -> Iter<'a, T> {
2526 #[stable(feature = "rust1", since = "1.0.0")]
2527 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2528 type Item = &'a mut T;
2529 type IntoIter = IterMut<'a, T>;
2531 fn into_iter(self) -> IterMut<'a, T> {
2536 #[stable(feature = "rust1", since = "1.0.0")]
2537 impl<A> Extend<A> for VecDeque<A> {
2538 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2540 self.push_back(elt);
2545 #[stable(feature = "extend_ref", since = "1.2.0")]
2546 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2547 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2548 self.extend(iter.into_iter().cloned());
2552 #[stable(feature = "rust1", since = "1.0.0")]
2553 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2554 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2555 f.debug_list().entries(self).finish()
2559 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2560 impl<T> From<Vec<T>> for VecDeque<T> {
2561 fn from(mut other: Vec<T>) -> Self {
2563 let other_buf = other.as_mut_ptr();
2564 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2565 let len = other.len();
2568 // We need to extend the buf if it's not a power of two, too small
2569 // or doesn't have at least one free space
2570 if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) ||
2571 (buf.cap() == len) {
2572 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2573 buf.reserve_exact(len, cap - len);
2585 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2586 impl<T> From<VecDeque<T>> for Vec<T> {
2587 fn from(other: VecDeque<T>) -> Self {
2589 let buf = other.buf.ptr();
2590 let len = other.len();
2591 let tail = other.tail;
2592 let head = other.head;
2593 let cap = other.cap();
2595 // Need to move the ring to the front of the buffer, as vec will expect this.
2596 if other.is_contiguous() {
2597 ptr::copy(buf.add(tail), buf, len);
2599 if (tail - head) >= cmp::min(cap - tail, head) {
2600 // There is enough free space in the centre for the shortest block so we can
2601 // do this in at most three copy moves.
2602 if (cap - tail) > head {
2603 // right hand block is the long one; move that enough for the left
2604 ptr::copy(buf.add(tail),
2605 buf.add(tail - head),
2607 // copy left in the end
2608 ptr::copy(buf, buf.add(cap - head), head);
2609 // shift the new thing to the start
2610 ptr::copy(buf.add(tail - head), buf, len);
2612 // left hand block is the long one, we can do it in two!
2613 ptr::copy(buf, buf.add(cap - tail), head);
2614 ptr::copy(buf.add(tail), buf, cap - tail);
2617 // Need to use N swaps to move the ring
2618 // We can use the space at the end of the ring as a temp store
2620 let mut left_edge: usize = 0;
2621 let mut right_edge: usize = tail;
2623 // The general problem looks like this
2624 // GHIJKLM...ABCDEF - before any swaps
2625 // ABCDEFM...GHIJKL - after 1 pass of swaps
2626 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2627 // - then restart the algorithm with a new (smaller) store
2628 // Sometimes the temp store is reached when the right edge is at the end
2629 // of the buffer - this means we've hit the right order with fewer swaps!
2632 // ABCDEF.. - after four only swaps we've finished
2634 while left_edge < len && right_edge != cap {
2635 let mut right_offset = 0;
2636 for i in left_edge..right_edge {
2637 right_offset = (i - left_edge) % (cap - right_edge);
2638 let src = right_edge + right_offset;
2639 ptr::swap(buf.add(i), buf.add(src));
2641 let n_ops = right_edge - left_edge;
2643 right_edge += right_offset + 1;
2649 let out = Vec::from_raw_parts(buf, len, cap);
2660 use super::VecDeque;
2663 fn bench_push_back_100(b: &mut test::Bencher) {
2664 let mut deq = VecDeque::with_capacity(101);
2675 fn bench_push_front_100(b: &mut test::Bencher) {
2676 let mut deq = VecDeque::with_capacity(101);
2687 fn bench_pop_back_100(b: &mut test::Bencher) {
2688 let mut deq = VecDeque::<i32>::with_capacity(101);
2693 while !deq.is_empty() {
2694 test::black_box(deq.pop_back());
2700 fn bench_pop_front_100(b: &mut test::Bencher) {
2701 let mut deq = VecDeque::<i32>::with_capacity(101);
2706 while !deq.is_empty() {
2707 test::black_box(deq.pop_front());
2713 fn test_swap_front_back_remove() {
2714 fn test(back: bool) {
2715 // This test checks that every single combination of tail position and length is tested.
2716 // Capacity 15 should be large enough to cover every case.
2717 let mut tester = VecDeque::with_capacity(15);
2718 let usable_cap = tester.capacity();
2719 let final_len = usable_cap / 2;
2721 for len in 0..final_len {
2722 let expected: VecDeque<_> = if back {
2725 (0..len).rev().collect()
2727 for tail_pos in 0..usable_cap {
2728 tester.tail = tail_pos;
2729 tester.head = tail_pos;
2731 for i in 0..len * 2 {
2732 tester.push_front(i);
2735 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2738 for i in 0..len * 2 {
2739 tester.push_back(i);
2742 let idx = tester.len() - 1 - i;
2743 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2746 assert!(tester.tail < tester.cap());
2747 assert!(tester.head < tester.cap());
2748 assert_eq!(tester, expected);
2758 // This test checks that every single combination of tail position, length, and
2759 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2761 let mut tester = VecDeque::with_capacity(15);
2762 // can't guarantee we got 15, so have to get what we got.
2763 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2764 // this test isn't covering what it wants to
2765 let cap = tester.capacity();
2768 // len is the length *after* insertion
2770 // 0, 1, 2, .., len - 1
2771 let expected = (0..).take(len).collect::<VecDeque<_>>();
2772 for tail_pos in 0..cap {
2773 for to_insert in 0..len {
2774 tester.tail = tail_pos;
2775 tester.head = tail_pos;
2778 tester.push_back(i);
2781 tester.insert(to_insert, to_insert);
2782 assert!(tester.tail < tester.cap());
2783 assert!(tester.head < tester.cap());
2784 assert_eq!(tester, expected);
2792 // This test checks that every single combination of tail position, length, and
2793 // removal position is tested. Capacity 15 should be large enough to cover every case.
2795 let mut tester = VecDeque::with_capacity(15);
2796 // can't guarantee we got 15, so have to get what we got.
2797 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2798 // this test isn't covering what it wants to
2799 let cap = tester.capacity();
2801 // len is the length *after* removal
2802 for len in 0..cap - 1 {
2803 // 0, 1, 2, .., len - 1
2804 let expected = (0..).take(len).collect::<VecDeque<_>>();
2805 for tail_pos in 0..cap {
2806 for to_remove in 0..len + 1 {
2807 tester.tail = tail_pos;
2808 tester.head = tail_pos;
2811 tester.push_back(1234);
2813 tester.push_back(i);
2815 if to_remove == len {
2816 tester.push_back(1234);
2818 tester.remove(to_remove);
2819 assert!(tester.tail < tester.cap());
2820 assert!(tester.head < tester.cap());
2821 assert_eq!(tester, expected);
2829 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2831 let cap = tester.capacity();
2832 for len in 0..cap + 1 {
2833 for tail in 0..cap + 1 {
2834 for drain_start in 0..len + 1 {
2835 for drain_end in drain_start..len + 1 {
2839 tester.push_back(i);
2842 // Check that we drain the correct values
2843 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2844 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2845 assert_eq!(drained, drained_expected);
2847 // We shouldn't have changed the capacity or made the
2848 // head or tail out of bounds
2849 assert_eq!(tester.capacity(), cap);
2850 assert!(tester.tail < tester.cap());
2851 assert!(tester.head < tester.cap());
2853 // We should see the correct values in the VecDeque
2854 let expected: VecDeque<_> = (0..drain_start)
2855 .chain(drain_end..len)
2857 assert_eq!(expected, tester);
2865 fn test_shrink_to_fit() {
2866 // This test checks that every single combination of head and tail position,
2867 // is tested. Capacity 15 should be large enough to cover every case.
2869 let mut tester = VecDeque::with_capacity(15);
2870 // can't guarantee we got 15, so have to get what we got.
2871 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2872 // this test isn't covering what it wants to
2873 let cap = tester.capacity();
2875 let max_cap = tester.capacity();
2877 for len in 0..cap + 1 {
2878 // 0, 1, 2, .., len - 1
2879 let expected = (0..).take(len).collect::<VecDeque<_>>();
2880 for tail_pos in 0..max_cap + 1 {
2881 tester.tail = tail_pos;
2882 tester.head = tail_pos;
2885 tester.push_back(i);
2887 tester.shrink_to_fit();
2888 assert!(tester.capacity() <= cap);
2889 assert!(tester.tail < tester.cap());
2890 assert!(tester.head < tester.cap());
2891 assert_eq!(tester, expected);
2897 fn test_split_off() {
2898 // This test checks that every single combination of tail position, length, and
2899 // split position is tested. Capacity 15 should be large enough to cover every case.
2901 let mut tester = VecDeque::with_capacity(15);
2902 // can't guarantee we got 15, so have to get what we got.
2903 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2904 // this test isn't covering what it wants to
2905 let cap = tester.capacity();
2907 // len is the length *before* splitting
2909 // index to split at
2910 for at in 0..len + 1 {
2911 // 0, 1, 2, .., at - 1 (may be empty)
2912 let expected_self = (0..).take(at).collect::<VecDeque<_>>();
2913 // at, at + 1, .., len - 1 (may be empty)
2914 let expected_other = (at..).take(len - at).collect::<VecDeque<_>>();
2916 for tail_pos in 0..cap {
2917 tester.tail = tail_pos;
2918 tester.head = tail_pos;
2920 tester.push_back(i);
2922 let result = tester.split_off(at);
2923 assert!(tester.tail < tester.cap());
2924 assert!(tester.head < tester.cap());
2925 assert!(result.tail < result.cap());
2926 assert!(result.head < result.cap());
2927 assert_eq!(tester, expected_self);
2928 assert_eq!(result, expected_other);
2935 fn test_from_vec() {
2938 for len in 0..cap + 1 {
2939 let mut vec = Vec::with_capacity(cap);
2942 let vd = VecDeque::from(vec.clone());
2943 assert!(vd.cap().is_power_of_two());
2944 assert_eq!(vd.len(), vec.len());
2945 assert!(vd.into_iter().eq(vec));
2951 fn test_vec_from_vecdeque() {
2954 fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
2955 let mut vd = VecDeque::with_capacity(cap);
2956 for _ in 0..offset {
2962 let vec: Vec<_> = Vec::from(vd.clone());
2963 assert_eq!(vec.len(), vd.len());
2964 assert!(vec.into_iter().eq(vd));
2967 for cap_pwr in 0..7 {
2968 // Make capacity as a (2^x)-1, so that the ring size is 2^x
2969 let cap = (2i32.pow(cap_pwr) - 1) as usize;
2971 // In these cases there is enough free space to solve it with copies
2972 for len in 0..((cap + 1) / 2) {
2973 // Test contiguous cases
2974 for offset in 0..(cap - len) {
2975 create_vec_and_test_convert(cap, offset, len)
2978 // Test cases where block at end of buffer is bigger than block at start
2979 for offset in (cap - len)..(cap - (len / 2)) {
2980 create_vec_and_test_convert(cap, offset, len)
2983 // Test cases where block at start of buffer is bigger than block at end
2984 for offset in (cap - (len / 2))..cap {
2985 create_vec_and_test_convert(cap, offset, len)
2989 // Now there's not (necessarily) space to straighten the ring with simple copies,
2990 // the ring will use swapping when:
2991 // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
2992 // right block size > free space && left block size > free space
2993 for len in ((cap + 1) / 2)..cap {
2994 // Test contiguous cases
2995 for offset in 0..(cap - len) {
2996 create_vec_and_test_convert(cap, offset, len)
2999 // Test cases where block at end of buffer is bigger than block at start
3000 for offset in (cap - len)..(cap - (len / 2)) {
3001 create_vec_and_test_convert(cap, offset, len)
3004 // Test cases where block at start of buffer is bigger than block at end
3005 for offset in (cap - (len / 2))..cap {
3006 create_vec_and_test_convert(cap, offset, len)
3016 let mut dst = VecDeque::new();
3017 dst.push_front(Box::new(1));
3018 dst.push_front(Box::new(2));
3019 assert_eq!(*dst.pop_back().unwrap(), 1);
3021 let mut src = VecDeque::new();
3022 src.push_front(Box::new(2));
3023 dst.append(&mut src);