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 //! VecDeque is a double-ended queue, which is implemented with the help of a
12 //! growing ring buffer.
14 //! This queue has `O(1)` amortized inserts and removals from both ends of the
15 //! container. It also has `O(1)` indexing like a vector. The contained elements
16 //! are not required to be copyable, and the queue will be sendable if the
17 //! contained type is sendable.
19 #![stable(feature = "rust1", since = "1.0.0")]
21 use core::cmp::Ordering;
23 use core::iter::{repeat, FromIterator};
25 use core::ops::{Index, IndexMut};
30 use core::hash::{Hash, Hasher};
33 use alloc::raw_vec::RawVec;
35 use super::range::RangeArgument;
37 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
38 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
39 const MAXIMUM_ZST_CAPACITY: usize = 1 << (usize::BITS - 1); // Largest possible power of two
41 /// `VecDeque` is a growable ring buffer, which can be used as a
42 /// double-ended queue efficiently.
44 /// The "default" usage of this type as a queue is to use `push_back` to add to the queue, and
45 /// `pop_front` to remove from the queue. `extend` and `append` push onto the back in this manner,
46 /// and iterating over `VecDeque` goes front to back.
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub struct VecDeque<T> {
49 // tail and head are pointers into the buffer. Tail always points
50 // to the first element that could be read, Head always points
51 // to where data should be written.
52 // If tail == head the buffer is empty. The length of the ringbuffer
53 // is defined as the distance between the two.
60 #[stable(feature = "rust1", since = "1.0.0")]
61 impl<T: Clone> Clone for VecDeque<T> {
62 fn clone(&self) -> VecDeque<T> {
63 self.iter().cloned().collect()
67 #[stable(feature = "rust1", since = "1.0.0")]
68 impl<T> Drop for VecDeque<T> {
69 #[unsafe_destructor_blind_to_params]
72 // RawVec handles deallocation
76 #[stable(feature = "rust1", since = "1.0.0")]
77 impl<T> Default for VecDeque<T> {
79 fn default() -> VecDeque<T> { VecDeque::new() }
83 /// Marginally more convenient
85 fn ptr(&self) -> *mut T {
89 /// Marginally more convenient
91 fn cap(&self) -> usize {
92 if mem::size_of::<T>() == 0 {
93 // For zero sized types, we are always at maximum capacity
100 /// Turn ptr into a slice
102 unsafe fn buffer_as_slice(&self) -> &[T] {
103 slice::from_raw_parts(self.ptr(), self.cap())
106 /// Turn ptr into a mut slice
108 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
109 slice::from_raw_parts_mut(self.ptr(), self.cap())
112 /// Moves an element out of the buffer
114 unsafe fn buffer_read(&mut self, off: usize) -> T {
115 ptr::read(self.ptr().offset(off as isize))
118 /// Writes an element into the buffer, moving it.
120 unsafe fn buffer_write(&mut self, off: usize, value: T) {
121 ptr::write(self.ptr().offset(off as isize), value);
124 /// Returns true if and only if the buffer is at capacity
126 fn is_full(&self) -> bool { self.cap() - self.len() == 1 }
128 /// Returns the index in the underlying buffer for a given logical element
131 fn wrap_index(&self, idx: usize) -> usize { wrap_index(idx, self.cap()) }
133 /// Returns the index in the underlying buffer for a given logical element
136 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
137 wrap_index(idx.wrapping_add(addend), self.cap())
140 /// Returns the index in the underlying buffer for a given logical element
141 /// index - subtrahend.
143 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
144 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
147 /// Copies a contiguous block of memory len long from src to dst
149 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
150 debug_assert!(dst + len <= self.cap(), "dst={} src={} len={} cap={}", dst, src, len,
152 debug_assert!(src + len <= self.cap(), "dst={} src={} len={} cap={}", dst, src, len,
155 self.ptr().offset(src as isize),
156 self.ptr().offset(dst as isize),
160 /// Copies a contiguous block of memory len long from src to dst
162 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
163 debug_assert!(dst + len <= self.cap(), "dst={} src={} len={} cap={}", dst, src, len,
165 debug_assert!(src + len <= self.cap(), "dst={} src={} len={} cap={}", dst, src, len,
167 ptr::copy_nonoverlapping(
168 self.ptr().offset(src as isize),
169 self.ptr().offset(dst as isize),
173 /// Copies a potentially wrapping block of memory len long from src to dest.
174 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
175 /// most one continuous overlapping region between src and dest).
176 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
178 (if src <= dst { dst - src } else { src - dst }) + len <= self.cap(),
179 "dst={} src={} len={} cap={}", dst, src, len, self.cap());
181 if src == dst || len == 0 { return }
183 let dst_after_src = self.wrap_sub(dst, src) < len;
185 let src_pre_wrap_len = self.cap() - src;
186 let dst_pre_wrap_len = self.cap() - dst;
187 let src_wraps = src_pre_wrap_len < len;
188 let dst_wraps = dst_pre_wrap_len < len;
190 match (dst_after_src, src_wraps, dst_wraps) {
191 (_, false, false) => {
192 // src doesn't wrap, dst doesn't wrap
195 // 1 [_ _ A A B B C C _]
196 // 2 [_ _ A A A A B B _]
199 self.copy(dst, src, len);
201 (false, false, true) => {
202 // dst before src, src doesn't wrap, dst wraps
205 // 1 [A A B B _ _ _ C C]
206 // 2 [A A B B _ _ _ A A]
207 // 3 [B B B B _ _ _ A A]
210 self.copy(dst, src, dst_pre_wrap_len);
211 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
213 (true, false, true) => {
214 // src before dst, src doesn't wrap, dst wraps
217 // 1 [C C _ _ _ A A B B]
218 // 2 [B B _ _ _ A A B B]
219 // 3 [B B _ _ _ A A A A]
222 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
223 self.copy(dst, src, dst_pre_wrap_len);
225 (false, true, false) => {
226 // dst before src, src wraps, dst doesn't wrap
229 // 1 [C C _ _ _ A A B B]
230 // 2 [C C _ _ _ B B B B]
231 // 3 [C C _ _ _ B B C C]
234 self.copy(dst, src, src_pre_wrap_len);
235 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
237 (true, true, false) => {
238 // src before dst, src wraps, dst doesn't wrap
241 // 1 [A A B B _ _ _ C C]
242 // 2 [A A A A _ _ _ C C]
243 // 3 [C C A A _ _ _ C C]
246 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
247 self.copy(dst, src, src_pre_wrap_len);
249 (false, true, true) => {
250 // dst before src, src wraps, dst wraps
253 // 1 [A B C D _ E F G H]
254 // 2 [A B C D _ E G H H]
255 // 3 [A B C D _ E G H A]
256 // 4 [B C C D _ E G H A]
259 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
260 let delta = dst_pre_wrap_len - src_pre_wrap_len;
261 self.copy(dst, src, src_pre_wrap_len);
262 self.copy(dst + src_pre_wrap_len, 0, delta);
263 self.copy(0, delta, len - dst_pre_wrap_len);
265 (true, true, true) => {
266 // src before dst, src wraps, dst wraps
269 // 1 [A B C D _ E F G H]
270 // 2 [A A B D _ E F G H]
271 // 3 [H A B D _ E F G H]
272 // 4 [H A B D _ E F F G]
275 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
276 let delta = src_pre_wrap_len - dst_pre_wrap_len;
277 self.copy(delta, 0, len - src_pre_wrap_len);
278 self.copy(0, self.cap() - delta, delta);
279 self.copy(dst, src, dst_pre_wrap_len);
284 /// Frobs the head and tail sections around to handle the fact that we
285 /// just reallocated. Unsafe because it trusts old_cap.
287 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
288 let new_cap = self.cap();
290 // Move the shortest contiguous section of the ring buffer
292 // [o o o o o o o . ]
294 // A [o o o o o o o . . . . . . . . . ]
296 // [o o . o o o o o ]
298 // B [. . . o o o o o o o . . . . . . ]
300 // [o o o o o . o o ]
302 // C [o o o o o . . . . . . . . . o o ]
304 if self.tail <= self.head { // A
306 } else if self.head < old_cap - self.tail { // B
307 self.copy_nonoverlapping(old_cap, 0, self.head);
308 self.head += old_cap;
309 debug_assert!(self.head > self.tail);
311 let new_tail = new_cap - (old_cap - self.tail);
312 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
313 self.tail = new_tail;
314 debug_assert!(self.head < self.tail);
316 debug_assert!(self.head < self.cap());
317 debug_assert!(self.tail < self.cap());
318 debug_assert!(self.cap().count_ones() == 1);
322 impl<T> VecDeque<T> {
323 /// Creates an empty `VecDeque`.
324 #[stable(feature = "rust1", since = "1.0.0")]
325 pub fn new() -> VecDeque<T> {
326 VecDeque::with_capacity(INITIAL_CAPACITY)
329 /// Creates an empty `VecDeque` with space for at least `n` elements.
330 #[stable(feature = "rust1", since = "1.0.0")]
331 pub fn with_capacity(n: usize) -> VecDeque<T> {
332 // +1 since the ringbuffer always leaves one space empty
333 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
334 assert!(cap > n, "capacity overflow");
339 buf: RawVec::with_capacity(cap),
343 /// Retrieves an element in the `VecDeque` by index.
348 /// use std::collections::VecDeque;
350 /// let mut buf = VecDeque::new();
351 /// buf.push_back(3);
352 /// buf.push_back(4);
353 /// buf.push_back(5);
354 /// assert_eq!(buf.get(1), Some(&4));
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn get(&self, index: usize) -> Option<&T> {
358 if index < self.len() {
359 let idx = self.wrap_add(self.tail, index);
360 unsafe { Some(&*self.ptr().offset(idx as isize)) }
366 /// Retrieves an element in the `VecDeque` mutably by index.
371 /// use std::collections::VecDeque;
373 /// let mut buf = VecDeque::new();
374 /// buf.push_back(3);
375 /// buf.push_back(4);
376 /// buf.push_back(5);
377 /// if let Some(elem) = buf.get_mut(1) {
381 /// assert_eq!(buf[1], 7);
383 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
385 if index < self.len() {
386 let idx = self.wrap_add(self.tail, index);
387 unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
393 /// Swaps elements at indices `i` and `j`.
395 /// `i` and `j` may be equal.
397 /// Fails if there is no element with either index.
402 /// use std::collections::VecDeque;
404 /// let mut buf = VecDeque::new();
405 /// buf.push_back(3);
406 /// buf.push_back(4);
407 /// buf.push_back(5);
409 /// assert_eq!(buf[0], 5);
410 /// assert_eq!(buf[2], 3);
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub fn swap(&mut self, i: usize, j: usize) {
414 assert!(i < self.len());
415 assert!(j < self.len());
416 let ri = self.wrap_add(self.tail, i);
417 let rj = self.wrap_add(self.tail, j);
419 ptr::swap(self.ptr().offset(ri as isize), self.ptr().offset(rj as isize))
423 /// Returns the number of elements the `VecDeque` can hold without
429 /// use std::collections::VecDeque;
431 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
432 /// assert!(buf.capacity() >= 10);
435 #[stable(feature = "rust1", since = "1.0.0")]
436 pub fn capacity(&self) -> usize { self.cap() - 1 }
438 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
439 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
441 /// Note that the allocator may give the collection more space than it requests. Therefore
442 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
443 /// insertions are expected.
447 /// Panics if the new capacity overflows `usize`.
452 /// use std::collections::VecDeque;
454 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
455 /// buf.reserve_exact(10);
456 /// assert!(buf.capacity() >= 11);
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn reserve_exact(&mut self, additional: usize) {
460 self.reserve(additional);
463 /// Reserves capacity for at least `additional` more elements to be inserted in the given
464 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
468 /// Panics if the new capacity overflows `usize`.
473 /// use std::collections::VecDeque;
475 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
477 /// assert!(buf.capacity() >= 11);
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn reserve(&mut self, additional: usize) {
481 let old_cap = self.cap();
482 let used_cap = self.len() + 1;
483 let new_cap = used_cap
484 .checked_add(additional)
485 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
486 .expect("capacity overflow");
488 if new_cap > self.capacity() {
489 self.buf.reserve_exact(used_cap, new_cap - used_cap);
490 unsafe { self.handle_cap_increase(old_cap); }
494 /// Shrinks the capacity of the `VecDeque` as much as possible.
496 /// It will drop down as close as possible to the length but the allocator may still inform the
497 /// `VecDeque` that there is space for a few more elements.
502 /// #![feature(deque_extras)]
504 /// use std::collections::VecDeque;
506 /// let mut buf = VecDeque::with_capacity(15);
507 /// buf.extend(0..4);
508 /// assert_eq!(buf.capacity(), 15);
509 /// buf.shrink_to_fit();
510 /// assert!(buf.capacity() >= 4);
512 #[unstable(feature = "deque_extras",
513 reason = "needs to be audited",
515 pub fn shrink_to_fit(&mut self) {
516 // +1 since the ringbuffer always leaves one space empty
517 // len + 1 can't overflow for an existing, well-formed ringbuffer.
518 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
519 if target_cap < self.cap() {
520 // There are three cases of interest:
521 // All elements are out of desired bounds
522 // Elements are contiguous, and head is out of desired bounds
523 // Elements are discontiguous, and tail is out of desired bounds
525 // At all other times, element positions are unaffected.
527 // Indicates that elements at the head should be moved.
528 let head_outside = self.head == 0 || self.head >= target_cap;
529 // Move elements from out of desired bounds (positions after target_cap)
530 if self.tail >= target_cap && head_outside {
532 // [. . . . . . . . o o o o o o o . ]
534 // [o o o o o o o . ]
536 self.copy_nonoverlapping(0, self.tail, self.len());
538 self.head = self.len();
540 } else if self.tail != 0 && self.tail < target_cap && head_outside {
542 // [. . . o o o o o o o . . . . . . ]
544 // [o o . o o o o o ]
545 let len = self.wrap_sub(self.head, target_cap);
547 self.copy_nonoverlapping(0, target_cap, len);
550 debug_assert!(self.head < self.tail);
551 } else if self.tail >= target_cap {
553 // [o o o o o . . . . . . . . . o o ]
555 // [o o o o o . o o ]
556 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
557 let len = self.cap() - self.tail;
558 let new_tail = target_cap - len;
560 self.copy_nonoverlapping(new_tail, self.tail, len);
562 self.tail = new_tail;
563 debug_assert!(self.head < self.tail);
566 self.buf.shrink_to_fit(target_cap);
568 debug_assert!(self.head < self.cap());
569 debug_assert!(self.tail < self.cap());
570 debug_assert!(self.cap().count_ones() == 1);
574 /// Shortens a `VecDeque`, dropping excess elements from the back.
576 /// If `len` is greater than the `VecDeque`'s current length, this has no
582 /// #![feature(deque_extras)]
584 /// use std::collections::VecDeque;
586 /// let mut buf = VecDeque::new();
587 /// buf.push_back(5);
588 /// buf.push_back(10);
589 /// buf.push_back(15);
591 /// assert_eq!(buf.len(), 1);
592 /// assert_eq!(Some(&5), buf.get(0));
594 #[unstable(feature = "deque_extras",
595 reason = "matches collection reform specification; waiting on panic semantics",
597 pub fn truncate(&mut self, len: usize) {
598 for _ in len..self.len() {
603 /// Returns a front-to-back iterator.
608 /// use std::collections::VecDeque;
610 /// let mut buf = VecDeque::new();
611 /// buf.push_back(5);
612 /// buf.push_back(3);
613 /// buf.push_back(4);
614 /// let b: &[_] = &[&5, &3, &4];
615 /// let c: Vec<&i32> = buf.iter().collect();
616 /// assert_eq!(&c[..], b);
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub fn iter(&self) -> Iter<T> {
623 ring: unsafe { self.buffer_as_slice() }
627 /// Returns a front-to-back iterator that returns mutable references.
632 /// use std::collections::VecDeque;
634 /// let mut buf = VecDeque::new();
635 /// buf.push_back(5);
636 /// buf.push_back(3);
637 /// buf.push_back(4);
638 /// for num in buf.iter_mut() {
641 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
642 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
644 #[stable(feature = "rust1", since = "1.0.0")]
645 pub fn iter_mut(&mut self) -> IterMut<T> {
649 ring: unsafe { self.buffer_as_mut_slice() },
653 /// Returns a pair of slices which contain, in order, the contents of the
656 #[unstable(feature = "deque_extras",
657 reason = "matches collection reform specification, waiting for dust to settle",
659 pub fn as_slices(&self) -> (&[T], &[T]) {
661 let contiguous = self.is_contiguous();
662 let buf = self.buffer_as_slice();
664 let (empty, buf) = buf.split_at(0);
665 (&buf[self.tail..self.head], empty)
667 let (mid, right) = buf.split_at(self.tail);
668 let (left, _) = mid.split_at(self.head);
674 /// Returns a pair of slices which contain, in order, the contents of the
677 #[unstable(feature = "deque_extras",
678 reason = "matches collection reform specification, waiting for dust to settle",
680 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
682 let contiguous = self.is_contiguous();
683 let head = self.head;
684 let tail = self.tail;
685 let buf = self.buffer_as_mut_slice();
688 let (empty, buf) = buf.split_at_mut(0);
689 (&mut buf[tail .. head], empty)
691 let (mid, right) = buf.split_at_mut(tail);
692 let (left, _) = mid.split_at_mut(head);
699 /// Returns the number of elements in the `VecDeque`.
704 /// use std::collections::VecDeque;
706 /// let mut v = VecDeque::new();
707 /// assert_eq!(v.len(), 0);
709 /// assert_eq!(v.len(), 1);
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn len(&self) -> usize { count(self.tail, self.head, self.cap()) }
714 /// Returns true if the buffer contains no elements
719 /// use std::collections::VecDeque;
721 /// let mut v = VecDeque::new();
722 /// assert!(v.is_empty());
724 /// assert!(!v.is_empty());
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn is_empty(&self) -> bool { self.len() == 0 }
729 /// Create a draining iterator that removes the specified range in the
730 /// `VecDeque` and yields the removed items from start to end. The element
731 /// range is removed even if the iterator is not consumed until the end.
733 /// Note: It is unspecified how many elements are removed from the deque,
734 /// if the `Drain` value is not dropped, but the borrow it holds expires
735 /// (eg. due to mem::forget).
739 /// Panics if the starting point is greater than the end point or if
740 /// the end point is greater than the length of the vector.
745 /// #![feature(drain)]
747 /// use std::collections::VecDeque;
749 /// // draining using `..` clears the whole deque.
750 /// let mut v = VecDeque::new();
752 /// assert_eq!(v.drain(..).next(), Some(1));
753 /// assert!(v.is_empty());
756 #[unstable(feature = "drain",
757 reason = "matches collection reform specification, waiting for dust to settle",
759 pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> {
762 // When the Drain is first created, the source deque is shortened to
763 // make sure no uninitialized or moved-from elements are accessible at
764 // all if the Drain's destructor never gets to run.
766 // Drain will ptr::read out the values to remove.
767 // When finished, the remaining data will be copied back to cover the hole,
768 // and the head/tail values will be restored correctly.
770 let len = self.len();
771 let start = *range.start().unwrap_or(&0);
772 let end = *range.end().unwrap_or(&len);
773 assert!(start <= end, "drain lower bound was too large");
774 assert!(end <= len, "drain upper bound was too large");
776 // The deque's elements are parted into three segments:
777 // * self.tail -> drain_tail
778 // * drain_tail -> drain_head
779 // * drain_head -> self.head
781 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
783 // We store drain_tail as self.head, and drain_head and self.head as
784 // after_tail and after_head respectively on the Drain. This also
785 // truncates the effective array such that if the Drain is leaked, we
786 // have forgotten about the potentially moved values after the start of
790 // [. . . o o x x o o . . .]
792 let drain_tail = self.wrap_add(self.tail, start);
793 let drain_head = self.wrap_add(self.tail, end);
794 let head = self.head;
796 // "forget" about the values after the start of the drain until after
797 // the drain is complete and the Drain destructor is run.
798 self.head = drain_tail;
801 deque: self as *mut _,
802 after_tail: drain_head,
807 ring: unsafe { self.buffer_as_mut_slice() },
812 /// Clears the buffer, removing all values.
817 /// use std::collections::VecDeque;
819 /// let mut v = VecDeque::new();
822 /// assert!(v.is_empty());
824 #[stable(feature = "rust1", since = "1.0.0")]
826 pub fn clear(&mut self) {
830 /// Provides a reference to the front element, or `None` if the sequence is
836 /// use std::collections::VecDeque;
838 /// let mut d = VecDeque::new();
839 /// assert_eq!(d.front(), None);
843 /// assert_eq!(d.front(), Some(&1));
845 #[stable(feature = "rust1", since = "1.0.0")]
846 pub fn front(&self) -> Option<&T> {
847 if !self.is_empty() { Some(&self[0]) } else { None }
850 /// Provides a mutable reference to the front element, or `None` if the
851 /// sequence is empty.
856 /// use std::collections::VecDeque;
858 /// let mut d = VecDeque::new();
859 /// assert_eq!(d.front_mut(), None);
863 /// match d.front_mut() {
864 /// Some(x) => *x = 9,
867 /// assert_eq!(d.front(), Some(&9));
869 #[stable(feature = "rust1", since = "1.0.0")]
870 pub fn front_mut(&mut self) -> Option<&mut T> {
871 if !self.is_empty() { Some(&mut self[0]) } else { None }
874 /// Provides a reference to the back element, or `None` if the sequence is
880 /// use std::collections::VecDeque;
882 /// let mut d = VecDeque::new();
883 /// assert_eq!(d.back(), None);
887 /// assert_eq!(d.back(), Some(&2));
889 #[stable(feature = "rust1", since = "1.0.0")]
890 pub fn back(&self) -> Option<&T> {
891 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
894 /// Provides a mutable reference to the back element, or `None` if the
895 /// sequence is empty.
900 /// use std::collections::VecDeque;
902 /// let mut d = VecDeque::new();
903 /// assert_eq!(d.back(), None);
907 /// match d.back_mut() {
908 /// Some(x) => *x = 9,
911 /// assert_eq!(d.back(), Some(&9));
913 #[stable(feature = "rust1", since = "1.0.0")]
914 pub fn back_mut(&mut self) -> Option<&mut T> {
915 let len = self.len();
916 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
919 /// Removes the first element and returns it, or `None` if the sequence is
925 /// use std::collections::VecDeque;
927 /// let mut d = VecDeque::new();
931 /// assert_eq!(d.pop_front(), Some(1));
932 /// assert_eq!(d.pop_front(), Some(2));
933 /// assert_eq!(d.pop_front(), None);
935 #[stable(feature = "rust1", since = "1.0.0")]
936 pub fn pop_front(&mut self) -> Option<T> {
940 let tail = self.tail;
941 self.tail = self.wrap_add(self.tail, 1);
942 unsafe { Some(self.buffer_read(tail)) }
946 /// Inserts an element first in the sequence.
951 /// use std::collections::VecDeque;
953 /// let mut d = VecDeque::new();
956 /// assert_eq!(d.front(), Some(&2));
958 #[stable(feature = "rust1", since = "1.0.0")]
959 pub fn push_front(&mut self, value: T) {
961 let old_cap = self.cap();
963 unsafe { self.handle_cap_increase(old_cap); }
964 debug_assert!(!self.is_full());
967 self.tail = self.wrap_sub(self.tail, 1);
968 let tail = self.tail;
969 unsafe { self.buffer_write(tail, value); }
972 /// Appends an element to the back of a buffer
977 /// use std::collections::VecDeque;
979 /// let mut buf = VecDeque::new();
980 /// buf.push_back(1);
981 /// buf.push_back(3);
982 /// assert_eq!(3, *buf.back().unwrap());
984 #[stable(feature = "rust1", since = "1.0.0")]
985 pub fn push_back(&mut self, value: T) {
987 let old_cap = self.cap();
989 unsafe { self.handle_cap_increase(old_cap); }
990 debug_assert!(!self.is_full());
993 let head = self.head;
994 self.head = self.wrap_add(self.head, 1);
995 unsafe { self.buffer_write(head, value) }
998 /// Removes the last element from a buffer and returns it, or `None` if
1004 /// use std::collections::VecDeque;
1006 /// let mut buf = VecDeque::new();
1007 /// assert_eq!(buf.pop_back(), None);
1008 /// buf.push_back(1);
1009 /// buf.push_back(3);
1010 /// assert_eq!(buf.pop_back(), Some(3));
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub fn pop_back(&mut self) -> Option<T> {
1014 if self.is_empty() {
1017 self.head = self.wrap_sub(self.head, 1);
1018 let head = self.head;
1019 unsafe { Some(self.buffer_read(head)) }
1024 fn is_contiguous(&self) -> bool {
1025 self.tail <= self.head
1028 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1031 /// This does not preserve ordering, but is O(1).
1033 /// Returns `None` if `index` is out of bounds.
1038 /// #![feature(deque_extras)]
1040 /// use std::collections::VecDeque;
1042 /// let mut buf = VecDeque::new();
1043 /// assert_eq!(buf.swap_back_remove(0), None);
1044 /// buf.push_back(1);
1045 /// buf.push_back(2);
1046 /// buf.push_back(3);
1048 /// assert_eq!(buf.swap_back_remove(0), Some(1));
1049 /// assert_eq!(buf.len(), 2);
1050 /// assert_eq!(buf[0], 3);
1051 /// assert_eq!(buf[1], 2);
1053 #[unstable(feature = "deque_extras",
1054 reason = "the naming of this function may be altered",
1056 pub fn swap_back_remove(&mut self, index: usize) -> Option<T> {
1057 let length = self.len();
1058 if length > 0 && index < length - 1 {
1059 self.swap(index, length - 1);
1060 } else if index >= length {
1066 /// Removes an element from anywhere in the `VecDeque` and returns it,
1067 /// replacing it with the first element.
1069 /// This does not preserve ordering, but is O(1).
1071 /// Returns `None` if `index` is out of bounds.
1076 /// #![feature(deque_extras)]
1078 /// use std::collections::VecDeque;
1080 /// let mut buf = VecDeque::new();
1081 /// assert_eq!(buf.swap_front_remove(0), None);
1082 /// buf.push_back(1);
1083 /// buf.push_back(2);
1084 /// buf.push_back(3);
1086 /// assert_eq!(buf.swap_front_remove(2), Some(3));
1087 /// assert_eq!(buf.len(), 2);
1088 /// assert_eq!(buf[0], 2);
1089 /// assert_eq!(buf[1], 1);
1091 #[unstable(feature = "deque_extras",
1092 reason = "the naming of this function may be altered",
1094 pub fn swap_front_remove(&mut self, index: usize) -> Option<T> {
1095 let length = self.len();
1096 if length > 0 && index < length && index != 0 {
1097 self.swap(index, 0);
1098 } else if index >= length {
1104 /// Inserts an element at `index` within the `VecDeque`. Whichever
1105 /// end is closer to the insertion point will be moved to make room,
1106 /// and all the affected elements will be moved to new positions.
1110 /// Panics if `index` is greater than `VecDeque`'s length
1114 /// #![feature(deque_extras)]
1116 /// use std::collections::VecDeque;
1118 /// let mut buf = VecDeque::new();
1119 /// buf.push_back(10);
1120 /// buf.push_back(12);
1121 /// buf.insert(1, 11);
1122 /// assert_eq!(Some(&11), buf.get(1));
1124 #[unstable(feature = "deque_extras",
1125 reason = "needs to be audited",
1127 pub fn insert(&mut self, index: usize, value: T) {
1128 assert!(index <= self.len(), "index out of bounds");
1130 let old_cap = self.cap();
1132 unsafe { self.handle_cap_increase(old_cap); }
1133 debug_assert!(!self.is_full());
1136 // Move the least number of elements in the ring buffer and insert
1139 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1141 // There are three main cases:
1142 // Elements are contiguous
1143 // - special case when tail is 0
1144 // Elements are discontiguous and the insert is in the tail section
1145 // Elements are discontiguous and the insert is in the head section
1147 // For each of those there are two more cases:
1148 // Insert is closer to tail
1149 // Insert is closer to head
1151 // Key: H - self.head
1153 // o - Valid element
1154 // I - Insertion element
1155 // A - The element that should be after the insertion point
1156 // M - Indicates element was moved
1158 let idx = self.wrap_add(self.tail, index);
1160 let distance_to_tail = index;
1161 let distance_to_head = self.len() - index;
1163 let contiguous = self.is_contiguous();
1165 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1166 (true, true, _) if index == 0 => {
1171 // [A o o o o o o . . . . . . . . .]
1174 // [A o o o o o o o . . . . . I]
1177 self.tail = self.wrap_sub(self.tail, 1);
1179 (true, true, _) => unsafe {
1180 // contiguous, insert closer to tail:
1183 // [. . . o o A o o o o . . . . . .]
1186 // [. . o o I A o o o o . . . . . .]
1189 // contiguous, insert closer to tail and tail is 0:
1193 // [o o A o o o o . . . . . . . . .]
1196 // [o I A o o o o o . . . . . . . o]
1199 let new_tail = self.wrap_sub(self.tail, 1);
1201 self.copy(new_tail, self.tail, 1);
1202 // Already moved the tail, so we only copy `index - 1` elements.
1203 self.copy(self.tail, self.tail + 1, index - 1);
1205 self.tail = new_tail;
1207 (true, false, _) => unsafe {
1208 // contiguous, insert closer to head:
1211 // [. . . o o o o A o o . . . . . .]
1214 // [. . . o o o o I A o o . . . . .]
1217 self.copy(idx + 1, idx, self.head - idx);
1218 self.head = self.wrap_add(self.head, 1);
1220 (false, true, true) => unsafe {
1221 // discontiguous, insert closer to tail, tail section:
1224 // [o o o o o o . . . . . o o A o o]
1227 // [o o o o o o . . . . o o I A o o]
1230 self.copy(self.tail - 1, self.tail, index);
1233 (false, false, true) => unsafe {
1234 // discontiguous, insert closer to head, tail section:
1237 // [o o . . . . . . . o o o o o A o]
1240 // [o o o . . . . . . o o o o o I A]
1243 // copy elements up to new head
1244 self.copy(1, 0, self.head);
1246 // copy last element into empty spot at bottom of buffer
1247 self.copy(0, self.cap() - 1, 1);
1249 // move elements from idx to end forward not including ^ element
1250 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1254 (false, true, false) if idx == 0 => unsafe {
1255 // discontiguous, insert is closer to tail, head section,
1256 // and is at index zero in the internal buffer:
1259 // [A o o o o o o o o o . . . o o o]
1262 // [A o o o o o o o o o . . o o o I]
1265 // copy elements up to new tail
1266 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1268 // copy last element into empty spot at bottom of buffer
1269 self.copy(self.cap() - 1, 0, 1);
1273 (false, true, false) => unsafe {
1274 // discontiguous, insert closer to tail, head section:
1277 // [o o o A o o o o o o . . . o o o]
1280 // [o o I A o o o o o o . . o o o o]
1283 // copy elements up to new tail
1284 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1286 // copy last element into empty spot at bottom of buffer
1287 self.copy(self.cap() - 1, 0, 1);
1289 // move elements from idx-1 to end forward not including ^ element
1290 self.copy(0, 1, idx - 1);
1294 (false, false, false) => unsafe {
1295 // discontiguous, insert closer to head, head section:
1298 // [o o o o A o o . . . . . . o o o]
1301 // [o o o o I A o o . . . . . o o o]
1304 self.copy(idx + 1, idx, self.head - idx);
1309 // tail might've been changed so we need to recalculate
1310 let new_idx = self.wrap_add(self.tail, index);
1312 self.buffer_write(new_idx, value);
1316 /// Removes and returns the element at `index` from the `VecDeque`.
1317 /// Whichever end is closer to the removal point will be moved to make
1318 /// room, and all the affected elements will be moved to new positions.
1319 /// Returns `None` if `index` is out of bounds.
1323 /// use std::collections::VecDeque;
1325 /// let mut buf = VecDeque::new();
1326 /// buf.push_back(1);
1327 /// buf.push_back(2);
1328 /// buf.push_back(3);
1330 /// assert_eq!(buf.remove(1), Some(2));
1331 /// assert_eq!(buf.get(1), Some(&3));
1333 #[stable(feature = "rust1", since = "1.0.0")]
1334 pub fn remove(&mut self, index: usize) -> Option<T> {
1335 if self.is_empty() || self.len() <= index {
1339 // There are three main cases:
1340 // Elements are contiguous
1341 // Elements are discontiguous and the removal is in the tail section
1342 // Elements are discontiguous and the removal is in the head section
1343 // - special case when elements are technically contiguous,
1344 // but self.head = 0
1346 // For each of those there are two more cases:
1347 // Insert is closer to tail
1348 // Insert is closer to head
1350 // Key: H - self.head
1352 // o - Valid element
1353 // x - Element marked for removal
1354 // R - Indicates element that is being removed
1355 // M - Indicates element was moved
1357 let idx = self.wrap_add(self.tail, index);
1360 Some(self.buffer_read(idx))
1363 let distance_to_tail = index;
1364 let distance_to_head = self.len() - index;
1366 let contiguous = self.is_contiguous();
1368 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1369 (true, true, _) => unsafe {
1370 // contiguous, remove closer to tail:
1373 // [. . . o o x o o o o . . . . . .]
1376 // [. . . . o o o o o o . . . . . .]
1379 self.copy(self.tail + 1, self.tail, index);
1382 (true, false, _) => unsafe {
1383 // contiguous, remove closer to head:
1386 // [. . . o o o o x o o . . . . . .]
1389 // [. . . o o o o o o . . . . . . .]
1392 self.copy(idx, idx + 1, self.head - idx - 1);
1395 (false, true, true) => unsafe {
1396 // discontiguous, remove closer to tail, tail section:
1399 // [o o o o o o . . . . . o o x o o]
1402 // [o o o o o o . . . . . . o o o o]
1405 self.copy(self.tail + 1, self.tail, index);
1406 self.tail = self.wrap_add(self.tail, 1);
1408 (false, false, false) => unsafe {
1409 // discontiguous, remove closer to head, head section:
1412 // [o o o o x o o . . . . . . o o o]
1415 // [o o o o o o . . . . . . . o o o]
1418 self.copy(idx, idx + 1, self.head - idx - 1);
1421 (false, false, true) => unsafe {
1422 // discontiguous, remove closer to head, tail section:
1425 // [o o o . . . . . . o o o o o x o]
1428 // [o o . . . . . . . o o o o o o o]
1431 // or quasi-discontiguous, remove next to head, tail section:
1434 // [. . . . . . . . . o o o o o x o]
1437 // [. . . . . . . . . o o o o o o .]
1440 // draw in elements in the tail section
1441 self.copy(idx, idx + 1, self.cap() - idx - 1);
1443 // Prevents underflow.
1445 // copy first element into empty spot
1446 self.copy(self.cap() - 1, 0, 1);
1448 // move elements in the head section backwards
1449 self.copy(0, 1, self.head - 1);
1452 self.head = self.wrap_sub(self.head, 1);
1454 (false, true, false) => unsafe {
1455 // discontiguous, remove closer to tail, head section:
1458 // [o o x o o o o o o o . . . o o o]
1461 // [o o o o o o o o o o . . . . o o]
1464 // draw in elements up to idx
1465 self.copy(1, 0, idx);
1467 // copy last element into empty spot
1468 self.copy(0, self.cap() - 1, 1);
1470 // move elements from tail to end forward, excluding the last one
1471 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1473 self.tail = self.wrap_add(self.tail, 1);
1480 /// Splits the collection into two at the given index.
1482 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1483 /// and the returned `Self` contains elements `[at, len)`.
1485 /// Note that the capacity of `self` does not change.
1489 /// Panics if `at > len`
1494 /// use std::collections::VecDeque;
1496 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1497 /// let buf2 = buf.split_off(1);
1498 /// // buf = [1], buf2 = [2, 3]
1499 /// assert_eq!(buf.len(), 1);
1500 /// assert_eq!(buf2.len(), 2);
1503 #[stable(feature = "split_off", since = "1.4.0")]
1504 pub fn split_off(&mut self, at: usize) -> Self {
1505 let len = self.len();
1506 assert!(at <= len, "`at` out of bounds");
1508 let other_len = len - at;
1509 let mut other = VecDeque::with_capacity(other_len);
1512 let (first_half, second_half) = self.as_slices();
1514 let first_len = first_half.len();
1515 let second_len = second_half.len();
1517 // `at` lies in the first half.
1518 let amount_in_first = first_len - at;
1520 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1524 // just take all of the second half.
1525 ptr::copy_nonoverlapping(second_half.as_ptr(),
1526 other.ptr().offset(amount_in_first as isize),
1529 // `at` lies in the second half, need to factor in the elements we skipped
1530 // in the first half.
1531 let offset = at - first_len;
1532 let amount_in_second = second_len - offset;
1533 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1539 // Cleanup where the ends of the buffers are
1540 self.head = self.wrap_sub(self.head, other_len);
1541 other.head = other.wrap_index(other_len);
1546 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1550 /// Panics if the new number of elements in self overflows a `usize`.
1555 /// use std::collections::VecDeque;
1557 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1558 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
1559 /// buf.append(&mut buf2);
1560 /// assert_eq!(buf.len(), 6);
1561 /// assert_eq!(buf2.len(), 0);
1564 #[stable(feature = "append", since = "1.4.0")]
1565 pub fn append(&mut self, other: &mut Self) {
1567 self.extend(other.drain(..));
1570 /// Retains only the elements specified by the predicate.
1572 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1573 /// This method operates in place and preserves the order of the retained
1579 /// use std::collections::VecDeque;
1581 /// let mut buf = VecDeque::new();
1582 /// buf.extend(1..5);
1583 /// buf.retain(|&x| x%2 == 0);
1585 /// let v: Vec<_> = buf.into_iter().collect();
1586 /// assert_eq!(&v[..], &[2, 4]);
1588 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1589 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
1590 let len = self.len();
1596 self.swap(i-del, i);
1600 self.truncate(len - del);
1605 impl<T: Clone> VecDeque<T> {
1606 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1607 /// either by removing excess elements or by appending copies of a value to the back.
1612 /// #![feature(deque_extras)]
1614 /// use std::collections::VecDeque;
1616 /// let mut buf = VecDeque::new();
1617 /// buf.push_back(5);
1618 /// buf.push_back(10);
1619 /// buf.push_back(15);
1620 /// buf.resize(2, 0);
1621 /// buf.resize(6, 20);
1622 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
1623 /// assert_eq!(a, b);
1626 #[unstable(feature = "deque_extras",
1627 reason = "matches collection reform specification; waiting on panic semantics",
1629 pub fn resize(&mut self, new_len: usize, value: T) {
1630 let len = self.len();
1633 self.extend(repeat(value).take(new_len - len))
1635 self.truncate(new_len);
1640 /// Returns the index in the underlying buffer for a given logical element index.
1642 fn wrap_index(index: usize, size: usize) -> usize {
1643 // size is always a power of 2
1644 debug_assert!(size.is_power_of_two());
1648 /// Calculate the number of elements left to be read in the buffer
1650 fn count(tail: usize, head: usize, size: usize) -> usize {
1651 // size is always a power of 2
1652 (head.wrapping_sub(tail)) & (size - 1)
1655 /// `VecDeque` iterator.
1656 #[stable(feature = "rust1", since = "1.0.0")]
1657 pub struct Iter<'a, T:'a> {
1663 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1664 impl<'a, T> Clone for Iter<'a, T> {
1665 fn clone(&self) -> Iter<'a, T> {
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 impl<'a, T> Iterator for Iter<'a, T> {
1679 fn next(&mut self) -> Option<&'a T> {
1680 if self.tail == self.head {
1683 let tail = self.tail;
1684 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1685 unsafe { Some(self.ring.get_unchecked(tail)) }
1689 fn size_hint(&self) -> (usize, Option<usize>) {
1690 let len = count(self.tail, self.head, self.ring.len());
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1698 fn next_back(&mut self) -> Option<&'a T> {
1699 if self.tail == self.head {
1702 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1703 unsafe { Some(self.ring.get_unchecked(self.head)) }
1707 #[stable(feature = "rust1", since = "1.0.0")]
1708 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1710 /// `VecDeque` mutable iterator.
1711 #[stable(feature = "rust1", since = "1.0.0")]
1712 pub struct IterMut<'a, T:'a> {
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl<'a, T> Iterator for IterMut<'a, T> {
1720 type Item = &'a mut T;
1723 fn next(&mut self) -> Option<&'a mut T> {
1724 if self.tail == self.head {
1727 let tail = self.tail;
1728 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1731 let elem = self.ring.get_unchecked_mut(tail);
1732 Some(&mut *(elem as *mut _))
1737 fn size_hint(&self) -> (usize, Option<usize>) {
1738 let len = count(self.tail, self.head, self.ring.len());
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1746 fn next_back(&mut self) -> Option<&'a mut T> {
1747 if self.tail == self.head {
1750 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1753 let elem = self.ring.get_unchecked_mut(self.head);
1754 Some(&mut *(elem as *mut _))
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1762 /// A by-value VecDeque iterator
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 pub struct IntoIter<T> {
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 impl<T> Iterator for IntoIter<T> {
1774 fn next(&mut self) -> Option<T> {
1775 self.inner.pop_front()
1779 fn size_hint(&self) -> (usize, Option<usize>) {
1780 let len = self.inner.len();
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 impl<T> DoubleEndedIterator for IntoIter<T> {
1788 fn next_back(&mut self) -> Option<T> {
1789 self.inner.pop_back()
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 impl<T> ExactSizeIterator for IntoIter<T> {}
1796 /// A draining VecDeque iterator
1797 #[unstable(feature = "drain",
1798 reason = "matches collection reform specification, waiting for dust to settle",
1800 pub struct Drain<'a, T: 'a> {
1804 deque: *mut VecDeque<T>,
1807 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1808 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1810 #[stable(feature = "rust1", since = "1.0.0")]
1811 impl<'a, T: 'a> Drop for Drain<'a, T> {
1812 fn drop(&mut self) {
1813 for _ in self.by_ref() {}
1815 let source_deque = unsafe { &mut *self.deque };
1817 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
1820 // [. . . o o x x o o . . .]
1822 let orig_tail = source_deque.tail;
1823 let drain_tail = source_deque.head;
1824 let drain_head = self.after_tail;
1825 let orig_head = self.after_head;
1827 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
1828 let head_len = count(drain_head, orig_head, source_deque.cap());
1830 // Restore the original head value
1831 source_deque.head = orig_head;
1833 match (tail_len, head_len) {
1835 source_deque.head = 0;
1836 source_deque.tail = 0;
1839 source_deque.tail = drain_head;
1842 source_deque.head = drain_tail;
1845 if tail_len <= head_len {
1846 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
1847 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
1849 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
1850 source_deque.wrap_copy(drain_tail, drain_head, head_len);
1857 #[stable(feature = "rust1", since = "1.0.0")]
1858 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1862 fn next(&mut self) -> Option<T> {
1863 self.iter.next().map(|elt|
1871 fn size_hint(&self) -> (usize, Option<usize>) {
1872 self.iter.size_hint()
1876 #[stable(feature = "rust1", since = "1.0.0")]
1877 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1879 fn next_back(&mut self) -> Option<T> {
1880 self.iter.next_back().map(|elt|
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 impl<A: PartialEq> PartialEq for VecDeque<A> {
1893 fn eq(&self, other: &VecDeque<A>) -> bool {
1894 self.len() == other.len() &&
1895 self.iter().zip(other).all(|(a, b)| a.eq(b))
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 impl<A: Eq> Eq for VecDeque<A> {}
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
1904 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
1905 self.iter().partial_cmp(other.iter())
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 impl<A: Ord> Ord for VecDeque<A> {
1912 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
1913 self.iter().cmp(other.iter())
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 impl<A: Hash> Hash for VecDeque<A> {
1919 fn hash<H: Hasher>(&self, state: &mut H) {
1920 self.len().hash(state);
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 impl<A> Index<usize> for VecDeque<A> {
1932 fn index(&self, index: usize) -> &A {
1933 self.get(index).expect("Out of bounds access")
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl<A> IndexMut<usize> for VecDeque<A> {
1940 fn index_mut(&mut self, index: usize) -> &mut A {
1941 self.get_mut(index).expect("Out of bounds access")
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 impl<A> FromIterator<A> for VecDeque<A> {
1947 fn from_iter<T: IntoIterator<Item=A>>(iterable: T) -> VecDeque<A> {
1948 let iterator = iterable.into_iter();
1949 let (lower, _) = iterator.size_hint();
1950 let mut deq = VecDeque::with_capacity(lower);
1951 deq.extend(iterator);
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 impl<T> IntoIterator for VecDeque<T> {
1959 type IntoIter = IntoIter<T>;
1961 /// Consumes the list into a front-to-back iterator yielding elements by
1963 fn into_iter(self) -> IntoIter<T> {
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 impl<'a, T> IntoIterator for &'a VecDeque<T> {
1973 type IntoIter = Iter<'a, T>;
1975 fn into_iter(self) -> Iter<'a, T> {
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
1982 type Item = &'a mut T;
1983 type IntoIter = IterMut<'a, T>;
1985 fn into_iter(mut self) -> IterMut<'a, T> {
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 impl<A> Extend<A> for VecDeque<A> {
1992 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
1994 self.push_back(elt);
1999 #[stable(feature = "extend_ref", since = "1.2.0")]
2000 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2001 fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
2002 self.extend(iter.into_iter().cloned());
2006 #[stable(feature = "rust1", since = "1.0.0")]
2007 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2008 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2009 f.debug_list().entries(self).finish()
2015 use core::iter::Iterator;
2016 use core::option::Option::Some;
2020 use super::VecDeque;
2023 fn bench_push_back_100(b: &mut test::Bencher) {
2024 let mut deq = VecDeque::with_capacity(101);
2035 fn bench_push_front_100(b: &mut test::Bencher) {
2036 let mut deq = VecDeque::with_capacity(101);
2047 fn bench_pop_back_100(b: &mut test::Bencher) {
2048 let mut deq= VecDeque::<i32>::with_capacity(101);
2053 while !deq.is_empty() {
2054 test::black_box(deq.pop_back());
2060 fn bench_pop_front_100(b: &mut test::Bencher) {
2061 let mut deq = VecDeque::<i32>::with_capacity(101);
2066 while !deq.is_empty() {
2067 test::black_box(deq.pop_front());
2073 fn test_swap_front_back_remove() {
2074 fn test(back: bool) {
2075 // This test checks that every single combination of tail position and length is tested.
2076 // Capacity 15 should be large enough to cover every case.
2077 let mut tester = VecDeque::with_capacity(15);
2078 let usable_cap = tester.capacity();
2079 let final_len = usable_cap / 2;
2081 for len in 0..final_len {
2082 let expected = if back {
2085 (0..len).rev().collect()
2087 for tail_pos in 0..usable_cap {
2088 tester.tail = tail_pos;
2089 tester.head = tail_pos;
2091 for i in 0..len * 2 {
2092 tester.push_front(i);
2095 assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
2098 for i in 0..len * 2 {
2099 tester.push_back(i);
2102 let idx = tester.len() - 1 - i;
2103 assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
2106 assert!(tester.tail < tester.cap());
2107 assert!(tester.head < tester.cap());
2108 assert_eq!(tester, expected);
2118 // This test checks that every single combination of tail position, length, and
2119 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2121 let mut tester = VecDeque::with_capacity(15);
2122 // can't guarantee we got 15, so have to get what we got.
2123 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2124 // this test isn't covering what it wants to
2125 let cap = tester.capacity();
2128 // len is the length *after* insertion
2130 // 0, 1, 2, .., len - 1
2131 let expected = (0..).take(len).collect();
2132 for tail_pos in 0..cap {
2133 for to_insert in 0..len {
2134 tester.tail = tail_pos;
2135 tester.head = tail_pos;
2138 tester.push_back(i);
2141 tester.insert(to_insert, to_insert);
2142 assert!(tester.tail < tester.cap());
2143 assert!(tester.head < tester.cap());
2144 assert_eq!(tester, expected);
2152 // This test checks that every single combination of tail position, length, and
2153 // removal position is tested. Capacity 15 should be large enough to cover every case.
2155 let mut tester = VecDeque::with_capacity(15);
2156 // can't guarantee we got 15, so have to get what we got.
2157 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2158 // this test isn't covering what it wants to
2159 let cap = tester.capacity();
2161 // len is the length *after* removal
2162 for len in 0..cap - 1 {
2163 // 0, 1, 2, .., len - 1
2164 let expected = (0..).take(len).collect();
2165 for tail_pos in 0..cap {
2166 for to_remove in 0..len + 1 {
2167 tester.tail = tail_pos;
2168 tester.head = tail_pos;
2171 tester.push_back(1234);
2173 tester.push_back(i);
2175 if to_remove == len {
2176 tester.push_back(1234);
2178 tester.remove(to_remove);
2179 assert!(tester.tail < tester.cap());
2180 assert!(tester.head < tester.cap());
2181 assert_eq!(tester, expected);
2189 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2191 let cap = tester.capacity();
2192 for len in 0..cap + 1 {
2193 for tail in 0..cap + 1 {
2194 for drain_start in 0..len + 1 {
2195 for drain_end in drain_start..len + 1 {
2199 tester.push_back(i);
2202 // Check that we drain the correct values
2203 let drained: VecDeque<_> =
2204 tester.drain(drain_start..drain_end).collect();
2205 let drained_expected: VecDeque<_> =
2206 (drain_start..drain_end).collect();
2207 assert_eq!(drained, drained_expected);
2209 // We shouldn't have changed the capacity or made the
2210 // head or tail out of bounds
2211 assert_eq!(tester.capacity(), cap);
2212 assert!(tester.tail < tester.cap());
2213 assert!(tester.head < tester.cap());
2215 // We should see the correct values in the VecDeque
2216 let expected: VecDeque<_> =
2217 (0..drain_start).chain(drain_end..len).collect();
2218 assert_eq!(expected, tester);
2226 fn test_shrink_to_fit() {
2227 // This test checks that every single combination of head and tail position,
2228 // is tested. Capacity 15 should be large enough to cover every case.
2230 let mut tester = VecDeque::with_capacity(15);
2231 // can't guarantee we got 15, so have to get what we got.
2232 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2233 // this test isn't covering what it wants to
2234 let cap = tester.capacity();
2236 let max_cap = tester.capacity();
2238 for len in 0..cap + 1 {
2239 // 0, 1, 2, .., len - 1
2240 let expected = (0..).take(len).collect();
2241 for tail_pos in 0..max_cap + 1 {
2242 tester.tail = tail_pos;
2243 tester.head = tail_pos;
2246 tester.push_back(i);
2248 tester.shrink_to_fit();
2249 assert!(tester.capacity() <= cap);
2250 assert!(tester.tail < tester.cap());
2251 assert!(tester.head < tester.cap());
2252 assert_eq!(tester, expected);
2258 fn test_split_off() {
2259 // This test checks that every single combination of tail position, length, and
2260 // split position is tested. Capacity 15 should be large enough to cover every case.
2262 let mut tester = VecDeque::with_capacity(15);
2263 // can't guarantee we got 15, so have to get what we got.
2264 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2265 // this test isn't covering what it wants to
2266 let cap = tester.capacity();
2268 // len is the length *before* splitting
2270 // index to split at
2271 for at in 0..len + 1 {
2272 // 0, 1, 2, .., at - 1 (may be empty)
2273 let expected_self = (0..).take(at).collect();
2274 // at, at + 1, .., len - 1 (may be empty)
2275 let expected_other = (at..).take(len - at).collect();
2277 for tail_pos in 0..cap {
2278 tester.tail = tail_pos;
2279 tester.head = tail_pos;
2281 tester.push_back(i);
2283 let result = tester.split_off(at);
2284 assert!(tester.tail < tester.cap());
2285 assert!(tester.head < tester.cap());
2286 assert!(result.tail < result.cap());
2287 assert!(result.head < result.cap());
2288 assert_eq!(tester, expected_self);
2289 assert_eq!(result, expected_other);
2296 fn test_zst_push() {
2302 // Test that for all possible sequences of push_front / push_back,
2303 // we end up with a deque of the correct size
2306 let mut tester = VecDeque::with_capacity(len);
2307 assert_eq!(tester.len(), 0);
2308 assert!(tester.capacity() >= len);
2309 for case in 0..(1 << len) {
2310 assert_eq!(tester.len(), 0);
2312 if case & (1 << bit) != 0 {
2313 tester.push_front(Zst);
2315 tester.push_back(Zst);
2318 assert_eq!(tester.len(), len);
2319 assert_eq!(tester.iter().count(), len);