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};
29 use core::hash::{Hash, Hasher};
32 use alloc::raw_vec::RawVec;
34 use super::range::RangeArgument;
36 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
37 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
38 #[cfg(target_pointer_width = "32")]
39 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
40 #[cfg(target_pointer_width = "64")]
41 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
43 /// `VecDeque` is a growable ring buffer, which can be used as a double-ended
44 /// queue efficiently.
46 /// The "default" usage of this type as a queue is to use `push_back` to add to
47 /// the queue, and `pop_front` to remove from the queue. `extend` and `append`
48 /// push onto the back in this manner, and iterating over `VecDeque` goes front
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub struct VecDeque<T> {
52 // tail and head are pointers into the buffer. Tail always points
53 // to the first element that could be read, Head always points
54 // to where data should be written.
55 // If tail == head the buffer is empty. The length of the ringbuffer
56 // is defined as the distance between the two.
62 #[stable(feature = "rust1", since = "1.0.0")]
63 impl<T: Clone> Clone for VecDeque<T> {
64 fn clone(&self) -> VecDeque<T> {
65 self.iter().cloned().collect()
69 #[stable(feature = "rust1", since = "1.0.0")]
70 impl<T> Drop for VecDeque<T> {
71 #[unsafe_destructor_blind_to_params]
74 // RawVec handles deallocation
78 #[stable(feature = "rust1", since = "1.0.0")]
79 impl<T> Default for VecDeque<T> {
81 fn default() -> VecDeque<T> {
87 /// Marginally more convenient
89 fn ptr(&self) -> *mut T {
93 /// Marginally more convenient
95 fn cap(&self) -> usize {
96 if mem::size_of::<T>() == 0 {
97 // For zero sized types, we are always at maximum capacity
104 /// Turn ptr into a slice
106 unsafe fn buffer_as_slice(&self) -> &[T] {
107 slice::from_raw_parts(self.ptr(), self.cap())
110 /// Turn ptr into a mut slice
112 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
113 slice::from_raw_parts_mut(self.ptr(), self.cap())
116 /// Moves an element out of the buffer
118 unsafe fn buffer_read(&mut self, off: usize) -> T {
119 ptr::read(self.ptr().offset(off as isize))
122 /// Writes an element into the buffer, moving it.
124 unsafe fn buffer_write(&mut self, off: usize, value: T) {
125 ptr::write(self.ptr().offset(off as isize), value);
128 /// Returns true if and only if the buffer is at capacity
130 fn is_full(&self) -> bool {
131 self.cap() - self.len() == 1
134 /// Returns the index in the underlying buffer for a given logical element
137 fn wrap_index(&self, idx: usize) -> usize {
138 wrap_index(idx, self.cap())
141 /// Returns the index in the underlying buffer for a given logical element
144 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
145 wrap_index(idx.wrapping_add(addend), self.cap())
148 /// Returns the index in the underlying buffer for a given logical element
149 /// index - subtrahend.
151 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
152 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
155 /// Copies a contiguous block of memory len long from src to dst
157 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
158 debug_assert!(dst + len <= self.cap(),
159 "cpy dst={} src={} len={} cap={}",
164 debug_assert!(src + len <= self.cap(),
165 "cpy dst={} src={} len={} cap={}",
170 ptr::copy(self.ptr().offset(src as isize),
171 self.ptr().offset(dst as isize),
175 /// Copies a contiguous block of memory len long from src to dst
177 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
178 debug_assert!(dst + len <= self.cap(),
179 "cno dst={} src={} len={} cap={}",
184 debug_assert!(src + len <= self.cap(),
185 "cno dst={} src={} len={} cap={}",
190 ptr::copy_nonoverlapping(self.ptr().offset(src as isize),
191 self.ptr().offset(dst as isize),
195 /// Copies a potentially wrapping block of memory len long from src to dest.
196 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
197 /// most one continuous overlapping region between src and dest).
198 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
200 fn diff(a: usize, b: usize) -> usize {
207 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
208 "wrc dst={} src={} len={} cap={}",
214 if src == dst || len == 0 {
218 let dst_after_src = self.wrap_sub(dst, src) < len;
220 let src_pre_wrap_len = self.cap() - src;
221 let dst_pre_wrap_len = self.cap() - dst;
222 let src_wraps = src_pre_wrap_len < len;
223 let dst_wraps = dst_pre_wrap_len < len;
225 match (dst_after_src, src_wraps, dst_wraps) {
226 (_, false, false) => {
227 // src doesn't wrap, dst doesn't wrap
230 // 1 [_ _ A A B B C C _]
231 // 2 [_ _ A A A A B B _]
234 self.copy(dst, src, len);
236 (false, false, true) => {
237 // dst before src, src doesn't wrap, dst wraps
240 // 1 [A A B B _ _ _ C C]
241 // 2 [A A B B _ _ _ A A]
242 // 3 [B B B B _ _ _ A A]
245 self.copy(dst, src, dst_pre_wrap_len);
246 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
248 (true, false, true) => {
249 // src before dst, src doesn't wrap, dst wraps
252 // 1 [C C _ _ _ A A B B]
253 // 2 [B B _ _ _ A A B B]
254 // 3 [B B _ _ _ A A A A]
257 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
258 self.copy(dst, src, dst_pre_wrap_len);
260 (false, true, false) => {
261 // dst before src, src wraps, dst doesn't wrap
264 // 1 [C C _ _ _ A A B B]
265 // 2 [C C _ _ _ B B B B]
266 // 3 [C C _ _ _ B B C C]
269 self.copy(dst, src, src_pre_wrap_len);
270 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
272 (true, true, false) => {
273 // src before dst, src wraps, dst doesn't wrap
276 // 1 [A A B B _ _ _ C C]
277 // 2 [A A A A _ _ _ C C]
278 // 3 [C C A A _ _ _ C C]
281 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
282 self.copy(dst, src, src_pre_wrap_len);
284 (false, true, true) => {
285 // dst before src, src wraps, dst wraps
288 // 1 [A B C D _ E F G H]
289 // 2 [A B C D _ E G H H]
290 // 3 [A B C D _ E G H A]
291 // 4 [B C C D _ E G H A]
294 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
295 let delta = dst_pre_wrap_len - src_pre_wrap_len;
296 self.copy(dst, src, src_pre_wrap_len);
297 self.copy(dst + src_pre_wrap_len, 0, delta);
298 self.copy(0, delta, len - dst_pre_wrap_len);
300 (true, true, true) => {
301 // src before dst, src wraps, dst wraps
304 // 1 [A B C D _ E F G H]
305 // 2 [A A B D _ E F G H]
306 // 3 [H A B D _ E F G H]
307 // 4 [H A B D _ E F F G]
310 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
311 let delta = src_pre_wrap_len - dst_pre_wrap_len;
312 self.copy(delta, 0, len - src_pre_wrap_len);
313 self.copy(0, self.cap() - delta, delta);
314 self.copy(dst, src, dst_pre_wrap_len);
319 /// Frobs the head and tail sections around to handle the fact that we
320 /// just reallocated. Unsafe because it trusts old_cap.
322 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
323 let new_cap = self.cap();
325 // Move the shortest contiguous section of the ring buffer
327 // [o o o o o o o . ]
329 // A [o o o o o o o . . . . . . . . . ]
331 // [o o . o o o o o ]
333 // B [. . . o o o o o o o . . . . . . ]
335 // [o o o o o . o o ]
337 // C [o o o o o . . . . . . . . . o o ]
339 if self.tail <= self.head {
342 } else if self.head < old_cap - self.tail {
344 self.copy_nonoverlapping(old_cap, 0, self.head);
345 self.head += old_cap;
346 debug_assert!(self.head > self.tail);
349 let new_tail = new_cap - (old_cap - self.tail);
350 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
351 self.tail = new_tail;
352 debug_assert!(self.head < self.tail);
354 debug_assert!(self.head < self.cap());
355 debug_assert!(self.tail < self.cap());
356 debug_assert!(self.cap().count_ones() == 1);
360 impl<T> VecDeque<T> {
361 /// Creates an empty `VecDeque`.
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn new() -> VecDeque<T> {
364 VecDeque::with_capacity(INITIAL_CAPACITY)
367 /// Creates an empty `VecDeque` with space for at least `n` elements.
368 #[stable(feature = "rust1", since = "1.0.0")]
369 pub fn with_capacity(n: usize) -> VecDeque<T> {
370 // +1 since the ringbuffer always leaves one space empty
371 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
372 assert!(cap > n, "capacity overflow");
377 buf: RawVec::with_capacity(cap),
381 /// Retrieves an element in the `VecDeque` by index.
386 /// use std::collections::VecDeque;
388 /// let mut buf = VecDeque::new();
389 /// buf.push_back(3);
390 /// buf.push_back(4);
391 /// buf.push_back(5);
392 /// assert_eq!(buf.get(1), Some(&4));
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn get(&self, index: usize) -> Option<&T> {
396 if index < self.len() {
397 let idx = self.wrap_add(self.tail, index);
398 unsafe { Some(&*self.ptr().offset(idx as isize)) }
404 /// Retrieves an element in the `VecDeque` mutably by index.
409 /// use std::collections::VecDeque;
411 /// let mut buf = VecDeque::new();
412 /// buf.push_back(3);
413 /// buf.push_back(4);
414 /// buf.push_back(5);
415 /// if let Some(elem) = buf.get_mut(1) {
419 /// assert_eq!(buf[1], 7);
421 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
423 if index < self.len() {
424 let idx = self.wrap_add(self.tail, index);
425 unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
431 /// Swaps elements at indices `i` and `j`.
433 /// `i` and `j` may be equal.
435 /// Fails if there is no element with either index.
440 /// use std::collections::VecDeque;
442 /// let mut buf = VecDeque::new();
443 /// buf.push_back(3);
444 /// buf.push_back(4);
445 /// buf.push_back(5);
447 /// assert_eq!(buf[0], 5);
448 /// assert_eq!(buf[2], 3);
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn swap(&mut self, i: usize, j: usize) {
452 assert!(i < self.len());
453 assert!(j < self.len());
454 let ri = self.wrap_add(self.tail, i);
455 let rj = self.wrap_add(self.tail, j);
457 ptr::swap(self.ptr().offset(ri as isize),
458 self.ptr().offset(rj as isize))
462 /// Returns the number of elements the `VecDeque` can hold without
468 /// use std::collections::VecDeque;
470 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
471 /// assert!(buf.capacity() >= 10);
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn capacity(&self) -> usize {
479 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
480 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
482 /// Note that the allocator may give the collection more space than it requests. Therefore
483 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
484 /// insertions are expected.
488 /// Panics if the new capacity overflows `usize`.
493 /// use std::collections::VecDeque;
495 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
496 /// buf.reserve_exact(10);
497 /// assert!(buf.capacity() >= 11);
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub fn reserve_exact(&mut self, additional: usize) {
501 self.reserve(additional);
504 /// Reserves capacity for at least `additional` more elements to be inserted in the given
505 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
509 /// Panics if the new capacity overflows `usize`.
514 /// use std::collections::VecDeque;
516 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
518 /// assert!(buf.capacity() >= 11);
520 #[stable(feature = "rust1", since = "1.0.0")]
521 pub fn reserve(&mut self, additional: usize) {
522 let old_cap = self.cap();
523 let used_cap = self.len() + 1;
524 let new_cap = used_cap.checked_add(additional)
525 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
526 .expect("capacity overflow");
528 if new_cap > self.capacity() {
529 self.buf.reserve_exact(used_cap, new_cap - used_cap);
531 self.handle_cap_increase(old_cap);
536 /// Shrinks the capacity of the `VecDeque` as much as possible.
538 /// It will drop down as close as possible to the length but the allocator may still inform the
539 /// `VecDeque` that there is space for a few more elements.
544 /// use std::collections::VecDeque;
546 /// let mut buf = VecDeque::with_capacity(15);
547 /// buf.extend(0..4);
548 /// assert_eq!(buf.capacity(), 15);
549 /// buf.shrink_to_fit();
550 /// assert!(buf.capacity() >= 4);
552 #[stable(feature = "deque_extras_15", since = "1.5.0")]
553 pub fn shrink_to_fit(&mut self) {
554 // +1 since the ringbuffer always leaves one space empty
555 // len + 1 can't overflow for an existing, well-formed ringbuffer.
556 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
557 if target_cap < self.cap() {
558 // There are three cases of interest:
559 // All elements are out of desired bounds
560 // Elements are contiguous, and head is out of desired bounds
561 // Elements are discontiguous, and tail is out of desired bounds
563 // At all other times, element positions are unaffected.
565 // Indicates that elements at the head should be moved.
566 let head_outside = self.head == 0 || self.head >= target_cap;
567 // Move elements from out of desired bounds (positions after target_cap)
568 if self.tail >= target_cap && head_outside {
570 // [. . . . . . . . o o o o o o o . ]
572 // [o o o o o o o . ]
574 self.copy_nonoverlapping(0, self.tail, self.len());
576 self.head = self.len();
578 } else if self.tail != 0 && self.tail < target_cap && head_outside {
580 // [. . . o o o o o o o . . . . . . ]
582 // [o o . o o o o o ]
583 let len = self.wrap_sub(self.head, target_cap);
585 self.copy_nonoverlapping(0, target_cap, len);
588 debug_assert!(self.head < self.tail);
589 } else if self.tail >= target_cap {
591 // [o o o o o . . . . . . . . . o o ]
593 // [o o o o o . o o ]
594 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
595 let len = self.cap() - self.tail;
596 let new_tail = target_cap - len;
598 self.copy_nonoverlapping(new_tail, self.tail, len);
600 self.tail = new_tail;
601 debug_assert!(self.head < self.tail);
604 self.buf.shrink_to_fit(target_cap);
606 debug_assert!(self.head < self.cap());
607 debug_assert!(self.tail < self.cap());
608 debug_assert!(self.cap().count_ones() == 1);
612 /// Shortens a `VecDeque`, dropping excess elements from the back.
614 /// If `len` is greater than the `VecDeque`'s current length, this has no
620 /// #![feature(deque_extras)]
622 /// use std::collections::VecDeque;
624 /// let mut buf = VecDeque::new();
625 /// buf.push_back(5);
626 /// buf.push_back(10);
627 /// buf.push_back(15);
629 /// assert_eq!(buf.len(), 1);
630 /// assert_eq!(Some(&5), buf.get(0));
632 #[unstable(feature = "deque_extras",
633 reason = "matches collection reform specification; waiting on panic semantics",
635 pub fn truncate(&mut self, len: usize) {
636 for _ in len..self.len() {
641 /// Returns a front-to-back iterator.
646 /// use std::collections::VecDeque;
648 /// let mut buf = VecDeque::new();
649 /// buf.push_back(5);
650 /// buf.push_back(3);
651 /// buf.push_back(4);
652 /// let b: &[_] = &[&5, &3, &4];
653 /// let c: Vec<&i32> = buf.iter().collect();
654 /// assert_eq!(&c[..], b);
656 #[stable(feature = "rust1", since = "1.0.0")]
657 pub fn iter(&self) -> Iter<T> {
661 ring: unsafe { self.buffer_as_slice() },
665 /// Returns a front-to-back iterator that returns mutable references.
670 /// use std::collections::VecDeque;
672 /// let mut buf = VecDeque::new();
673 /// buf.push_back(5);
674 /// buf.push_back(3);
675 /// buf.push_back(4);
676 /// for num in buf.iter_mut() {
679 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
680 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn iter_mut(&mut self) -> IterMut<T> {
687 ring: unsafe { self.buffer_as_mut_slice() },
691 /// Returns a pair of slices which contain, in order, the contents of the
694 #[stable(feature = "deque_extras_15", since = "1.5.0")]
695 pub fn as_slices(&self) -> (&[T], &[T]) {
697 let contiguous = self.is_contiguous();
698 let buf = self.buffer_as_slice();
700 let (empty, buf) = buf.split_at(0);
701 (&buf[self.tail..self.head], empty)
703 let (mid, right) = buf.split_at(self.tail);
704 let (left, _) = mid.split_at(self.head);
710 /// Returns a pair of slices which contain, in order, the contents of the
713 #[stable(feature = "deque_extras_15", since = "1.5.0")]
714 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
716 let contiguous = self.is_contiguous();
717 let head = self.head;
718 let tail = self.tail;
719 let buf = self.buffer_as_mut_slice();
722 let (empty, buf) = buf.split_at_mut(0);
723 (&mut buf[tail..head], empty)
725 let (mid, right) = buf.split_at_mut(tail);
726 let (left, _) = mid.split_at_mut(head);
733 /// Returns the number of elements in the `VecDeque`.
738 /// use std::collections::VecDeque;
740 /// let mut v = VecDeque::new();
741 /// assert_eq!(v.len(), 0);
743 /// assert_eq!(v.len(), 1);
745 #[stable(feature = "rust1", since = "1.0.0")]
746 pub fn len(&self) -> usize {
747 count(self.tail, self.head, self.cap())
750 /// Returns true if the buffer contains no elements
755 /// use std::collections::VecDeque;
757 /// let mut v = VecDeque::new();
758 /// assert!(v.is_empty());
760 /// assert!(!v.is_empty());
762 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn is_empty(&self) -> bool {
767 /// Create a draining iterator that removes the specified range in the
768 /// `VecDeque` and yields the removed items.
770 /// Note 1: The element range is removed even if the iterator is not
771 /// consumed until the end.
773 /// Note 2: It is unspecified how many elements are removed from the deque,
774 /// if the `Drain` value is not dropped, but the borrow it holds expires
775 /// (eg. due to mem::forget).
779 /// Panics if the starting point is greater than the end point or if
780 /// the end point is greater than the length of the vector.
785 /// use std::collections::VecDeque;
787 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
788 /// assert_eq!(vec![3].into_iter().collect::<VecDeque<_>>(), v.drain(2..).collect());
789 /// assert_eq!(vec![1, 2].into_iter().collect::<VecDeque<_>>(), v);
791 /// // A full range clears all contents
793 /// assert!(v.is_empty());
796 #[stable(feature = "drain", since = "1.6.0")]
797 pub fn drain<R>(&mut self, range: R) -> Drain<T>
798 where R: RangeArgument<usize>
802 // When the Drain is first created, the source deque is shortened to
803 // make sure no uninitialized or moved-from elements are accessible at
804 // all if the Drain's destructor never gets to run.
806 // Drain will ptr::read out the values to remove.
807 // When finished, the remaining data will be copied back to cover the hole,
808 // and the head/tail values will be restored correctly.
810 let len = self.len();
811 let start = *range.start().unwrap_or(&0);
812 let end = *range.end().unwrap_or(&len);
813 assert!(start <= end, "drain lower bound was too large");
814 assert!(end <= len, "drain upper bound was too large");
816 // The deque's elements are parted into three segments:
817 // * self.tail -> drain_tail
818 // * drain_tail -> drain_head
819 // * drain_head -> self.head
821 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
823 // We store drain_tail as self.head, and drain_head and self.head as
824 // after_tail and after_head respectively on the Drain. This also
825 // truncates the effective array such that if the Drain is leaked, we
826 // have forgotten about the potentially moved values after the start of
830 // [. . . o o x x o o . . .]
832 let drain_tail = self.wrap_add(self.tail, start);
833 let drain_head = self.wrap_add(self.tail, end);
834 let head = self.head;
836 // "forget" about the values after the start of the drain until after
837 // the drain is complete and the Drain destructor is run.
838 self.head = drain_tail;
841 deque: self as *mut _,
842 after_tail: drain_head,
847 ring: unsafe { self.buffer_as_mut_slice() },
852 /// Clears the buffer, removing all values.
857 /// use std::collections::VecDeque;
859 /// let mut v = VecDeque::new();
862 /// assert!(v.is_empty());
864 #[stable(feature = "rust1", since = "1.0.0")]
866 pub fn clear(&mut self) {
870 /// Provides a reference to the front element, or `None` if the sequence is
876 /// use std::collections::VecDeque;
878 /// let mut d = VecDeque::new();
879 /// assert_eq!(d.front(), None);
883 /// assert_eq!(d.front(), Some(&1));
885 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn front(&self) -> Option<&T> {
887 if !self.is_empty() {
894 /// Provides a mutable reference to the front element, or `None` if the
895 /// sequence is empty.
900 /// use std::collections::VecDeque;
902 /// let mut d = VecDeque::new();
903 /// assert_eq!(d.front_mut(), None);
907 /// match d.front_mut() {
908 /// Some(x) => *x = 9,
911 /// assert_eq!(d.front(), Some(&9));
913 #[stable(feature = "rust1", since = "1.0.0")]
914 pub fn front_mut(&mut self) -> Option<&mut T> {
915 if !self.is_empty() {
922 /// Provides a reference to the back element, or `None` if the sequence is
928 /// use std::collections::VecDeque;
930 /// let mut d = VecDeque::new();
931 /// assert_eq!(d.back(), None);
935 /// assert_eq!(d.back(), Some(&2));
937 #[stable(feature = "rust1", since = "1.0.0")]
938 pub fn back(&self) -> Option<&T> {
939 if !self.is_empty() {
940 Some(&self[self.len() - 1])
946 /// Provides a mutable reference to the back element, or `None` if the
947 /// sequence is empty.
952 /// use std::collections::VecDeque;
954 /// let mut d = VecDeque::new();
955 /// assert_eq!(d.back(), None);
959 /// match d.back_mut() {
960 /// Some(x) => *x = 9,
963 /// assert_eq!(d.back(), Some(&9));
965 #[stable(feature = "rust1", since = "1.0.0")]
966 pub fn back_mut(&mut self) -> Option<&mut T> {
967 let len = self.len();
968 if !self.is_empty() {
969 Some(&mut self[len - 1])
975 /// Removes the first element and returns it, or `None` if the sequence is
981 /// use std::collections::VecDeque;
983 /// let mut d = VecDeque::new();
987 /// assert_eq!(d.pop_front(), Some(1));
988 /// assert_eq!(d.pop_front(), Some(2));
989 /// assert_eq!(d.pop_front(), None);
991 #[stable(feature = "rust1", since = "1.0.0")]
992 pub fn pop_front(&mut self) -> Option<T> {
996 let tail = self.tail;
997 self.tail = self.wrap_add(self.tail, 1);
998 unsafe { Some(self.buffer_read(tail)) }
1002 /// Inserts an element first in the sequence.
1007 /// use std::collections::VecDeque;
1009 /// let mut d = VecDeque::new();
1010 /// d.push_front(1);
1011 /// d.push_front(2);
1012 /// assert_eq!(d.front(), Some(&2));
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 pub fn push_front(&mut self, value: T) {
1017 let old_cap = self.cap();
1020 self.handle_cap_increase(old_cap);
1022 debug_assert!(!self.is_full());
1025 self.tail = self.wrap_sub(self.tail, 1);
1026 let tail = self.tail;
1028 self.buffer_write(tail, value);
1032 /// Appends an element to the back of a buffer
1037 /// use std::collections::VecDeque;
1039 /// let mut buf = VecDeque::new();
1040 /// buf.push_back(1);
1041 /// buf.push_back(3);
1042 /// assert_eq!(3, *buf.back().unwrap());
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 pub fn push_back(&mut self, value: T) {
1047 let old_cap = self.cap();
1050 self.handle_cap_increase(old_cap);
1052 debug_assert!(!self.is_full());
1055 let head = self.head;
1056 self.head = self.wrap_add(self.head, 1);
1057 unsafe { self.buffer_write(head, value) }
1060 /// Removes the last element from a buffer and returns it, or `None` if
1066 /// use std::collections::VecDeque;
1068 /// let mut buf = VecDeque::new();
1069 /// assert_eq!(buf.pop_back(), None);
1070 /// buf.push_back(1);
1071 /// buf.push_back(3);
1072 /// assert_eq!(buf.pop_back(), Some(3));
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 pub fn pop_back(&mut self) -> Option<T> {
1076 if self.is_empty() {
1079 self.head = self.wrap_sub(self.head, 1);
1080 let head = self.head;
1081 unsafe { Some(self.buffer_read(head)) }
1086 fn is_contiguous(&self) -> bool {
1087 self.tail <= self.head
1090 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1093 /// This does not preserve ordering, but is O(1).
1095 /// Returns `None` if `index` is out of bounds.
1100 /// use std::collections::VecDeque;
1102 /// let mut buf = VecDeque::new();
1103 /// assert_eq!(buf.swap_remove_back(0), None);
1104 /// buf.push_back(1);
1105 /// buf.push_back(2);
1106 /// buf.push_back(3);
1108 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1109 /// assert_eq!(buf.len(), 2);
1110 /// assert_eq!(buf[0], 3);
1111 /// assert_eq!(buf[1], 2);
1113 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1114 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1115 let length = self.len();
1116 if length > 0 && index < length - 1 {
1117 self.swap(index, length - 1);
1118 } else if index >= length {
1124 /// Removes an element from anywhere in the `VecDeque` and returns it,
1125 /// replacing it with the first element.
1127 /// This does not preserve ordering, but is O(1).
1129 /// Returns `None` if `index` is out of bounds.
1134 /// use std::collections::VecDeque;
1136 /// let mut buf = VecDeque::new();
1137 /// assert_eq!(buf.swap_remove_front(0), None);
1138 /// buf.push_back(1);
1139 /// buf.push_back(2);
1140 /// buf.push_back(3);
1142 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1143 /// assert_eq!(buf.len(), 2);
1144 /// assert_eq!(buf[0], 2);
1145 /// assert_eq!(buf[1], 1);
1147 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1148 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1149 let length = self.len();
1150 if length > 0 && index < length && index != 0 {
1151 self.swap(index, 0);
1152 } else if index >= length {
1158 /// Inserts an element at `index` within the `VecDeque`. Whichever
1159 /// end is closer to the insertion point will be moved to make room,
1160 /// and all the affected elements will be moved to new positions.
1164 /// Panics if `index` is greater than `VecDeque`'s length
1168 /// use std::collections::VecDeque;
1170 /// let mut buf = VecDeque::new();
1171 /// buf.push_back(10);
1172 /// buf.push_back(12);
1173 /// buf.insert(1, 11);
1174 /// assert_eq!(Some(&11), buf.get(1));
1176 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1177 pub fn insert(&mut self, index: usize, value: T) {
1178 assert!(index <= self.len(), "index out of bounds");
1180 let old_cap = self.cap();
1183 self.handle_cap_increase(old_cap);
1185 debug_assert!(!self.is_full());
1188 // Move the least number of elements in the ring buffer and insert
1191 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1193 // There are three main cases:
1194 // Elements are contiguous
1195 // - special case when tail is 0
1196 // Elements are discontiguous and the insert is in the tail section
1197 // Elements are discontiguous and the insert is in the head section
1199 // For each of those there are two more cases:
1200 // Insert is closer to tail
1201 // Insert is closer to head
1203 // Key: H - self.head
1205 // o - Valid element
1206 // I - Insertion element
1207 // A - The element that should be after the insertion point
1208 // M - Indicates element was moved
1210 let idx = self.wrap_add(self.tail, index);
1212 let distance_to_tail = index;
1213 let distance_to_head = self.len() - index;
1215 let contiguous = self.is_contiguous();
1218 distance_to_tail <= distance_to_head,
1220 (true, true, _) if index == 0 => {
1225 // [A o o o o o o . . . . . . . . .]
1228 // [A o o o o o o o . . . . . I]
1231 self.tail = self.wrap_sub(self.tail, 1);
1233 (true, true, _) => {
1235 // contiguous, insert closer to tail:
1238 // [. . . o o A o o o o . . . . . .]
1241 // [. . o o I A o o o o . . . . . .]
1244 // contiguous, insert closer to tail and tail is 0:
1248 // [o o A o o o o . . . . . . . . .]
1251 // [o I A o o o o o . . . . . . . o]
1254 let new_tail = self.wrap_sub(self.tail, 1);
1256 self.copy(new_tail, self.tail, 1);
1257 // Already moved the tail, so we only copy `index - 1` elements.
1258 self.copy(self.tail, self.tail + 1, index - 1);
1260 self.tail = new_tail;
1263 (true, false, _) => {
1265 // contiguous, insert closer to head:
1268 // [. . . o o o o A o o . . . . . .]
1271 // [. . . o o o o I A o o . . . . .]
1274 self.copy(idx + 1, idx, self.head - idx);
1275 self.head = self.wrap_add(self.head, 1);
1278 (false, true, true) => {
1280 // discontiguous, insert closer to tail, tail section:
1283 // [o o o o o o . . . . . o o A o o]
1286 // [o o o o o o . . . . o o I A o o]
1289 self.copy(self.tail - 1, self.tail, index);
1293 (false, false, true) => {
1295 // discontiguous, insert closer to head, tail section:
1298 // [o o . . . . . . . o o o o o A o]
1301 // [o o o . . . . . . o o o o o I A]
1304 // copy elements up to new head
1305 self.copy(1, 0, self.head);
1307 // copy last element into empty spot at bottom of buffer
1308 self.copy(0, self.cap() - 1, 1);
1310 // move elements from idx to end forward not including ^ element
1311 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1316 (false, true, false) if idx == 0 => {
1318 // discontiguous, insert is closer to tail, head section,
1319 // and is at index zero in the internal buffer:
1322 // [A o o o o o o o o o . . . o o o]
1325 // [A o o o o o o o o o . . o o o I]
1328 // copy elements up to new tail
1329 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1331 // copy last element into empty spot at bottom of buffer
1332 self.copy(self.cap() - 1, 0, 1);
1337 (false, true, false) => {
1339 // discontiguous, insert closer to tail, head section:
1342 // [o o o A o o o o o o . . . o o o]
1345 // [o o I A o o o o o o . . o o o o]
1348 // copy elements up to new tail
1349 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1351 // copy last element into empty spot at bottom of buffer
1352 self.copy(self.cap() - 1, 0, 1);
1354 // move elements from idx-1 to end forward not including ^ element
1355 self.copy(0, 1, idx - 1);
1360 (false, false, false) => {
1362 // discontiguous, insert closer to head, head section:
1365 // [o o o o A o o . . . . . . o o o]
1368 // [o o o o I A o o . . . . . o o o]
1371 self.copy(idx + 1, idx, self.head - idx);
1377 // tail might've been changed so we need to recalculate
1378 let new_idx = self.wrap_add(self.tail, index);
1380 self.buffer_write(new_idx, value);
1384 /// Removes and returns the element at `index` from the `VecDeque`.
1385 /// Whichever end is closer to the removal point will be moved to make
1386 /// room, and all the affected elements will be moved to new positions.
1387 /// Returns `None` if `index` is out of bounds.
1391 /// use std::collections::VecDeque;
1393 /// let mut buf = VecDeque::new();
1394 /// buf.push_back(1);
1395 /// buf.push_back(2);
1396 /// buf.push_back(3);
1398 /// assert_eq!(buf.remove(1), Some(2));
1399 /// assert_eq!(buf.get(1), Some(&3));
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub fn remove(&mut self, index: usize) -> Option<T> {
1403 if self.is_empty() || self.len() <= index {
1407 // There are three main cases:
1408 // Elements are contiguous
1409 // Elements are discontiguous and the removal is in the tail section
1410 // Elements are discontiguous and the removal is in the head section
1411 // - special case when elements are technically contiguous,
1412 // but self.head = 0
1414 // For each of those there are two more cases:
1415 // Insert is closer to tail
1416 // Insert is closer to head
1418 // Key: H - self.head
1420 // o - Valid element
1421 // x - Element marked for removal
1422 // R - Indicates element that is being removed
1423 // M - Indicates element was moved
1425 let idx = self.wrap_add(self.tail, index);
1427 let elem = unsafe { Some(self.buffer_read(idx)) };
1429 let distance_to_tail = index;
1430 let distance_to_head = self.len() - index;
1432 let contiguous = self.is_contiguous();
1435 distance_to_tail <= distance_to_head,
1437 (true, true, _) => {
1439 // contiguous, remove closer to tail:
1442 // [. . . o o x o o o o . . . . . .]
1445 // [. . . . o o o o o o . . . . . .]
1448 self.copy(self.tail + 1, self.tail, index);
1452 (true, false, _) => {
1454 // contiguous, remove closer to head:
1457 // [. . . o o o o x o o . . . . . .]
1460 // [. . . o o o o o o . . . . . . .]
1463 self.copy(idx, idx + 1, self.head - idx - 1);
1467 (false, true, true) => {
1469 // discontiguous, remove closer to tail, tail section:
1472 // [o o o o o o . . . . . o o x o o]
1475 // [o o o o o o . . . . . . o o o o]
1478 self.copy(self.tail + 1, self.tail, index);
1479 self.tail = self.wrap_add(self.tail, 1);
1482 (false, false, false) => {
1484 // discontiguous, remove closer to head, head section:
1487 // [o o o o x o o . . . . . . o o o]
1490 // [o o o o o o . . . . . . . o o o]
1493 self.copy(idx, idx + 1, self.head - idx - 1);
1497 (false, false, true) => {
1499 // discontiguous, remove closer to head, tail section:
1502 // [o o o . . . . . . o o o o o x o]
1505 // [o o . . . . . . . o o o o o o o]
1508 // or quasi-discontiguous, remove next to head, tail section:
1511 // [. . . . . . . . . o o o o o x o]
1514 // [. . . . . . . . . o o o o o o .]
1517 // draw in elements in the tail section
1518 self.copy(idx, idx + 1, self.cap() - idx - 1);
1520 // Prevents underflow.
1522 // copy first element into empty spot
1523 self.copy(self.cap() - 1, 0, 1);
1525 // move elements in the head section backwards
1526 self.copy(0, 1, self.head - 1);
1529 self.head = self.wrap_sub(self.head, 1);
1532 (false, true, false) => {
1534 // discontiguous, remove closer to tail, head section:
1537 // [o o x o o o o o o o . . . o o o]
1540 // [o o o o o o o o o o . . . . o o]
1543 // draw in elements up to idx
1544 self.copy(1, 0, idx);
1546 // copy last element into empty spot
1547 self.copy(0, self.cap() - 1, 1);
1549 // move elements from tail to end forward, excluding the last one
1550 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1552 self.tail = self.wrap_add(self.tail, 1);
1560 /// Splits the collection into two at the given index.
1562 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1563 /// and the returned `Self` contains elements `[at, len)`.
1565 /// Note that the capacity of `self` does not change.
1569 /// Panics if `at > len`
1574 /// use std::collections::VecDeque;
1576 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1577 /// let buf2 = buf.split_off(1);
1578 /// // buf = [1], buf2 = [2, 3]
1579 /// assert_eq!(buf.len(), 1);
1580 /// assert_eq!(buf2.len(), 2);
1583 #[stable(feature = "split_off", since = "1.4.0")]
1584 pub fn split_off(&mut self, at: usize) -> Self {
1585 let len = self.len();
1586 assert!(at <= len, "`at` out of bounds");
1588 let other_len = len - at;
1589 let mut other = VecDeque::with_capacity(other_len);
1592 let (first_half, second_half) = self.as_slices();
1594 let first_len = first_half.len();
1595 let second_len = second_half.len();
1597 // `at` lies in the first half.
1598 let amount_in_first = first_len - at;
1600 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1604 // just take all of the second half.
1605 ptr::copy_nonoverlapping(second_half.as_ptr(),
1606 other.ptr().offset(amount_in_first as isize),
1609 // `at` lies in the second half, need to factor in the elements we skipped
1610 // in the first half.
1611 let offset = at - first_len;
1612 let amount_in_second = second_len - offset;
1613 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1619 // Cleanup where the ends of the buffers are
1620 self.head = self.wrap_sub(self.head, other_len);
1621 other.head = other.wrap_index(other_len);
1626 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1630 /// Panics if the new number of elements in self overflows a `usize`.
1635 /// use std::collections::VecDeque;
1637 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1638 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
1639 /// buf.append(&mut buf2);
1640 /// assert_eq!(buf.len(), 6);
1641 /// assert_eq!(buf2.len(), 0);
1644 #[stable(feature = "append", since = "1.4.0")]
1645 pub fn append(&mut self, other: &mut Self) {
1647 self.extend(other.drain(..));
1650 /// Retains only the elements specified by the predicate.
1652 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1653 /// This method operates in place and preserves the order of the retained
1659 /// use std::collections::VecDeque;
1661 /// let mut buf = VecDeque::new();
1662 /// buf.extend(1..5);
1663 /// buf.retain(|&x| x%2 == 0);
1665 /// let v: Vec<_> = buf.into_iter().collect();
1666 /// assert_eq!(&v[..], &[2, 4]);
1668 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1669 pub fn retain<F>(&mut self, mut f: F)
1670 where F: FnMut(&T) -> bool
1672 let len = self.len();
1678 self.swap(i - del, i);
1682 self.truncate(len - del);
1687 impl<T: Clone> VecDeque<T> {
1688 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1689 /// either by removing excess elements or by appending copies of a value to the back.
1694 /// #![feature(deque_extras)]
1696 /// use std::collections::VecDeque;
1698 /// let mut buf = VecDeque::new();
1699 /// buf.push_back(5);
1700 /// buf.push_back(10);
1701 /// buf.push_back(15);
1702 /// buf.resize(2, 0);
1703 /// buf.resize(6, 20);
1704 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
1705 /// assert_eq!(a, b);
1708 #[unstable(feature = "deque_extras",
1709 reason = "matches collection reform specification; waiting on panic semantics",
1711 pub fn resize(&mut self, new_len: usize, value: T) {
1712 let len = self.len();
1715 self.extend(repeat(value).take(new_len - len))
1717 self.truncate(new_len);
1722 /// Returns the index in the underlying buffer for a given logical element index.
1724 fn wrap_index(index: usize, size: usize) -> usize {
1725 // size is always a power of 2
1726 debug_assert!(size.is_power_of_two());
1730 /// Calculate the number of elements left to be read in the buffer
1732 fn count(tail: usize, head: usize, size: usize) -> usize {
1733 // size is always a power of 2
1734 (head.wrapping_sub(tail)) & (size - 1)
1737 /// `VecDeque` iterator.
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 pub struct Iter<'a, T: 'a> {
1745 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 impl<'a, T> Clone for Iter<'a, T> {
1748 fn clone(&self) -> Iter<'a, T> {
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<'a, T> Iterator for Iter<'a, T> {
1762 fn next(&mut self) -> Option<&'a T> {
1763 if self.tail == self.head {
1766 let tail = self.tail;
1767 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1768 unsafe { Some(self.ring.get_unchecked(tail)) }
1772 fn size_hint(&self) -> (usize, Option<usize>) {
1773 let len = count(self.tail, self.head, self.ring.len());
1778 #[stable(feature = "rust1", since = "1.0.0")]
1779 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1781 fn next_back(&mut self) -> Option<&'a T> {
1782 if self.tail == self.head {
1785 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1786 unsafe { Some(self.ring.get_unchecked(self.head)) }
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1793 /// `VecDeque` mutable iterator.
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 pub struct IterMut<'a, T: 'a> {
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 impl<'a, T> Iterator for IterMut<'a, T> {
1803 type Item = &'a mut T;
1806 fn next(&mut self) -> Option<&'a mut T> {
1807 if self.tail == self.head {
1810 let tail = self.tail;
1811 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1814 let elem = self.ring.get_unchecked_mut(tail);
1815 Some(&mut *(elem as *mut _))
1820 fn size_hint(&self) -> (usize, Option<usize>) {
1821 let len = count(self.tail, self.head, self.ring.len());
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1829 fn next_back(&mut self) -> Option<&'a mut T> {
1830 if self.tail == self.head {
1833 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1836 let elem = self.ring.get_unchecked_mut(self.head);
1837 Some(&mut *(elem as *mut _))
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1845 /// A by-value VecDeque iterator
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 pub struct IntoIter<T> {
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 impl<T> Iterator for IntoIter<T> {
1857 fn next(&mut self) -> Option<T> {
1858 self.inner.pop_front()
1862 fn size_hint(&self) -> (usize, Option<usize>) {
1863 let len = self.inner.len();
1868 #[stable(feature = "rust1", since = "1.0.0")]
1869 impl<T> DoubleEndedIterator for IntoIter<T> {
1871 fn next_back(&mut self) -> Option<T> {
1872 self.inner.pop_back()
1876 #[stable(feature = "rust1", since = "1.0.0")]
1877 impl<T> ExactSizeIterator for IntoIter<T> {}
1879 /// A draining VecDeque iterator
1880 #[stable(feature = "drain", since = "1.6.0")]
1881 pub struct Drain<'a, T: 'a> {
1885 deque: *mut VecDeque<T>,
1888 #[stable(feature = "drain", since = "1.6.0")]
1889 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1890 #[stable(feature = "drain", since = "1.6.0")]
1891 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 impl<'a, T: 'a> Drop for Drain<'a, T> {
1895 fn drop(&mut self) {
1896 for _ in self.by_ref() {}
1898 let source_deque = unsafe { &mut *self.deque };
1900 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
1903 // [. . . o o x x o o . . .]
1905 let orig_tail = source_deque.tail;
1906 let drain_tail = source_deque.head;
1907 let drain_head = self.after_tail;
1908 let orig_head = self.after_head;
1910 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
1911 let head_len = count(drain_head, orig_head, source_deque.cap());
1913 // Restore the original head value
1914 source_deque.head = orig_head;
1916 match (tail_len, head_len) {
1918 source_deque.head = 0;
1919 source_deque.tail = 0;
1922 source_deque.tail = drain_head;
1925 source_deque.head = drain_tail;
1929 if tail_len <= head_len {
1930 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
1931 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
1933 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
1934 source_deque.wrap_copy(drain_tail, drain_head, head_len);
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1947 fn next(&mut self) -> Option<T> {
1948 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
1952 fn size_hint(&self) -> (usize, Option<usize>) {
1953 self.iter.size_hint()
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1960 fn next_back(&mut self) -> Option<T> {
1961 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1968 #[stable(feature = "rust1", since = "1.0.0")]
1969 impl<A: PartialEq> PartialEq for VecDeque<A> {
1970 fn eq(&self, other: &VecDeque<A>) -> bool {
1971 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a.eq(b))
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl<A: Eq> Eq for VecDeque<A> {}
1978 #[stable(feature = "rust1", since = "1.0.0")]
1979 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
1980 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
1981 self.iter().partial_cmp(other.iter())
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 impl<A: Ord> Ord for VecDeque<A> {
1988 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
1989 self.iter().cmp(other.iter())
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 impl<A: Hash> Hash for VecDeque<A> {
1995 fn hash<H: Hasher>(&self, state: &mut H) {
1996 self.len().hash(state);
1997 let (a, b) = self.as_slices();
1998 Hash::hash_slice(a, state);
1999 Hash::hash_slice(b, state);
2003 #[stable(feature = "rust1", since = "1.0.0")]
2004 impl<A> Index<usize> for VecDeque<A> {
2008 fn index(&self, index: usize) -> &A {
2009 self.get(index).expect("Out of bounds access")
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl<A> IndexMut<usize> for VecDeque<A> {
2016 fn index_mut(&mut self, index: usize) -> &mut A {
2017 self.get_mut(index).expect("Out of bounds access")
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 impl<A> FromIterator<A> for VecDeque<A> {
2023 fn from_iter<T: IntoIterator<Item = A>>(iterable: T) -> VecDeque<A> {
2024 let iterator = iterable.into_iter();
2025 let (lower, _) = iterator.size_hint();
2026 let mut deq = VecDeque::with_capacity(lower);
2027 deq.extend(iterator);
2032 #[stable(feature = "rust1", since = "1.0.0")]
2033 impl<T> IntoIterator for VecDeque<T> {
2035 type IntoIter = IntoIter<T>;
2037 /// Consumes the list into a front-to-back iterator yielding elements by
2039 fn into_iter(self) -> IntoIter<T> {
2040 IntoIter { inner: self }
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2047 type IntoIter = Iter<'a, T>;
2049 fn into_iter(self) -> Iter<'a, T> {
2054 #[stable(feature = "rust1", since = "1.0.0")]
2055 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2056 type Item = &'a mut T;
2057 type IntoIter = IterMut<'a, T>;
2059 fn into_iter(mut self) -> IterMut<'a, T> {
2064 #[stable(feature = "rust1", since = "1.0.0")]
2065 impl<A> Extend<A> for VecDeque<A> {
2066 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2068 self.push_back(elt);
2073 #[stable(feature = "extend_ref", since = "1.2.0")]
2074 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2075 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2076 self.extend(iter.into_iter().cloned());
2080 #[stable(feature = "rust1", since = "1.0.0")]
2081 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2082 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2083 f.debug_list().entries(self).finish()
2089 use core::iter::Iterator;
2090 use core::option::Option::Some;
2094 use super::VecDeque;
2097 fn bench_push_back_100(b: &mut test::Bencher) {
2098 let mut deq = VecDeque::with_capacity(101);
2109 fn bench_push_front_100(b: &mut test::Bencher) {
2110 let mut deq = VecDeque::with_capacity(101);
2121 fn bench_pop_back_100(b: &mut test::Bencher) {
2122 let mut deq = VecDeque::<i32>::with_capacity(101);
2127 while !deq.is_empty() {
2128 test::black_box(deq.pop_back());
2134 fn bench_pop_front_100(b: &mut test::Bencher) {
2135 let mut deq = VecDeque::<i32>::with_capacity(101);
2140 while !deq.is_empty() {
2141 test::black_box(deq.pop_front());
2147 fn test_swap_front_back_remove() {
2148 fn test(back: bool) {
2149 // This test checks that every single combination of tail position and length is tested.
2150 // Capacity 15 should be large enough to cover every case.
2151 let mut tester = VecDeque::with_capacity(15);
2152 let usable_cap = tester.capacity();
2153 let final_len = usable_cap / 2;
2155 for len in 0..final_len {
2156 let expected = if back {
2159 (0..len).rev().collect()
2161 for tail_pos in 0..usable_cap {
2162 tester.tail = tail_pos;
2163 tester.head = tail_pos;
2165 for i in 0..len * 2 {
2166 tester.push_front(i);
2169 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2172 for i in 0..len * 2 {
2173 tester.push_back(i);
2176 let idx = tester.len() - 1 - i;
2177 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2180 assert!(tester.tail < tester.cap());
2181 assert!(tester.head < tester.cap());
2182 assert_eq!(tester, expected);
2192 // This test checks that every single combination of tail position, length, and
2193 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2195 let mut tester = VecDeque::with_capacity(15);
2196 // can't guarantee we got 15, so have to get what we got.
2197 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2198 // this test isn't covering what it wants to
2199 let cap = tester.capacity();
2202 // len is the length *after* insertion
2204 // 0, 1, 2, .., len - 1
2205 let expected = (0..).take(len).collect();
2206 for tail_pos in 0..cap {
2207 for to_insert in 0..len {
2208 tester.tail = tail_pos;
2209 tester.head = tail_pos;
2212 tester.push_back(i);
2215 tester.insert(to_insert, to_insert);
2216 assert!(tester.tail < tester.cap());
2217 assert!(tester.head < tester.cap());
2218 assert_eq!(tester, expected);
2226 // This test checks that every single combination of tail position, length, and
2227 // removal position is tested. Capacity 15 should be large enough to cover every case.
2229 let mut tester = VecDeque::with_capacity(15);
2230 // can't guarantee we got 15, so have to get what we got.
2231 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2232 // this test isn't covering what it wants to
2233 let cap = tester.capacity();
2235 // len is the length *after* removal
2236 for len in 0..cap - 1 {
2237 // 0, 1, 2, .., len - 1
2238 let expected = (0..).take(len).collect();
2239 for tail_pos in 0..cap {
2240 for to_remove in 0..len + 1 {
2241 tester.tail = tail_pos;
2242 tester.head = tail_pos;
2245 tester.push_back(1234);
2247 tester.push_back(i);
2249 if to_remove == len {
2250 tester.push_back(1234);
2252 tester.remove(to_remove);
2253 assert!(tester.tail < tester.cap());
2254 assert!(tester.head < tester.cap());
2255 assert_eq!(tester, expected);
2263 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2265 let cap = tester.capacity();
2266 for len in 0..cap + 1 {
2267 for tail in 0..cap + 1 {
2268 for drain_start in 0..len + 1 {
2269 for drain_end in drain_start..len + 1 {
2273 tester.push_back(i);
2276 // Check that we drain the correct values
2277 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2278 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2279 assert_eq!(drained, drained_expected);
2281 // We shouldn't have changed the capacity or made the
2282 // head or tail out of bounds
2283 assert_eq!(tester.capacity(), cap);
2284 assert!(tester.tail < tester.cap());
2285 assert!(tester.head < tester.cap());
2287 // We should see the correct values in the VecDeque
2288 let expected: VecDeque<_> = (0..drain_start)
2289 .chain(drain_end..len)
2291 assert_eq!(expected, tester);
2299 fn test_shrink_to_fit() {
2300 // This test checks that every single combination of head and tail position,
2301 // is tested. Capacity 15 should be large enough to cover every case.
2303 let mut tester = VecDeque::with_capacity(15);
2304 // can't guarantee we got 15, so have to get what we got.
2305 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2306 // this test isn't covering what it wants to
2307 let cap = tester.capacity();
2309 let max_cap = tester.capacity();
2311 for len in 0..cap + 1 {
2312 // 0, 1, 2, .., len - 1
2313 let expected = (0..).take(len).collect();
2314 for tail_pos in 0..max_cap + 1 {
2315 tester.tail = tail_pos;
2316 tester.head = tail_pos;
2319 tester.push_back(i);
2321 tester.shrink_to_fit();
2322 assert!(tester.capacity() <= cap);
2323 assert!(tester.tail < tester.cap());
2324 assert!(tester.head < tester.cap());
2325 assert_eq!(tester, expected);
2331 fn test_split_off() {
2332 // This test checks that every single combination of tail position, length, and
2333 // split position is tested. Capacity 15 should be large enough to cover every case.
2335 let mut tester = VecDeque::with_capacity(15);
2336 // can't guarantee we got 15, so have to get what we got.
2337 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2338 // this test isn't covering what it wants to
2339 let cap = tester.capacity();
2341 // len is the length *before* splitting
2343 // index to split at
2344 for at in 0..len + 1 {
2345 // 0, 1, 2, .., at - 1 (may be empty)
2346 let expected_self = (0..).take(at).collect();
2347 // at, at + 1, .., len - 1 (may be empty)
2348 let expected_other = (at..).take(len - at).collect();
2350 for tail_pos in 0..cap {
2351 tester.tail = tail_pos;
2352 tester.head = tail_pos;
2354 tester.push_back(i);
2356 let result = tester.split_off(at);
2357 assert!(tester.tail < tester.cap());
2358 assert!(tester.head < tester.cap());
2359 assert!(result.tail < result.cap());
2360 assert!(result.head < result.cap());
2361 assert_eq!(tester, expected_self);
2362 assert_eq!(result, expected_other);