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 double-ended
42 /// queue efficiently.
44 /// The "default" usage of this type as a queue is to use `push_back` to add to
45 /// the queue, and `pop_front` to remove from the queue. `extend` and `append`
46 /// push onto the back in this manner, and iterating over `VecDeque` goes front
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub struct VecDeque<T> {
50 // tail and head are pointers into the buffer. Tail always points
51 // to the first element that could be read, Head always points
52 // to where data should be written.
53 // If tail == head the buffer is empty. The length of the ringbuffer
54 // 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> {
85 /// Marginally more convenient
87 fn ptr(&self) -> *mut T {
91 /// Marginally more convenient
93 fn cap(&self) -> usize {
94 if mem::size_of::<T>() == 0 {
95 // For zero sized types, we are always at maximum capacity
102 /// Turn ptr into a slice
104 unsafe fn buffer_as_slice(&self) -> &[T] {
105 slice::from_raw_parts(self.ptr(), self.cap())
108 /// Turn ptr into a mut slice
110 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
111 slice::from_raw_parts_mut(self.ptr(), self.cap())
114 /// Moves an element out of the buffer
116 unsafe fn buffer_read(&mut self, off: usize) -> T {
117 ptr::read(self.ptr().offset(off as isize))
120 /// Writes an element into the buffer, moving it.
122 unsafe fn buffer_write(&mut self, off: usize, value: T) {
123 ptr::write(self.ptr().offset(off as isize), value);
126 /// Returns true if and only if the buffer is at capacity
128 fn is_full(&self) -> bool {
129 self.cap() - self.len() == 1
132 /// Returns the index in the underlying buffer for a given logical element
135 fn wrap_index(&self, idx: usize) -> usize {
136 wrap_index(idx, self.cap())
139 /// Returns the index in the underlying buffer for a given logical element
142 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
143 wrap_index(idx.wrapping_add(addend), self.cap())
146 /// Returns the index in the underlying buffer for a given logical element
147 /// index - subtrahend.
149 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
150 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
153 /// Copies a contiguous block of memory len long from src to dst
155 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
156 debug_assert!(dst + len <= self.cap(),
157 "cpy dst={} src={} len={} cap={}",
162 debug_assert!(src + len <= self.cap(),
163 "cpy dst={} src={} len={} cap={}",
168 ptr::copy(self.ptr().offset(src as isize),
169 self.ptr().offset(dst as isize),
173 /// Copies a contiguous block of memory len long from src to dst
175 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
176 debug_assert!(dst + len <= self.cap(),
177 "cno dst={} src={} len={} cap={}",
182 debug_assert!(src + len <= self.cap(),
183 "cno dst={} src={} len={} cap={}",
188 ptr::copy_nonoverlapping(self.ptr().offset(src as isize),
189 self.ptr().offset(dst as isize),
193 /// Copies a potentially wrapping block of memory len long from src to dest.
194 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
195 /// most one continuous overlapping region between src and dest).
196 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
198 fn diff(a: usize, b: usize) -> usize {
205 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
206 "wrc dst={} src={} len={} cap={}",
212 if src == dst || len == 0 {
216 let dst_after_src = self.wrap_sub(dst, src) < len;
218 let src_pre_wrap_len = self.cap() - src;
219 let dst_pre_wrap_len = self.cap() - dst;
220 let src_wraps = src_pre_wrap_len < len;
221 let dst_wraps = dst_pre_wrap_len < len;
223 match (dst_after_src, src_wraps, dst_wraps) {
224 (_, false, false) => {
225 // src doesn't wrap, dst doesn't wrap
228 // 1 [_ _ A A B B C C _]
229 // 2 [_ _ A A A A B B _]
232 self.copy(dst, src, len);
234 (false, false, true) => {
235 // dst before src, src doesn't wrap, dst wraps
238 // 1 [A A B B _ _ _ C C]
239 // 2 [A A B B _ _ _ A A]
240 // 3 [B B B B _ _ _ A A]
243 self.copy(dst, src, dst_pre_wrap_len);
244 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
246 (true, false, true) => {
247 // src before dst, src doesn't wrap, dst wraps
250 // 1 [C C _ _ _ A A B B]
251 // 2 [B B _ _ _ A A B B]
252 // 3 [B B _ _ _ A A A A]
255 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
256 self.copy(dst, src, dst_pre_wrap_len);
258 (false, true, false) => {
259 // dst before src, src wraps, dst doesn't wrap
262 // 1 [C C _ _ _ A A B B]
263 // 2 [C C _ _ _ B B B B]
264 // 3 [C C _ _ _ B B C C]
267 self.copy(dst, src, src_pre_wrap_len);
268 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
270 (true, true, false) => {
271 // src before dst, src wraps, dst doesn't wrap
274 // 1 [A A B B _ _ _ C C]
275 // 2 [A A A A _ _ _ C C]
276 // 3 [C C A A _ _ _ C C]
279 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
280 self.copy(dst, src, src_pre_wrap_len);
282 (false, true, true) => {
283 // dst before src, src wraps, dst wraps
286 // 1 [A B C D _ E F G H]
287 // 2 [A B C D _ E G H H]
288 // 3 [A B C D _ E G H A]
289 // 4 [B C C D _ E G H A]
292 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
293 let delta = dst_pre_wrap_len - src_pre_wrap_len;
294 self.copy(dst, src, src_pre_wrap_len);
295 self.copy(dst + src_pre_wrap_len, 0, delta);
296 self.copy(0, delta, len - dst_pre_wrap_len);
298 (true, true, true) => {
299 // src before dst, src wraps, dst wraps
302 // 1 [A B C D _ E F G H]
303 // 2 [A A B D _ E F G H]
304 // 3 [H A B D _ E F G H]
305 // 4 [H A B D _ E F F G]
308 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
309 let delta = src_pre_wrap_len - dst_pre_wrap_len;
310 self.copy(delta, 0, len - src_pre_wrap_len);
311 self.copy(0, self.cap() - delta, delta);
312 self.copy(dst, src, dst_pre_wrap_len);
317 /// Frobs the head and tail sections around to handle the fact that we
318 /// just reallocated. Unsafe because it trusts old_cap.
320 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
321 let new_cap = self.cap();
323 // Move the shortest contiguous section of the ring buffer
325 // [o o o o o o o . ]
327 // A [o o o o o o o . . . . . . . . . ]
329 // [o o . o o o o o ]
331 // B [. . . o o o o o o o . . . . . . ]
333 // [o o o o o . o o ]
335 // C [o o o o o . . . . . . . . . o o ]
337 if self.tail <= self.head {
340 } else if self.head < old_cap - self.tail {
342 self.copy_nonoverlapping(old_cap, 0, self.head);
343 self.head += old_cap;
344 debug_assert!(self.head > self.tail);
347 let new_tail = new_cap - (old_cap - self.tail);
348 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
349 self.tail = new_tail;
350 debug_assert!(self.head < self.tail);
352 debug_assert!(self.head < self.cap());
353 debug_assert!(self.tail < self.cap());
354 debug_assert!(self.cap().count_ones() == 1);
358 impl<T> VecDeque<T> {
359 /// Creates an empty `VecDeque`.
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub fn new() -> VecDeque<T> {
362 VecDeque::with_capacity(INITIAL_CAPACITY)
365 /// Creates an empty `VecDeque` with space for at least `n` elements.
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn with_capacity(n: usize) -> VecDeque<T> {
368 // +1 since the ringbuffer always leaves one space empty
369 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
370 assert!(cap > n, "capacity overflow");
375 buf: RawVec::with_capacity(cap),
379 /// Retrieves an element in the `VecDeque` by index.
384 /// use std::collections::VecDeque;
386 /// let mut buf = VecDeque::new();
387 /// buf.push_back(3);
388 /// buf.push_back(4);
389 /// buf.push_back(5);
390 /// assert_eq!(buf.get(1), Some(&4));
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub fn get(&self, index: usize) -> Option<&T> {
394 if index < self.len() {
395 let idx = self.wrap_add(self.tail, index);
396 unsafe { Some(&*self.ptr().offset(idx as isize)) }
402 /// Retrieves an element in the `VecDeque` mutably by index.
407 /// use std::collections::VecDeque;
409 /// let mut buf = VecDeque::new();
410 /// buf.push_back(3);
411 /// buf.push_back(4);
412 /// buf.push_back(5);
413 /// if let Some(elem) = buf.get_mut(1) {
417 /// assert_eq!(buf[1], 7);
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
421 if index < self.len() {
422 let idx = self.wrap_add(self.tail, index);
423 unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
429 /// Swaps elements at indices `i` and `j`.
431 /// `i` and `j` may be equal.
433 /// Fails if there is no element with either index.
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);
445 /// assert_eq!(buf[0], 5);
446 /// assert_eq!(buf[2], 3);
448 #[stable(feature = "rust1", since = "1.0.0")]
449 pub fn swap(&mut self, i: usize, j: usize) {
450 assert!(i < self.len());
451 assert!(j < self.len());
452 let ri = self.wrap_add(self.tail, i);
453 let rj = self.wrap_add(self.tail, j);
455 ptr::swap(self.ptr().offset(ri as isize),
456 self.ptr().offset(rj as isize))
460 /// Returns the number of elements the `VecDeque` can hold without
466 /// use std::collections::VecDeque;
468 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
469 /// assert!(buf.capacity() >= 10);
472 #[stable(feature = "rust1", since = "1.0.0")]
473 pub fn capacity(&self) -> usize {
477 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
478 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
480 /// Note that the allocator may give the collection more space than it requests. Therefore
481 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
482 /// insertions are expected.
486 /// Panics if the new capacity overflows `usize`.
491 /// use std::collections::VecDeque;
493 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
494 /// buf.reserve_exact(10);
495 /// assert!(buf.capacity() >= 11);
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn reserve_exact(&mut self, additional: usize) {
499 self.reserve(additional);
502 /// Reserves capacity for at least `additional` more elements to be inserted in the given
503 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
507 /// Panics if the new capacity overflows `usize`.
512 /// use std::collections::VecDeque;
514 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
516 /// assert!(buf.capacity() >= 11);
518 #[stable(feature = "rust1", since = "1.0.0")]
519 pub fn reserve(&mut self, additional: usize) {
520 let old_cap = self.cap();
521 let used_cap = self.len() + 1;
522 let new_cap = used_cap.checked_add(additional)
523 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
524 .expect("capacity overflow");
526 if new_cap > self.capacity() {
527 self.buf.reserve_exact(used_cap, new_cap - used_cap);
529 self.handle_cap_increase(old_cap);
534 /// Shrinks the capacity of the `VecDeque` as much as possible.
536 /// It will drop down as close as possible to the length but the allocator may still inform the
537 /// `VecDeque` that there is space for a few more elements.
542 /// use std::collections::VecDeque;
544 /// let mut buf = VecDeque::with_capacity(15);
545 /// buf.extend(0..4);
546 /// assert_eq!(buf.capacity(), 15);
547 /// buf.shrink_to_fit();
548 /// assert!(buf.capacity() >= 4);
550 #[stable(feature = "deque_extras_15", since = "1.5.0")]
551 pub fn shrink_to_fit(&mut self) {
552 // +1 since the ringbuffer always leaves one space empty
553 // len + 1 can't overflow for an existing, well-formed ringbuffer.
554 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
555 if target_cap < self.cap() {
556 // There are three cases of interest:
557 // All elements are out of desired bounds
558 // Elements are contiguous, and head is out of desired bounds
559 // Elements are discontiguous, and tail is out of desired bounds
561 // At all other times, element positions are unaffected.
563 // Indicates that elements at the head should be moved.
564 let head_outside = self.head == 0 || self.head >= target_cap;
565 // Move elements from out of desired bounds (positions after target_cap)
566 if self.tail >= target_cap && head_outside {
568 // [. . . . . . . . o o o o o o o . ]
570 // [o o o o o o o . ]
572 self.copy_nonoverlapping(0, self.tail, self.len());
574 self.head = self.len();
576 } else if self.tail != 0 && self.tail < target_cap && head_outside {
578 // [. . . o o o o o o o . . . . . . ]
580 // [o o . o o o o o ]
581 let len = self.wrap_sub(self.head, target_cap);
583 self.copy_nonoverlapping(0, target_cap, len);
586 debug_assert!(self.head < self.tail);
587 } else if self.tail >= target_cap {
589 // [o o o o o . . . . . . . . . o o ]
591 // [o o o o o . o o ]
592 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
593 let len = self.cap() - self.tail;
594 let new_tail = target_cap - len;
596 self.copy_nonoverlapping(new_tail, self.tail, len);
598 self.tail = new_tail;
599 debug_assert!(self.head < self.tail);
602 self.buf.shrink_to_fit(target_cap);
604 debug_assert!(self.head < self.cap());
605 debug_assert!(self.tail < self.cap());
606 debug_assert!(self.cap().count_ones() == 1);
610 /// Shortens a `VecDeque`, dropping excess elements from the back.
612 /// If `len` is greater than the `VecDeque`'s current length, this has no
618 /// #![feature(deque_extras)]
620 /// use std::collections::VecDeque;
622 /// let mut buf = VecDeque::new();
623 /// buf.push_back(5);
624 /// buf.push_back(10);
625 /// buf.push_back(15);
627 /// assert_eq!(buf.len(), 1);
628 /// assert_eq!(Some(&5), buf.get(0));
630 #[unstable(feature = "deque_extras",
631 reason = "matches collection reform specification; waiting on panic semantics",
633 pub fn truncate(&mut self, len: usize) {
634 for _ in len..self.len() {
639 /// Returns a front-to-back iterator.
644 /// use std::collections::VecDeque;
646 /// let mut buf = VecDeque::new();
647 /// buf.push_back(5);
648 /// buf.push_back(3);
649 /// buf.push_back(4);
650 /// let b: &[_] = &[&5, &3, &4];
651 /// let c: Vec<&i32> = buf.iter().collect();
652 /// assert_eq!(&c[..], b);
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub fn iter(&self) -> Iter<T> {
659 ring: unsafe { self.buffer_as_slice() },
663 /// Returns a front-to-back iterator that returns mutable references.
668 /// use std::collections::VecDeque;
670 /// let mut buf = VecDeque::new();
671 /// buf.push_back(5);
672 /// buf.push_back(3);
673 /// buf.push_back(4);
674 /// for num in buf.iter_mut() {
677 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
678 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub fn iter_mut(&mut self) -> IterMut<T> {
685 ring: unsafe { self.buffer_as_mut_slice() },
689 /// Returns a pair of slices which contain, in order, the contents of the
692 #[stable(feature = "deque_extras_15", since = "1.5.0")]
693 pub fn as_slices(&self) -> (&[T], &[T]) {
695 let contiguous = self.is_contiguous();
696 let buf = self.buffer_as_slice();
698 let (empty, buf) = buf.split_at(0);
699 (&buf[self.tail..self.head], empty)
701 let (mid, right) = buf.split_at(self.tail);
702 let (left, _) = mid.split_at(self.head);
708 /// Returns a pair of slices which contain, in order, the contents of the
711 #[stable(feature = "deque_extras_15", since = "1.5.0")]
712 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
714 let contiguous = self.is_contiguous();
715 let head = self.head;
716 let tail = self.tail;
717 let buf = self.buffer_as_mut_slice();
720 let (empty, buf) = buf.split_at_mut(0);
721 (&mut buf[tail..head], empty)
723 let (mid, right) = buf.split_at_mut(tail);
724 let (left, _) = mid.split_at_mut(head);
731 /// Returns the number of elements in the `VecDeque`.
736 /// use std::collections::VecDeque;
738 /// let mut v = VecDeque::new();
739 /// assert_eq!(v.len(), 0);
741 /// assert_eq!(v.len(), 1);
743 #[stable(feature = "rust1", since = "1.0.0")]
744 pub fn len(&self) -> usize {
745 count(self.tail, self.head, self.cap())
748 /// Returns true if the buffer contains no elements
753 /// use std::collections::VecDeque;
755 /// let mut v = VecDeque::new();
756 /// assert!(v.is_empty());
758 /// assert!(!v.is_empty());
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn is_empty(&self) -> bool {
765 /// Create a draining iterator that removes the specified range in the
766 /// `VecDeque` and yields the removed items from start to end. The element
767 /// range is removed even if the iterator is not consumed until the end.
769 /// Note: It is unspecified how many elements are removed from the deque,
770 /// if the `Drain` value is not dropped, but the borrow it holds expires
771 /// (eg. due to mem::forget).
775 /// Panics if the starting point is greater than the end point or if
776 /// the end point is greater than the length of the vector.
781 /// #![feature(drain)]
783 /// use std::collections::VecDeque;
785 /// // draining using `..` clears the whole deque.
786 /// let mut v = VecDeque::new();
788 /// assert_eq!(v.drain(..).next(), Some(1));
789 /// assert!(v.is_empty());
792 #[unstable(feature = "drain",
793 reason = "matches collection reform specification, waiting for dust to settle",
795 pub fn drain<R>(&mut self, range: R) -> Drain<T>
796 where R: RangeArgument<usize>
800 // When the Drain is first created, the source deque is shortened to
801 // make sure no uninitialized or moved-from elements are accessible at
802 // all if the Drain's destructor never gets to run.
804 // Drain will ptr::read out the values to remove.
805 // When finished, the remaining data will be copied back to cover the hole,
806 // and the head/tail values will be restored correctly.
808 let len = self.len();
809 let start = *range.start().unwrap_or(&0);
810 let end = *range.end().unwrap_or(&len);
811 assert!(start <= end, "drain lower bound was too large");
812 assert!(end <= len, "drain upper bound was too large");
814 // The deque's elements are parted into three segments:
815 // * self.tail -> drain_tail
816 // * drain_tail -> drain_head
817 // * drain_head -> self.head
819 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
821 // We store drain_tail as self.head, and drain_head and self.head as
822 // after_tail and after_head respectively on the Drain. This also
823 // truncates the effective array such that if the Drain is leaked, we
824 // have forgotten about the potentially moved values after the start of
828 // [. . . o o x x o o . . .]
830 let drain_tail = self.wrap_add(self.tail, start);
831 let drain_head = self.wrap_add(self.tail, end);
832 let head = self.head;
834 // "forget" about the values after the start of the drain until after
835 // the drain is complete and the Drain destructor is run.
836 self.head = drain_tail;
839 deque: self as *mut _,
840 after_tail: drain_head,
845 ring: unsafe { self.buffer_as_mut_slice() },
850 /// Clears the buffer, removing all values.
855 /// use std::collections::VecDeque;
857 /// let mut v = VecDeque::new();
860 /// assert!(v.is_empty());
862 #[stable(feature = "rust1", since = "1.0.0")]
864 pub fn clear(&mut self) {
868 /// Provides a reference to the front element, or `None` if the sequence is
874 /// use std::collections::VecDeque;
876 /// let mut d = VecDeque::new();
877 /// assert_eq!(d.front(), None);
881 /// assert_eq!(d.front(), Some(&1));
883 #[stable(feature = "rust1", since = "1.0.0")]
884 pub fn front(&self) -> Option<&T> {
885 if !self.is_empty() {
892 /// Provides a mutable reference to the front element, or `None` if the
893 /// sequence is empty.
898 /// use std::collections::VecDeque;
900 /// let mut d = VecDeque::new();
901 /// assert_eq!(d.front_mut(), None);
905 /// match d.front_mut() {
906 /// Some(x) => *x = 9,
909 /// assert_eq!(d.front(), Some(&9));
911 #[stable(feature = "rust1", since = "1.0.0")]
912 pub fn front_mut(&mut self) -> Option<&mut T> {
913 if !self.is_empty() {
920 /// Provides a reference to the back element, or `None` if the sequence is
926 /// use std::collections::VecDeque;
928 /// let mut d = VecDeque::new();
929 /// assert_eq!(d.back(), None);
933 /// assert_eq!(d.back(), Some(&2));
935 #[stable(feature = "rust1", since = "1.0.0")]
936 pub fn back(&self) -> Option<&T> {
937 if !self.is_empty() {
938 Some(&self[self.len() - 1])
944 /// Provides a mutable reference to the back element, or `None` if the
945 /// sequence is empty.
950 /// use std::collections::VecDeque;
952 /// let mut d = VecDeque::new();
953 /// assert_eq!(d.back(), None);
957 /// match d.back_mut() {
958 /// Some(x) => *x = 9,
961 /// assert_eq!(d.back(), Some(&9));
963 #[stable(feature = "rust1", since = "1.0.0")]
964 pub fn back_mut(&mut self) -> Option<&mut T> {
965 let len = self.len();
966 if !self.is_empty() {
967 Some(&mut self[len - 1])
973 /// Removes the first element and returns it, or `None` if the sequence is
979 /// use std::collections::VecDeque;
981 /// let mut d = VecDeque::new();
985 /// assert_eq!(d.pop_front(), Some(1));
986 /// assert_eq!(d.pop_front(), Some(2));
987 /// assert_eq!(d.pop_front(), None);
989 #[stable(feature = "rust1", since = "1.0.0")]
990 pub fn pop_front(&mut self) -> Option<T> {
994 let tail = self.tail;
995 self.tail = self.wrap_add(self.tail, 1);
996 unsafe { Some(self.buffer_read(tail)) }
1000 /// Inserts an element first in the sequence.
1005 /// use std::collections::VecDeque;
1007 /// let mut d = VecDeque::new();
1008 /// d.push_front(1);
1009 /// d.push_front(2);
1010 /// assert_eq!(d.front(), Some(&2));
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub fn push_front(&mut self, value: T) {
1015 let old_cap = self.cap();
1018 self.handle_cap_increase(old_cap);
1020 debug_assert!(!self.is_full());
1023 self.tail = self.wrap_sub(self.tail, 1);
1024 let tail = self.tail;
1026 self.buffer_write(tail, value);
1030 /// Appends an element to the back of a buffer
1035 /// use std::collections::VecDeque;
1037 /// let mut buf = VecDeque::new();
1038 /// buf.push_back(1);
1039 /// buf.push_back(3);
1040 /// assert_eq!(3, *buf.back().unwrap());
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn push_back(&mut self, value: T) {
1045 let old_cap = self.cap();
1048 self.handle_cap_increase(old_cap);
1050 debug_assert!(!self.is_full());
1053 let head = self.head;
1054 self.head = self.wrap_add(self.head, 1);
1055 unsafe { self.buffer_write(head, value) }
1058 /// Removes the last element from a buffer and returns it, or `None` if
1064 /// use std::collections::VecDeque;
1066 /// let mut buf = VecDeque::new();
1067 /// assert_eq!(buf.pop_back(), None);
1068 /// buf.push_back(1);
1069 /// buf.push_back(3);
1070 /// assert_eq!(buf.pop_back(), Some(3));
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 pub fn pop_back(&mut self) -> Option<T> {
1074 if self.is_empty() {
1077 self.head = self.wrap_sub(self.head, 1);
1078 let head = self.head;
1079 unsafe { Some(self.buffer_read(head)) }
1084 fn is_contiguous(&self) -> bool {
1085 self.tail <= self.head
1088 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1091 /// This does not preserve ordering, but is O(1).
1093 /// Returns `None` if `index` is out of bounds.
1098 /// use std::collections::VecDeque;
1100 /// let mut buf = VecDeque::new();
1101 /// assert_eq!(buf.swap_remove_back(0), None);
1102 /// buf.push_back(1);
1103 /// buf.push_back(2);
1104 /// buf.push_back(3);
1106 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1107 /// assert_eq!(buf.len(), 2);
1108 /// assert_eq!(buf[0], 3);
1109 /// assert_eq!(buf[1], 2);
1111 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1112 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1113 let length = self.len();
1114 if length > 0 && index < length - 1 {
1115 self.swap(index, length - 1);
1116 } else if index >= length {
1123 #[unstable(feature = "deque_extras",
1124 reason = "the naming of this function may be altered",
1126 #[deprecated(since = "1.5.0", reason = "renamed to swap_remove_back")]
1127 pub fn swap_back_remove(&mut self, index: usize) -> Option<T> {
1128 self.swap_remove_back(index)
1131 /// Removes an element from anywhere in the `VecDeque` and returns it,
1132 /// replacing it with the first element.
1134 /// This does not preserve ordering, but is O(1).
1136 /// Returns `None` if `index` is out of bounds.
1141 /// use std::collections::VecDeque;
1143 /// let mut buf = VecDeque::new();
1144 /// assert_eq!(buf.swap_remove_front(0), None);
1145 /// buf.push_back(1);
1146 /// buf.push_back(2);
1147 /// buf.push_back(3);
1149 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1150 /// assert_eq!(buf.len(), 2);
1151 /// assert_eq!(buf[0], 2);
1152 /// assert_eq!(buf[1], 1);
1154 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1155 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1156 let length = self.len();
1157 if length > 0 && index < length && index != 0 {
1158 self.swap(index, 0);
1159 } else if index >= length {
1166 #[unstable(feature = "deque_extras",
1167 reason = "the naming of this function may be altered",
1169 #[deprecated(since = "1.5.0", reason = "renamed to swap_remove_front")]
1170 pub fn swap_front_remove(&mut self, index: usize) -> Option<T> {
1171 self.swap_remove_front(index)
1174 /// Inserts an element at `index` within the `VecDeque`. Whichever
1175 /// end is closer to the insertion point will be moved to make room,
1176 /// and all the affected elements will be moved to new positions.
1180 /// Panics if `index` is greater than `VecDeque`'s length
1184 /// use std::collections::VecDeque;
1186 /// let mut buf = VecDeque::new();
1187 /// buf.push_back(10);
1188 /// buf.push_back(12);
1189 /// buf.insert(1, 11);
1190 /// assert_eq!(Some(&11), buf.get(1));
1192 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1193 pub fn insert(&mut self, index: usize, value: T) {
1194 assert!(index <= self.len(), "index out of bounds");
1196 let old_cap = self.cap();
1199 self.handle_cap_increase(old_cap);
1201 debug_assert!(!self.is_full());
1204 // Move the least number of elements in the ring buffer and insert
1207 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1209 // There are three main cases:
1210 // Elements are contiguous
1211 // - special case when tail is 0
1212 // Elements are discontiguous and the insert is in the tail section
1213 // Elements are discontiguous and the insert is in the head section
1215 // For each of those there are two more cases:
1216 // Insert is closer to tail
1217 // Insert is closer to head
1219 // Key: H - self.head
1221 // o - Valid element
1222 // I - Insertion element
1223 // A - The element that should be after the insertion point
1224 // M - Indicates element was moved
1226 let idx = self.wrap_add(self.tail, index);
1228 let distance_to_tail = index;
1229 let distance_to_head = self.len() - index;
1231 let contiguous = self.is_contiguous();
1234 distance_to_tail <= distance_to_head,
1236 (true, true, _) if index == 0 => {
1241 // [A o o o o o o . . . . . . . . .]
1244 // [A o o o o o o o . . . . . I]
1247 self.tail = self.wrap_sub(self.tail, 1);
1249 (true, true, _) => {
1251 // contiguous, insert closer to tail:
1254 // [. . . o o A o o o o . . . . . .]
1257 // [. . o o I A o o o o . . . . . .]
1260 // contiguous, insert closer to tail and tail is 0:
1264 // [o o A o o o o . . . . . . . . .]
1267 // [o I A o o o o o . . . . . . . o]
1270 let new_tail = self.wrap_sub(self.tail, 1);
1272 self.copy(new_tail, self.tail, 1);
1273 // Already moved the tail, so we only copy `index - 1` elements.
1274 self.copy(self.tail, self.tail + 1, index - 1);
1276 self.tail = new_tail;
1279 (true, false, _) => {
1281 // contiguous, insert closer to head:
1284 // [. . . o o o o A o o . . . . . .]
1287 // [. . . o o o o I A o o . . . . .]
1290 self.copy(idx + 1, idx, self.head - idx);
1291 self.head = self.wrap_add(self.head, 1);
1294 (false, true, true) => {
1296 // discontiguous, insert closer to tail, tail section:
1299 // [o o o o o o . . . . . o o A o o]
1302 // [o o o o o o . . . . o o I A o o]
1305 self.copy(self.tail - 1, self.tail, index);
1309 (false, false, true) => {
1311 // discontiguous, insert closer to head, tail section:
1314 // [o o . . . . . . . o o o o o A o]
1317 // [o o o . . . . . . o o o o o I A]
1320 // copy elements up to new head
1321 self.copy(1, 0, self.head);
1323 // copy last element into empty spot at bottom of buffer
1324 self.copy(0, self.cap() - 1, 1);
1326 // move elements from idx to end forward not including ^ element
1327 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1332 (false, true, false) if idx == 0 => {
1334 // discontiguous, insert is closer to tail, head section,
1335 // and is at index zero in the internal buffer:
1338 // [A o o o o o o o o o . . . o o o]
1341 // [A o o o o o o o o o . . o o o I]
1344 // copy elements up to new tail
1345 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1347 // copy last element into empty spot at bottom of buffer
1348 self.copy(self.cap() - 1, 0, 1);
1353 (false, true, false) => {
1355 // discontiguous, insert closer to tail, head section:
1358 // [o o o A o o o o o o . . . o o o]
1361 // [o o I A o o o o o o . . o o o o]
1364 // copy elements up to new tail
1365 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1367 // copy last element into empty spot at bottom of buffer
1368 self.copy(self.cap() - 1, 0, 1);
1370 // move elements from idx-1 to end forward not including ^ element
1371 self.copy(0, 1, idx - 1);
1376 (false, false, false) => {
1378 // discontiguous, insert closer to head, head section:
1381 // [o o o o A o o . . . . . . o o o]
1384 // [o o o o I A o o . . . . . o o o]
1387 self.copy(idx + 1, idx, self.head - idx);
1393 // tail might've been changed so we need to recalculate
1394 let new_idx = self.wrap_add(self.tail, index);
1396 self.buffer_write(new_idx, value);
1400 /// Removes and returns the element at `index` from the `VecDeque`.
1401 /// Whichever end is closer to the removal point will be moved to make
1402 /// room, and all the affected elements will be moved to new positions.
1403 /// Returns `None` if `index` is out of bounds.
1407 /// use std::collections::VecDeque;
1409 /// let mut buf = VecDeque::new();
1410 /// buf.push_back(1);
1411 /// buf.push_back(2);
1412 /// buf.push_back(3);
1414 /// assert_eq!(buf.remove(1), Some(2));
1415 /// assert_eq!(buf.get(1), Some(&3));
1417 #[stable(feature = "rust1", since = "1.0.0")]
1418 pub fn remove(&mut self, index: usize) -> Option<T> {
1419 if self.is_empty() || self.len() <= index {
1423 // There are three main cases:
1424 // Elements are contiguous
1425 // Elements are discontiguous and the removal is in the tail section
1426 // Elements are discontiguous and the removal is in the head section
1427 // - special case when elements are technically contiguous,
1428 // but self.head = 0
1430 // For each of those there are two more cases:
1431 // Insert is closer to tail
1432 // Insert is closer to head
1434 // Key: H - self.head
1436 // o - Valid element
1437 // x - Element marked for removal
1438 // R - Indicates element that is being removed
1439 // M - Indicates element was moved
1441 let idx = self.wrap_add(self.tail, index);
1443 let elem = unsafe { Some(self.buffer_read(idx)) };
1445 let distance_to_tail = index;
1446 let distance_to_head = self.len() - index;
1448 let contiguous = self.is_contiguous();
1451 distance_to_tail <= distance_to_head,
1453 (true, true, _) => {
1455 // contiguous, remove closer to tail:
1458 // [. . . o o x o o o o . . . . . .]
1461 // [. . . . o o o o o o . . . . . .]
1464 self.copy(self.tail + 1, self.tail, index);
1468 (true, false, _) => {
1470 // contiguous, remove closer to head:
1473 // [. . . o o o o x o o . . . . . .]
1476 // [. . . o o o o o o . . . . . . .]
1479 self.copy(idx, idx + 1, self.head - idx - 1);
1483 (false, true, true) => {
1485 // discontiguous, remove closer to tail, tail section:
1488 // [o o o o o o . . . . . o o x o o]
1491 // [o o o o o o . . . . . . o o o o]
1494 self.copy(self.tail + 1, self.tail, index);
1495 self.tail = self.wrap_add(self.tail, 1);
1498 (false, false, false) => {
1500 // discontiguous, remove closer to head, head section:
1503 // [o o o o x o o . . . . . . o o o]
1506 // [o o o o o o . . . . . . . o o o]
1509 self.copy(idx, idx + 1, self.head - idx - 1);
1513 (false, false, true) => {
1515 // discontiguous, remove closer to head, tail section:
1518 // [o o o . . . . . . o o o o o x o]
1521 // [o o . . . . . . . o o o o o o o]
1524 // or quasi-discontiguous, remove next to head, tail section:
1527 // [. . . . . . . . . o o o o o x o]
1530 // [. . . . . . . . . o o o o o o .]
1533 // draw in elements in the tail section
1534 self.copy(idx, idx + 1, self.cap() - idx - 1);
1536 // Prevents underflow.
1538 // copy first element into empty spot
1539 self.copy(self.cap() - 1, 0, 1);
1541 // move elements in the head section backwards
1542 self.copy(0, 1, self.head - 1);
1545 self.head = self.wrap_sub(self.head, 1);
1548 (false, true, false) => {
1550 // discontiguous, remove closer to tail, head section:
1553 // [o o x o o o o o o o . . . o o o]
1556 // [o o o o o o o o o o . . . . o o]
1559 // draw in elements up to idx
1560 self.copy(1, 0, idx);
1562 // copy last element into empty spot
1563 self.copy(0, self.cap() - 1, 1);
1565 // move elements from tail to end forward, excluding the last one
1566 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1568 self.tail = self.wrap_add(self.tail, 1);
1576 /// Splits the collection into two at the given index.
1578 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1579 /// and the returned `Self` contains elements `[at, len)`.
1581 /// Note that the capacity of `self` does not change.
1585 /// Panics if `at > len`
1590 /// use std::collections::VecDeque;
1592 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1593 /// let buf2 = buf.split_off(1);
1594 /// // buf = [1], buf2 = [2, 3]
1595 /// assert_eq!(buf.len(), 1);
1596 /// assert_eq!(buf2.len(), 2);
1599 #[stable(feature = "split_off", since = "1.4.0")]
1600 pub fn split_off(&mut self, at: usize) -> Self {
1601 let len = self.len();
1602 assert!(at <= len, "`at` out of bounds");
1604 let other_len = len - at;
1605 let mut other = VecDeque::with_capacity(other_len);
1608 let (first_half, second_half) = self.as_slices();
1610 let first_len = first_half.len();
1611 let second_len = second_half.len();
1613 // `at` lies in the first half.
1614 let amount_in_first = first_len - at;
1616 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1620 // just take all of the second half.
1621 ptr::copy_nonoverlapping(second_half.as_ptr(),
1622 other.ptr().offset(amount_in_first as isize),
1625 // `at` lies in the second half, need to factor in the elements we skipped
1626 // in the first half.
1627 let offset = at - first_len;
1628 let amount_in_second = second_len - offset;
1629 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1635 // Cleanup where the ends of the buffers are
1636 self.head = self.wrap_sub(self.head, other_len);
1637 other.head = other.wrap_index(other_len);
1642 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1646 /// Panics if the new number of elements in self overflows a `usize`.
1651 /// use std::collections::VecDeque;
1653 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1654 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
1655 /// buf.append(&mut buf2);
1656 /// assert_eq!(buf.len(), 6);
1657 /// assert_eq!(buf2.len(), 0);
1660 #[stable(feature = "append", since = "1.4.0")]
1661 pub fn append(&mut self, other: &mut Self) {
1663 self.extend(other.drain(..));
1666 /// Retains only the elements specified by the predicate.
1668 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1669 /// This method operates in place and preserves the order of the retained
1675 /// use std::collections::VecDeque;
1677 /// let mut buf = VecDeque::new();
1678 /// buf.extend(1..5);
1679 /// buf.retain(|&x| x%2 == 0);
1681 /// let v: Vec<_> = buf.into_iter().collect();
1682 /// assert_eq!(&v[..], &[2, 4]);
1684 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1685 pub fn retain<F>(&mut self, mut f: F)
1686 where F: FnMut(&T) -> bool
1688 let len = self.len();
1694 self.swap(i - del, i);
1698 self.truncate(len - del);
1703 impl<T: Clone> VecDeque<T> {
1704 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1705 /// either by removing excess elements or by appending copies of a value to the back.
1710 /// #![feature(deque_extras)]
1712 /// use std::collections::VecDeque;
1714 /// let mut buf = VecDeque::new();
1715 /// buf.push_back(5);
1716 /// buf.push_back(10);
1717 /// buf.push_back(15);
1718 /// buf.resize(2, 0);
1719 /// buf.resize(6, 20);
1720 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
1721 /// assert_eq!(a, b);
1724 #[unstable(feature = "deque_extras",
1725 reason = "matches collection reform specification; waiting on panic semantics",
1727 pub fn resize(&mut self, new_len: usize, value: T) {
1728 let len = self.len();
1731 self.extend(repeat(value).take(new_len - len))
1733 self.truncate(new_len);
1738 /// Returns the index in the underlying buffer for a given logical element index.
1740 fn wrap_index(index: usize, size: usize) -> usize {
1741 // size is always a power of 2
1742 debug_assert!(size.is_power_of_two());
1746 /// Calculate the number of elements left to be read in the buffer
1748 fn count(tail: usize, head: usize, size: usize) -> usize {
1749 // size is always a power of 2
1750 (head.wrapping_sub(tail)) & (size - 1)
1753 /// `VecDeque` iterator.
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 pub struct Iter<'a, T: 'a> {
1761 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl<'a, T> Clone for Iter<'a, T> {
1764 fn clone(&self) -> Iter<'a, T> {
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 impl<'a, T> Iterator for Iter<'a, T> {
1778 fn next(&mut self) -> Option<&'a T> {
1779 if self.tail == self.head {
1782 let tail = self.tail;
1783 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1784 unsafe { Some(self.ring.get_unchecked(tail)) }
1788 fn size_hint(&self) -> (usize, Option<usize>) {
1789 let len = count(self.tail, self.head, self.ring.len());
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1797 fn next_back(&mut self) -> Option<&'a T> {
1798 if self.tail == self.head {
1801 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1802 unsafe { Some(self.ring.get_unchecked(self.head)) }
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1809 /// `VecDeque` mutable iterator.
1810 #[stable(feature = "rust1", since = "1.0.0")]
1811 pub struct IterMut<'a, T: 'a> {
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 impl<'a, T> Iterator for IterMut<'a, T> {
1819 type Item = &'a mut T;
1822 fn next(&mut self) -> Option<&'a mut T> {
1823 if self.tail == self.head {
1826 let tail = self.tail;
1827 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1830 let elem = self.ring.get_unchecked_mut(tail);
1831 Some(&mut *(elem as *mut _))
1836 fn size_hint(&self) -> (usize, Option<usize>) {
1837 let len = count(self.tail, self.head, self.ring.len());
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1845 fn next_back(&mut self) -> Option<&'a mut T> {
1846 if self.tail == self.head {
1849 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1852 let elem = self.ring.get_unchecked_mut(self.head);
1853 Some(&mut *(elem as *mut _))
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1861 /// A by-value VecDeque iterator
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 pub struct IntoIter<T> {
1868 #[stable(feature = "rust1", since = "1.0.0")]
1869 impl<T> Iterator for IntoIter<T> {
1873 fn next(&mut self) -> Option<T> {
1874 self.inner.pop_front()
1878 fn size_hint(&self) -> (usize, Option<usize>) {
1879 let len = self.inner.len();
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 impl<T> DoubleEndedIterator for IntoIter<T> {
1887 fn next_back(&mut self) -> Option<T> {
1888 self.inner.pop_back()
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 impl<T> ExactSizeIterator for IntoIter<T> {}
1895 /// A draining VecDeque iterator
1896 #[unstable(feature = "drain",
1897 reason = "matches collection reform specification, waiting for dust to settle",
1899 pub struct Drain<'a, T: 'a> {
1903 deque: *mut VecDeque<T>,
1906 #[unstable(feature = "drain", issue = "27711")]
1907 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1908 #[unstable(feature = "drain", issue = "27711")]
1909 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 impl<'a, T: 'a> Drop for Drain<'a, T> {
1913 fn drop(&mut self) {
1914 for _ in self.by_ref() {}
1916 let source_deque = unsafe { &mut *self.deque };
1918 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
1921 // [. . . o o x x o o . . .]
1923 let orig_tail = source_deque.tail;
1924 let drain_tail = source_deque.head;
1925 let drain_head = self.after_tail;
1926 let orig_head = self.after_head;
1928 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
1929 let head_len = count(drain_head, orig_head, source_deque.cap());
1931 // Restore the original head value
1932 source_deque.head = orig_head;
1934 match (tail_len, head_len) {
1936 source_deque.head = 0;
1937 source_deque.tail = 0;
1940 source_deque.tail = drain_head;
1943 source_deque.head = drain_tail;
1947 if tail_len <= head_len {
1948 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
1949 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
1951 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
1952 source_deque.wrap_copy(drain_tail, drain_head, head_len);
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1965 fn next(&mut self) -> Option<T> {
1966 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
1970 fn size_hint(&self) -> (usize, Option<usize>) {
1971 self.iter.size_hint()
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1978 fn next_back(&mut self) -> Option<T> {
1979 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1986 #[stable(feature = "rust1", since = "1.0.0")]
1987 impl<A: PartialEq> PartialEq for VecDeque<A> {
1988 fn eq(&self, other: &VecDeque<A>) -> bool {
1989 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a.eq(b))
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 impl<A: Eq> Eq for VecDeque<A> {}
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
1998 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
1999 self.iter().partial_cmp(other.iter())
2003 #[stable(feature = "rust1", since = "1.0.0")]
2004 impl<A: Ord> Ord for VecDeque<A> {
2006 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2007 self.iter().cmp(other.iter())
2011 #[stable(feature = "rust1", since = "1.0.0")]
2012 impl<A: Hash> Hash for VecDeque<A> {
2013 fn hash<H: Hasher>(&self, state: &mut H) {
2014 self.len().hash(state);
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 impl<A> Index<usize> for VecDeque<A> {
2026 fn index(&self, index: usize) -> &A {
2027 self.get(index).expect("Out of bounds access")
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 impl<A> IndexMut<usize> for VecDeque<A> {
2034 fn index_mut(&mut self, index: usize) -> &mut A {
2035 self.get_mut(index).expect("Out of bounds access")
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 impl<A> FromIterator<A> for VecDeque<A> {
2041 fn from_iter<T: IntoIterator<Item = A>>(iterable: T) -> VecDeque<A> {
2042 let iterator = iterable.into_iter();
2043 let (lower, _) = iterator.size_hint();
2044 let mut deq = VecDeque::with_capacity(lower);
2045 deq.extend(iterator);
2050 #[stable(feature = "rust1", since = "1.0.0")]
2051 impl<T> IntoIterator for VecDeque<T> {
2053 type IntoIter = IntoIter<T>;
2055 /// Consumes the list into a front-to-back iterator yielding elements by
2057 fn into_iter(self) -> IntoIter<T> {
2058 IntoIter { inner: self }
2062 #[stable(feature = "rust1", since = "1.0.0")]
2063 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2065 type IntoIter = Iter<'a, T>;
2067 fn into_iter(self) -> Iter<'a, T> {
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2074 type Item = &'a mut T;
2075 type IntoIter = IterMut<'a, T>;
2077 fn into_iter(mut self) -> IterMut<'a, T> {
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 impl<A> Extend<A> for VecDeque<A> {
2084 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2086 self.push_back(elt);
2091 #[stable(feature = "extend_ref", since = "1.2.0")]
2092 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2093 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2094 self.extend(iter.into_iter().cloned());
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2100 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2101 f.debug_list().entries(self).finish()
2107 use core::iter::Iterator;
2108 use core::option::Option::Some;
2112 use super::VecDeque;
2115 fn bench_push_back_100(b: &mut test::Bencher) {
2116 let mut deq = VecDeque::with_capacity(101);
2127 fn bench_push_front_100(b: &mut test::Bencher) {
2128 let mut deq = VecDeque::with_capacity(101);
2139 fn bench_pop_back_100(b: &mut test::Bencher) {
2140 let mut deq = VecDeque::<i32>::with_capacity(101);
2145 while !deq.is_empty() {
2146 test::black_box(deq.pop_back());
2152 fn bench_pop_front_100(b: &mut test::Bencher) {
2153 let mut deq = VecDeque::<i32>::with_capacity(101);
2158 while !deq.is_empty() {
2159 test::black_box(deq.pop_front());
2165 fn test_swap_front_back_remove() {
2166 fn test(back: bool) {
2167 // This test checks that every single combination of tail position and length is tested.
2168 // Capacity 15 should be large enough to cover every case.
2169 let mut tester = VecDeque::with_capacity(15);
2170 let usable_cap = tester.capacity();
2171 let final_len = usable_cap / 2;
2173 for len in 0..final_len {
2174 let expected = if back {
2177 (0..len).rev().collect()
2179 for tail_pos in 0..usable_cap {
2180 tester.tail = tail_pos;
2181 tester.head = tail_pos;
2183 for i in 0..len * 2 {
2184 tester.push_front(i);
2187 assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
2190 for i in 0..len * 2 {
2191 tester.push_back(i);
2194 let idx = tester.len() - 1 - i;
2195 assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
2198 assert!(tester.tail < tester.cap());
2199 assert!(tester.head < tester.cap());
2200 assert_eq!(tester, expected);
2210 // This test checks that every single combination of tail position, length, and
2211 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2213 let mut tester = VecDeque::with_capacity(15);
2214 // can't guarantee we got 15, so have to get what we got.
2215 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2216 // this test isn't covering what it wants to
2217 let cap = tester.capacity();
2220 // len is the length *after* insertion
2222 // 0, 1, 2, .., len - 1
2223 let expected = (0..).take(len).collect();
2224 for tail_pos in 0..cap {
2225 for to_insert in 0..len {
2226 tester.tail = tail_pos;
2227 tester.head = tail_pos;
2230 tester.push_back(i);
2233 tester.insert(to_insert, to_insert);
2234 assert!(tester.tail < tester.cap());
2235 assert!(tester.head < tester.cap());
2236 assert_eq!(tester, expected);
2244 // This test checks that every single combination of tail position, length, and
2245 // removal position is tested. Capacity 15 should be large enough to cover every case.
2247 let mut tester = VecDeque::with_capacity(15);
2248 // can't guarantee we got 15, so have to get what we got.
2249 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2250 // this test isn't covering what it wants to
2251 let cap = tester.capacity();
2253 // len is the length *after* removal
2254 for len in 0..cap - 1 {
2255 // 0, 1, 2, .., len - 1
2256 let expected = (0..).take(len).collect();
2257 for tail_pos in 0..cap {
2258 for to_remove in 0..len + 1 {
2259 tester.tail = tail_pos;
2260 tester.head = tail_pos;
2263 tester.push_back(1234);
2265 tester.push_back(i);
2267 if to_remove == len {
2268 tester.push_back(1234);
2270 tester.remove(to_remove);
2271 assert!(tester.tail < tester.cap());
2272 assert!(tester.head < tester.cap());
2273 assert_eq!(tester, expected);
2281 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2283 let cap = tester.capacity();
2284 for len in 0..cap + 1 {
2285 for tail in 0..cap + 1 {
2286 for drain_start in 0..len + 1 {
2287 for drain_end in drain_start..len + 1 {
2291 tester.push_back(i);
2294 // Check that we drain the correct values
2295 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2296 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2297 assert_eq!(drained, drained_expected);
2299 // We shouldn't have changed the capacity or made the
2300 // head or tail out of bounds
2301 assert_eq!(tester.capacity(), cap);
2302 assert!(tester.tail < tester.cap());
2303 assert!(tester.head < tester.cap());
2305 // We should see the correct values in the VecDeque
2306 let expected: VecDeque<_> = (0..drain_start)
2307 .chain(drain_end..len)
2309 assert_eq!(expected, tester);
2317 fn test_shrink_to_fit() {
2318 // This test checks that every single combination of head and tail position,
2319 // is tested. Capacity 15 should be large enough to cover every case.
2321 let mut tester = VecDeque::with_capacity(15);
2322 // can't guarantee we got 15, so have to get what we got.
2323 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2324 // this test isn't covering what it wants to
2325 let cap = tester.capacity();
2327 let max_cap = tester.capacity();
2329 for len in 0..cap + 1 {
2330 // 0, 1, 2, .., len - 1
2331 let expected = (0..).take(len).collect();
2332 for tail_pos in 0..max_cap + 1 {
2333 tester.tail = tail_pos;
2334 tester.head = tail_pos;
2337 tester.push_back(i);
2339 tester.shrink_to_fit();
2340 assert!(tester.capacity() <= cap);
2341 assert!(tester.tail < tester.cap());
2342 assert!(tester.head < tester.cap());
2343 assert_eq!(tester, expected);
2349 fn test_split_off() {
2350 // This test checks that every single combination of tail position, length, and
2351 // split position is tested. Capacity 15 should be large enough to cover every case.
2353 let mut tester = VecDeque::with_capacity(15);
2354 // can't guarantee we got 15, so have to get what we got.
2355 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2356 // this test isn't covering what it wants to
2357 let cap = tester.capacity();
2359 // len is the length *before* splitting
2361 // index to split at
2362 for at in 0..len + 1 {
2363 // 0, 1, 2, .., at - 1 (may be empty)
2364 let expected_self = (0..).take(at).collect();
2365 // at, at + 1, .., len - 1 (may be empty)
2366 let expected_other = (at..).take(len - at).collect();
2368 for tail_pos in 0..cap {
2369 tester.tail = tail_pos;
2370 tester.head = tail_pos;
2372 tester.push_back(i);
2374 let result = tester.split_off(at);
2375 assert!(tester.tail < tester.cap());
2376 assert!(tester.head < tester.cap());
2377 assert!(result.tail < result.cap());
2378 assert!(result.head < result.cap());
2379 assert_eq!(tester, expected_self);
2380 assert_eq!(result, expected_other);
2387 fn test_zst_push() {
2393 // Test that for all possible sequences of push_front / push_back,
2394 // we end up with a deque of the correct size
2397 let mut tester = VecDeque::with_capacity(len);
2398 assert_eq!(tester.len(), 0);
2399 assert!(tester.capacity() >= len);
2400 for case in 0..(1 << len) {
2401 assert_eq!(tester.len(), 0);
2403 if case & (1 << bit) != 0 {
2404 tester.push_front(Zst);
2406 tester.push_back(Zst);
2409 assert_eq!(tester.len(), len);
2410 assert_eq!(tester.iter().count(), len);