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, FusedIterator};
25 use core::ops::{Index, IndexMut};
27 use core::ptr::Shared;
30 use core::hash::{Hash, Hasher};
33 use alloc::raw_vec::RawVec;
35 use super::range::RangeArgument;
36 use Bound::{Excluded, Included, Unbounded};
39 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
40 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
41 #[cfg(target_pointer_width = "32")]
42 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
43 #[cfg(target_pointer_width = "64")]
44 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
46 /// `VecDeque` is a growable ring buffer, which can be used as a double-ended
47 /// queue efficiently.
49 /// The "default" usage of this type as a queue is to use `push_back` to add to
50 /// the queue, and `pop_front` to remove from the queue. `extend` and `append`
51 /// push onto the back in this manner, and iterating over `VecDeque` goes front
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub struct VecDeque<T> {
55 // tail and head are pointers into the buffer. Tail always points
56 // to the first element that could be read, Head always points
57 // to where data should be written.
58 // If tail == head the buffer is empty. The length of the ringbuffer
59 // is defined as the distance between the two.
65 #[stable(feature = "rust1", since = "1.0.0")]
66 impl<T: Clone> Clone for VecDeque<T> {
67 fn clone(&self) -> VecDeque<T> {
68 self.iter().cloned().collect()
72 #[stable(feature = "rust1", since = "1.0.0")]
73 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
75 let (front, back) = self.as_mut_slices();
78 ptr::drop_in_place(front);
79 ptr::drop_in_place(back);
81 // RawVec handles deallocation
85 #[stable(feature = "rust1", since = "1.0.0")]
86 impl<T> Default for VecDeque<T> {
87 /// Creates an empty `VecDeque<T>`.
89 fn default() -> VecDeque<T> {
95 /// Marginally more convenient
97 fn ptr(&self) -> *mut T {
101 /// Marginally more convenient
103 fn cap(&self) -> usize {
104 if mem::size_of::<T>() == 0 {
105 // For zero sized types, we are always at maximum capacity
112 /// Turn ptr into a slice
114 unsafe fn buffer_as_slice(&self) -> &[T] {
115 slice::from_raw_parts(self.ptr(), self.cap())
118 /// Turn ptr into a mut slice
120 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
121 slice::from_raw_parts_mut(self.ptr(), self.cap())
124 /// Moves an element out of the buffer
126 unsafe fn buffer_read(&mut self, off: usize) -> T {
127 ptr::read(self.ptr().offset(off as isize))
130 /// Writes an element into the buffer, moving it.
132 unsafe fn buffer_write(&mut self, off: usize, value: T) {
133 ptr::write(self.ptr().offset(off as isize), value);
136 /// Returns true if and only if the buffer is at capacity
138 fn is_full(&self) -> bool {
139 self.cap() - self.len() == 1
142 /// Returns the index in the underlying buffer for a given logical element
145 fn wrap_index(&self, idx: usize) -> usize {
146 wrap_index(idx, self.cap())
149 /// Returns the index in the underlying buffer for a given logical element
152 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
153 wrap_index(idx.wrapping_add(addend), self.cap())
156 /// Returns the index in the underlying buffer for a given logical element
157 /// index - subtrahend.
159 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
160 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
163 /// Copies a contiguous block of memory len long from src to dst
165 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
166 debug_assert!(dst + len <= self.cap(),
167 "cpy dst={} src={} len={} cap={}",
172 debug_assert!(src + len <= self.cap(),
173 "cpy dst={} src={} len={} cap={}",
178 ptr::copy(self.ptr().offset(src as isize),
179 self.ptr().offset(dst as isize),
183 /// Copies a contiguous block of memory len long from src to dst
185 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
186 debug_assert!(dst + len <= self.cap(),
187 "cno dst={} src={} len={} cap={}",
192 debug_assert!(src + len <= self.cap(),
193 "cno dst={} src={} len={} cap={}",
198 ptr::copy_nonoverlapping(self.ptr().offset(src as isize),
199 self.ptr().offset(dst as isize),
203 /// Copies a potentially wrapping block of memory len long from src to dest.
204 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
205 /// most one continuous overlapping region between src and dest).
206 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
208 fn diff(a: usize, b: usize) -> usize {
209 if a <= b { b - a } else { a - b }
211 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
212 "wrc dst={} src={} len={} cap={}",
218 if src == dst || len == 0 {
222 let dst_after_src = self.wrap_sub(dst, src) < len;
224 let src_pre_wrap_len = self.cap() - src;
225 let dst_pre_wrap_len = self.cap() - dst;
226 let src_wraps = src_pre_wrap_len < len;
227 let dst_wraps = dst_pre_wrap_len < len;
229 match (dst_after_src, src_wraps, dst_wraps) {
230 (_, false, false) => {
231 // src doesn't wrap, dst doesn't wrap
234 // 1 [_ _ A A B B C C _]
235 // 2 [_ _ A A A A B B _]
238 self.copy(dst, src, len);
240 (false, false, true) => {
241 // dst before src, src doesn't wrap, dst wraps
244 // 1 [A A B B _ _ _ C C]
245 // 2 [A A B B _ _ _ A A]
246 // 3 [B B B B _ _ _ A A]
249 self.copy(dst, src, dst_pre_wrap_len);
250 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
252 (true, false, true) => {
253 // src before dst, src doesn't wrap, dst wraps
256 // 1 [C C _ _ _ A A B B]
257 // 2 [B B _ _ _ A A B B]
258 // 3 [B B _ _ _ A A A A]
261 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
262 self.copy(dst, src, dst_pre_wrap_len);
264 (false, true, false) => {
265 // dst before src, src wraps, dst doesn't wrap
268 // 1 [C C _ _ _ A A B B]
269 // 2 [C C _ _ _ B B B B]
270 // 3 [C C _ _ _ B B C C]
273 self.copy(dst, src, src_pre_wrap_len);
274 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
276 (true, true, false) => {
277 // src before dst, src wraps, dst doesn't wrap
280 // 1 [A A B B _ _ _ C C]
281 // 2 [A A A A _ _ _ C C]
282 // 3 [C C A A _ _ _ C C]
285 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
286 self.copy(dst, src, src_pre_wrap_len);
288 (false, true, true) => {
289 // dst before src, src wraps, dst wraps
292 // 1 [A B C D _ E F G H]
293 // 2 [A B C D _ E G H H]
294 // 3 [A B C D _ E G H A]
295 // 4 [B C C D _ E G H A]
298 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
299 let delta = dst_pre_wrap_len - src_pre_wrap_len;
300 self.copy(dst, src, src_pre_wrap_len);
301 self.copy(dst + src_pre_wrap_len, 0, delta);
302 self.copy(0, delta, len - dst_pre_wrap_len);
304 (true, true, true) => {
305 // src before dst, src wraps, dst wraps
308 // 1 [A B C D _ E F G H]
309 // 2 [A A B D _ E F G H]
310 // 3 [H A B D _ E F G H]
311 // 4 [H A B D _ E F F G]
314 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
315 let delta = src_pre_wrap_len - dst_pre_wrap_len;
316 self.copy(delta, 0, len - src_pre_wrap_len);
317 self.copy(0, self.cap() - delta, delta);
318 self.copy(dst, src, dst_pre_wrap_len);
323 /// Frobs the head and tail sections around to handle the fact that we
324 /// just reallocated. Unsafe because it trusts old_cap.
326 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
327 let new_cap = self.cap();
329 // Move the shortest contiguous section of the ring buffer
331 // [o o o o o o o . ]
333 // A [o o o o o o o . . . . . . . . . ]
335 // [o o . o o o o o ]
337 // B [. . . o o o o o o o . . . . . . ]
339 // [o o o o o . o o ]
341 // C [o o o o o . . . . . . . . . o o ]
343 if self.tail <= self.head {
346 } else if self.head < old_cap - self.tail {
348 self.copy_nonoverlapping(old_cap, 0, self.head);
349 self.head += old_cap;
350 debug_assert!(self.head > self.tail);
353 let new_tail = new_cap - (old_cap - self.tail);
354 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
355 self.tail = new_tail;
356 debug_assert!(self.head < self.tail);
358 debug_assert!(self.head < self.cap());
359 debug_assert!(self.tail < self.cap());
360 debug_assert!(self.cap().count_ones() == 1);
364 impl<T> VecDeque<T> {
365 /// Creates an empty `VecDeque`.
370 /// use std::collections::VecDeque;
372 /// let vector: VecDeque<u32> = VecDeque::new();
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn new() -> VecDeque<T> {
376 VecDeque::with_capacity(INITIAL_CAPACITY)
379 /// Creates an empty `VecDeque` with space for at least `n` elements.
384 /// use std::collections::VecDeque;
386 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn with_capacity(n: usize) -> VecDeque<T> {
390 // +1 since the ringbuffer always leaves one space empty
391 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
392 assert!(cap > n, "capacity overflow");
397 buf: RawVec::with_capacity(cap),
401 /// Retrieves an element in the `VecDeque` by index.
403 /// Element at index 0 is the front of the queue.
408 /// use std::collections::VecDeque;
410 /// let mut buf = VecDeque::new();
411 /// buf.push_back(3);
412 /// buf.push_back(4);
413 /// buf.push_back(5);
414 /// assert_eq!(buf.get(1), Some(&4));
416 #[stable(feature = "rust1", since = "1.0.0")]
417 pub fn get(&self, index: usize) -> Option<&T> {
418 if index < self.len() {
419 let idx = self.wrap_add(self.tail, index);
420 unsafe { Some(&*self.ptr().offset(idx as isize)) }
426 /// Retrieves an element in the `VecDeque` mutably by index.
428 /// Element at index 0 is the front of the queue.
433 /// use std::collections::VecDeque;
435 /// let mut buf = VecDeque::new();
436 /// buf.push_back(3);
437 /// buf.push_back(4);
438 /// buf.push_back(5);
439 /// if let Some(elem) = buf.get_mut(1) {
443 /// assert_eq!(buf[1], 7);
445 #[stable(feature = "rust1", since = "1.0.0")]
446 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
447 if index < self.len() {
448 let idx = self.wrap_add(self.tail, index);
449 unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
455 /// Swaps elements at indices `i` and `j`.
457 /// `i` and `j` may be equal.
459 /// Fails if there is no element with either index.
461 /// Element at index 0 is the front of the queue.
466 /// use std::collections::VecDeque;
468 /// let mut buf = VecDeque::new();
469 /// buf.push_back(3);
470 /// buf.push_back(4);
471 /// buf.push_back(5);
473 /// assert_eq!(buf[0], 5);
474 /// assert_eq!(buf[2], 3);
476 #[stable(feature = "rust1", since = "1.0.0")]
477 pub fn swap(&mut self, i: usize, j: usize) {
478 assert!(i < self.len());
479 assert!(j < self.len());
480 let ri = self.wrap_add(self.tail, i);
481 let rj = self.wrap_add(self.tail, j);
483 ptr::swap(self.ptr().offset(ri as isize),
484 self.ptr().offset(rj as isize))
488 /// Returns the number of elements the `VecDeque` can hold without
494 /// use std::collections::VecDeque;
496 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
497 /// assert!(buf.capacity() >= 10);
500 #[stable(feature = "rust1", since = "1.0.0")]
501 pub fn capacity(&self) -> usize {
505 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
506 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
508 /// Note that the allocator may give the collection more space than it requests. Therefore
509 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
510 /// insertions are expected.
514 /// Panics if the new capacity overflows `usize`.
519 /// use std::collections::VecDeque;
521 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
522 /// buf.reserve_exact(10);
523 /// assert!(buf.capacity() >= 11);
525 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn reserve_exact(&mut self, additional: usize) {
527 self.reserve(additional);
530 /// Reserves capacity for at least `additional` more elements to be inserted in the given
531 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
535 /// Panics if the new capacity overflows `usize`.
540 /// use std::collections::VecDeque;
542 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
544 /// assert!(buf.capacity() >= 11);
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn reserve(&mut self, additional: usize) {
548 let old_cap = self.cap();
549 let used_cap = self.len() + 1;
550 let new_cap = used_cap.checked_add(additional)
551 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
552 .expect("capacity overflow");
554 if new_cap > self.capacity() {
555 self.buf.reserve_exact(used_cap, new_cap - used_cap);
557 self.handle_cap_increase(old_cap);
562 /// Shrinks the capacity of the `VecDeque` as much as possible.
564 /// It will drop down as close as possible to the length but the allocator may still inform the
565 /// `VecDeque` that there is space for a few more elements.
570 /// use std::collections::VecDeque;
572 /// let mut buf = VecDeque::with_capacity(15);
573 /// buf.extend(0..4);
574 /// assert_eq!(buf.capacity(), 15);
575 /// buf.shrink_to_fit();
576 /// assert!(buf.capacity() >= 4);
578 #[stable(feature = "deque_extras_15", since = "1.5.0")]
579 pub fn shrink_to_fit(&mut self) {
580 // +1 since the ringbuffer always leaves one space empty
581 // len + 1 can't overflow for an existing, well-formed ringbuffer.
582 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
583 if target_cap < self.cap() {
584 // There are three cases of interest:
585 // All elements are out of desired bounds
586 // Elements are contiguous, and head is out of desired bounds
587 // Elements are discontiguous, and tail is out of desired bounds
589 // At all other times, element positions are unaffected.
591 // Indicates that elements at the head should be moved.
592 let head_outside = self.head == 0 || self.head >= target_cap;
593 // Move elements from out of desired bounds (positions after target_cap)
594 if self.tail >= target_cap && head_outside {
596 // [. . . . . . . . o o o o o o o . ]
598 // [o o o o o o o . ]
600 self.copy_nonoverlapping(0, self.tail, self.len());
602 self.head = self.len();
604 } else if self.tail != 0 && self.tail < target_cap && head_outside {
606 // [. . . o o o o o o o . . . . . . ]
608 // [o o . o o o o o ]
609 let len = self.wrap_sub(self.head, target_cap);
611 self.copy_nonoverlapping(0, target_cap, len);
614 debug_assert!(self.head < self.tail);
615 } else if self.tail >= target_cap {
617 // [o o o o o . . . . . . . . . o o ]
619 // [o o o o o . o o ]
620 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
621 let len = self.cap() - self.tail;
622 let new_tail = target_cap - len;
624 self.copy_nonoverlapping(new_tail, self.tail, len);
626 self.tail = new_tail;
627 debug_assert!(self.head < self.tail);
630 self.buf.shrink_to_fit(target_cap);
632 debug_assert!(self.head < self.cap());
633 debug_assert!(self.tail < self.cap());
634 debug_assert!(self.cap().count_ones() == 1);
638 /// Shortens a `VecDeque`, dropping excess elements from the back.
640 /// If `len` is greater than the `VecDeque`'s current length, this has no
646 /// #![feature(deque_extras)]
648 /// use std::collections::VecDeque;
650 /// let mut buf = VecDeque::new();
651 /// buf.push_back(5);
652 /// buf.push_back(10);
653 /// buf.push_back(15);
655 /// assert_eq!(buf.len(), 1);
656 /// assert_eq!(Some(&5), buf.get(0));
658 #[unstable(feature = "deque_extras",
659 reason = "matches collection reform specification; waiting on panic semantics",
661 pub fn truncate(&mut self, len: usize) {
662 for _ in len..self.len() {
667 /// Returns a front-to-back iterator.
672 /// use std::collections::VecDeque;
674 /// let mut buf = VecDeque::new();
675 /// buf.push_back(5);
676 /// buf.push_back(3);
677 /// buf.push_back(4);
678 /// let b: &[_] = &[&5, &3, &4];
679 /// let c: Vec<&i32> = buf.iter().collect();
680 /// assert_eq!(&c[..], b);
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn iter(&self) -> Iter<T> {
687 ring: unsafe { self.buffer_as_slice() },
691 /// Returns a front-to-back iterator that returns mutable references.
696 /// use std::collections::VecDeque;
698 /// let mut buf = VecDeque::new();
699 /// buf.push_back(5);
700 /// buf.push_back(3);
701 /// buf.push_back(4);
702 /// for num in buf.iter_mut() {
705 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
706 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
708 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn iter_mut(&mut self) -> IterMut<T> {
713 ring: unsafe { self.buffer_as_mut_slice() },
717 /// Returns a pair of slices which contain, in order, the contents of the
723 /// use std::collections::VecDeque;
725 /// let mut vector = VecDeque::new();
727 /// vector.push_back(0);
728 /// vector.push_back(1);
729 /// vector.push_back(2);
731 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
733 /// vector.push_front(10);
734 /// vector.push_front(9);
736 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
739 #[stable(feature = "deque_extras_15", since = "1.5.0")]
740 pub fn as_slices(&self) -> (&[T], &[T]) {
742 let buf = self.buffer_as_slice();
743 RingSlices::ring_slices(buf, self.head, self.tail)
747 /// Returns a pair of slices which contain, in order, the contents of the
753 /// use std::collections::VecDeque;
755 /// let mut vector = VecDeque::new();
757 /// vector.push_back(0);
758 /// vector.push_back(1);
760 /// vector.push_front(10);
761 /// vector.push_front(9);
763 /// vector.as_mut_slices().0[0] = 42;
764 /// vector.as_mut_slices().1[0] = 24;
765 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
768 #[stable(feature = "deque_extras_15", since = "1.5.0")]
769 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
771 let head = self.head;
772 let tail = self.tail;
773 let buf = self.buffer_as_mut_slice();
774 RingSlices::ring_slices(buf, head, tail)
778 /// Returns the number of elements in the `VecDeque`.
783 /// use std::collections::VecDeque;
785 /// let mut v = VecDeque::new();
786 /// assert_eq!(v.len(), 0);
788 /// assert_eq!(v.len(), 1);
790 #[stable(feature = "rust1", since = "1.0.0")]
791 pub fn len(&self) -> usize {
792 count(self.tail, self.head, self.cap())
795 /// Returns true if the buffer contains no elements
800 /// use std::collections::VecDeque;
802 /// let mut v = VecDeque::new();
803 /// assert!(v.is_empty());
805 /// assert!(!v.is_empty());
807 #[stable(feature = "rust1", since = "1.0.0")]
808 pub fn is_empty(&self) -> bool {
809 self.tail == self.head
812 /// Create a draining iterator that removes the specified range in the
813 /// `VecDeque` and yields the removed items.
815 /// Note 1: The element range is removed even if the iterator is not
816 /// consumed until the end.
818 /// Note 2: It is unspecified how many elements are removed from the deque,
819 /// if the `Drain` value is not dropped, but the borrow it holds expires
820 /// (eg. due to mem::forget).
824 /// Panics if the starting point is greater than the end point or if
825 /// the end point is greater than the length of the vector.
830 /// use std::collections::VecDeque;
832 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
833 /// assert_eq!(vec![3].into_iter().collect::<VecDeque<_>>(), v.drain(2..).collect());
834 /// assert_eq!(vec![1, 2].into_iter().collect::<VecDeque<_>>(), v);
836 /// // A full range clears all contents
838 /// assert!(v.is_empty());
841 #[stable(feature = "drain", since = "1.6.0")]
842 pub fn drain<R>(&mut self, range: R) -> Drain<T>
843 where R: RangeArgument<usize>
847 // When the Drain is first created, the source deque is shortened to
848 // make sure no uninitialized or moved-from elements are accessible at
849 // all if the Drain's destructor never gets to run.
851 // Drain will ptr::read out the values to remove.
852 // When finished, the remaining data will be copied back to cover the hole,
853 // and the head/tail values will be restored correctly.
855 let len = self.len();
856 let start = match range.start() {
858 Excluded(&n) => n + 1,
861 let end = match range.end() {
862 Included(&n) => n + 1,
866 assert!(start <= end, "drain lower bound was too large");
867 assert!(end <= len, "drain upper bound was too large");
869 // The deque's elements are parted into three segments:
870 // * self.tail -> drain_tail
871 // * drain_tail -> drain_head
872 // * drain_head -> self.head
874 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
876 // We store drain_tail as self.head, and drain_head and self.head as
877 // after_tail and after_head respectively on the Drain. This also
878 // truncates the effective array such that if the Drain is leaked, we
879 // have forgotten about the potentially moved values after the start of
883 // [. . . o o x x o o . . .]
885 let drain_tail = self.wrap_add(self.tail, start);
886 let drain_head = self.wrap_add(self.tail, end);
887 let head = self.head;
889 // "forget" about the values after the start of the drain until after
890 // the drain is complete and the Drain destructor is run.
891 self.head = drain_tail;
894 deque: unsafe { Shared::new(self as *mut _) },
895 after_tail: drain_head,
900 ring: unsafe { self.buffer_as_mut_slice() },
905 /// Clears the buffer, removing all values.
910 /// use std::collections::VecDeque;
912 /// let mut v = VecDeque::new();
915 /// assert!(v.is_empty());
917 #[stable(feature = "rust1", since = "1.0.0")]
919 pub fn clear(&mut self) {
923 /// Returns `true` if the `VecDeque` contains an element equal to the
929 /// use std::collections::VecDeque;
931 /// let mut vector: VecDeque<u32> = VecDeque::new();
933 /// vector.push_back(0);
934 /// vector.push_back(1);
936 /// assert_eq!(vector.contains(&1), true);
937 /// assert_eq!(vector.contains(&10), false);
939 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
940 pub fn contains(&self, x: &T) -> bool
941 where T: PartialEq<T>
943 let (a, b) = self.as_slices();
944 a.contains(x) || b.contains(x)
947 /// Provides a reference to the front element, or `None` if the sequence is
953 /// use std::collections::VecDeque;
955 /// let mut d = VecDeque::new();
956 /// assert_eq!(d.front(), None);
960 /// assert_eq!(d.front(), Some(&1));
962 #[stable(feature = "rust1", since = "1.0.0")]
963 pub fn front(&self) -> Option<&T> {
964 if !self.is_empty() {
971 /// Provides a mutable reference to the front element, or `None` if the
972 /// sequence is empty.
977 /// use std::collections::VecDeque;
979 /// let mut d = VecDeque::new();
980 /// assert_eq!(d.front_mut(), None);
984 /// match d.front_mut() {
985 /// Some(x) => *x = 9,
988 /// assert_eq!(d.front(), Some(&9));
990 #[stable(feature = "rust1", since = "1.0.0")]
991 pub fn front_mut(&mut self) -> Option<&mut T> {
992 if !self.is_empty() {
999 /// Provides a reference to the back element, or `None` if the sequence is
1005 /// use std::collections::VecDeque;
1007 /// let mut d = VecDeque::new();
1008 /// assert_eq!(d.back(), None);
1012 /// assert_eq!(d.back(), Some(&2));
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 pub fn back(&self) -> Option<&T> {
1016 if !self.is_empty() {
1017 Some(&self[self.len() - 1])
1023 /// Provides a mutable reference to the back element, or `None` if the
1024 /// sequence is empty.
1029 /// use std::collections::VecDeque;
1031 /// let mut d = VecDeque::new();
1032 /// assert_eq!(d.back(), None);
1036 /// match d.back_mut() {
1037 /// Some(x) => *x = 9,
1040 /// assert_eq!(d.back(), Some(&9));
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn back_mut(&mut self) -> Option<&mut T> {
1044 let len = self.len();
1045 if !self.is_empty() {
1046 Some(&mut self[len - 1])
1052 /// Removes the first element and returns it, or `None` if the sequence is
1058 /// use std::collections::VecDeque;
1060 /// let mut d = VecDeque::new();
1064 /// assert_eq!(d.pop_front(), Some(1));
1065 /// assert_eq!(d.pop_front(), Some(2));
1066 /// assert_eq!(d.pop_front(), None);
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 pub fn pop_front(&mut self) -> Option<T> {
1070 if self.is_empty() {
1073 let tail = self.tail;
1074 self.tail = self.wrap_add(self.tail, 1);
1075 unsafe { Some(self.buffer_read(tail)) }
1079 /// Inserts an element first in the sequence.
1084 /// use std::collections::VecDeque;
1086 /// let mut d = VecDeque::new();
1087 /// d.push_front(1);
1088 /// d.push_front(2);
1089 /// assert_eq!(d.front(), Some(&2));
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 pub fn push_front(&mut self, value: T) {
1094 let old_cap = self.cap();
1097 self.handle_cap_increase(old_cap);
1099 debug_assert!(!self.is_full());
1102 self.tail = self.wrap_sub(self.tail, 1);
1103 let tail = self.tail;
1105 self.buffer_write(tail, value);
1109 /// Appends an element to the back of a buffer
1114 /// use std::collections::VecDeque;
1116 /// let mut buf = VecDeque::new();
1117 /// buf.push_back(1);
1118 /// buf.push_back(3);
1119 /// assert_eq!(3, *buf.back().unwrap());
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 pub fn push_back(&mut self, value: T) {
1124 let old_cap = self.cap();
1127 self.handle_cap_increase(old_cap);
1129 debug_assert!(!self.is_full());
1132 let head = self.head;
1133 self.head = self.wrap_add(self.head, 1);
1134 unsafe { self.buffer_write(head, value) }
1137 /// Removes the last element from a buffer and returns it, or `None` if
1143 /// use std::collections::VecDeque;
1145 /// let mut buf = VecDeque::new();
1146 /// assert_eq!(buf.pop_back(), None);
1147 /// buf.push_back(1);
1148 /// buf.push_back(3);
1149 /// assert_eq!(buf.pop_back(), Some(3));
1151 #[stable(feature = "rust1", since = "1.0.0")]
1152 pub fn pop_back(&mut self) -> Option<T> {
1153 if self.is_empty() {
1156 self.head = self.wrap_sub(self.head, 1);
1157 let head = self.head;
1158 unsafe { Some(self.buffer_read(head)) }
1163 fn is_contiguous(&self) -> bool {
1164 self.tail <= self.head
1167 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1170 /// This does not preserve ordering, but is O(1).
1172 /// Returns `None` if `index` is out of bounds.
1174 /// Element at index 0 is the front of the queue.
1179 /// use std::collections::VecDeque;
1181 /// let mut buf = VecDeque::new();
1182 /// assert_eq!(buf.swap_remove_back(0), None);
1183 /// buf.push_back(1);
1184 /// buf.push_back(2);
1185 /// buf.push_back(3);
1187 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1188 /// assert_eq!(buf.len(), 2);
1189 /// assert_eq!(buf[0], 3);
1190 /// assert_eq!(buf[1], 2);
1192 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1193 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1194 let length = self.len();
1195 if length > 0 && index < length - 1 {
1196 self.swap(index, length - 1);
1197 } else if index >= length {
1203 /// Removes an element from anywhere in the `VecDeque` and returns it,
1204 /// replacing it with the first element.
1206 /// This does not preserve ordering, but is O(1).
1208 /// Returns `None` if `index` is out of bounds.
1210 /// Element at index 0 is the front of the queue.
1215 /// use std::collections::VecDeque;
1217 /// let mut buf = VecDeque::new();
1218 /// assert_eq!(buf.swap_remove_front(0), None);
1219 /// buf.push_back(1);
1220 /// buf.push_back(2);
1221 /// buf.push_back(3);
1223 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1224 /// assert_eq!(buf.len(), 2);
1225 /// assert_eq!(buf[0], 2);
1226 /// assert_eq!(buf[1], 1);
1228 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1229 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1230 let length = self.len();
1231 if length > 0 && index < length && index != 0 {
1232 self.swap(index, 0);
1233 } else if index >= length {
1239 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1240 /// greater than or equal to `index` towards the back.
1242 /// Element at index 0 is the front of the queue.
1246 /// Panics if `index` is greater than `VecDeque`'s length
1251 /// use std::collections::VecDeque;
1253 /// let mut vec_deque = VecDeque::new();
1254 /// vec_deque.push_back('a');
1255 /// vec_deque.push_back('b');
1256 /// vec_deque.push_back('c');
1258 /// vec_deque.insert(1, 'd');
1260 /// let vec = vec_deque.into_iter().collect::<Vec<_>>();
1261 /// assert_eq!(vec, ['a', 'd', 'b', 'c']);
1263 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1264 pub fn insert(&mut self, index: usize, value: T) {
1265 assert!(index <= self.len(), "index out of bounds");
1267 let old_cap = self.cap();
1270 self.handle_cap_increase(old_cap);
1272 debug_assert!(!self.is_full());
1275 // Move the least number of elements in the ring buffer and insert
1278 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1280 // There are three main cases:
1281 // Elements are contiguous
1282 // - special case when tail is 0
1283 // Elements are discontiguous and the insert is in the tail section
1284 // Elements are discontiguous and the insert is in the head section
1286 // For each of those there are two more cases:
1287 // Insert is closer to tail
1288 // Insert is closer to head
1290 // Key: H - self.head
1292 // o - Valid element
1293 // I - Insertion element
1294 // A - The element that should be after the insertion point
1295 // M - Indicates element was moved
1297 let idx = self.wrap_add(self.tail, index);
1299 let distance_to_tail = index;
1300 let distance_to_head = self.len() - index;
1302 let contiguous = self.is_contiguous();
1304 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1305 (true, true, _) if index == 0 => {
1310 // [A o o o o o o . . . . . . . . .]
1313 // [A o o o o o o o . . . . . I]
1316 self.tail = self.wrap_sub(self.tail, 1);
1318 (true, true, _) => {
1320 // contiguous, insert closer to tail:
1323 // [. . . o o A o o o o . . . . . .]
1326 // [. . o o I A o o o o . . . . . .]
1329 // contiguous, insert closer to tail and tail is 0:
1333 // [o o A o o o o . . . . . . . . .]
1336 // [o I A o o o o o . . . . . . . o]
1339 let new_tail = self.wrap_sub(self.tail, 1);
1341 self.copy(new_tail, self.tail, 1);
1342 // Already moved the tail, so we only copy `index - 1` elements.
1343 self.copy(self.tail, self.tail + 1, index - 1);
1345 self.tail = new_tail;
1348 (true, false, _) => {
1350 // contiguous, insert closer to head:
1353 // [. . . o o o o A o o . . . . . .]
1356 // [. . . o o o o I A o o . . . . .]
1359 self.copy(idx + 1, idx, self.head - idx);
1360 self.head = self.wrap_add(self.head, 1);
1363 (false, true, true) => {
1365 // discontiguous, insert closer to tail, tail section:
1368 // [o o o o o o . . . . . o o A o o]
1371 // [o o o o o o . . . . o o I A o o]
1374 self.copy(self.tail - 1, self.tail, index);
1378 (false, false, true) => {
1380 // discontiguous, insert closer to head, tail section:
1383 // [o o . . . . . . . o o o o o A o]
1386 // [o o o . . . . . . o o o o o I A]
1389 // copy elements up to new head
1390 self.copy(1, 0, self.head);
1392 // copy last element into empty spot at bottom of buffer
1393 self.copy(0, self.cap() - 1, 1);
1395 // move elements from idx to end forward not including ^ element
1396 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1401 (false, true, false) if idx == 0 => {
1403 // discontiguous, insert is closer to tail, head section,
1404 // and is at index zero in the internal buffer:
1407 // [A o o o o o o o o o . . . o o o]
1410 // [A o o o o o o o o o . . o o o I]
1413 // copy elements up to new tail
1414 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1416 // copy last element into empty spot at bottom of buffer
1417 self.copy(self.cap() - 1, 0, 1);
1422 (false, true, false) => {
1424 // discontiguous, insert closer to tail, head section:
1427 // [o o o A o o o o o o . . . o o o]
1430 // [o o I A o o o o o o . . o o o o]
1433 // copy elements up to new tail
1434 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1436 // copy last element into empty spot at bottom of buffer
1437 self.copy(self.cap() - 1, 0, 1);
1439 // move elements from idx-1 to end forward not including ^ element
1440 self.copy(0, 1, idx - 1);
1445 (false, false, false) => {
1447 // discontiguous, insert closer to head, head section:
1450 // [o o o o A o o . . . . . . o o o]
1453 // [o o o o I A o o . . . . . o o o]
1456 self.copy(idx + 1, idx, self.head - idx);
1462 // tail might've been changed so we need to recalculate
1463 let new_idx = self.wrap_add(self.tail, index);
1465 self.buffer_write(new_idx, value);
1469 /// Removes and returns the element at `index` from the `VecDeque`.
1470 /// Whichever end is closer to the removal point will be moved to make
1471 /// room, and all the affected elements will be moved to new positions.
1472 /// Returns `None` if `index` is out of bounds.
1474 /// Element at index 0 is the front of the queue.
1479 /// use std::collections::VecDeque;
1481 /// let mut buf = VecDeque::new();
1482 /// buf.push_back(1);
1483 /// buf.push_back(2);
1484 /// buf.push_back(3);
1486 /// assert_eq!(buf.remove(1), Some(2));
1487 /// assert_eq!(buf.get(1), Some(&3));
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 pub fn remove(&mut self, index: usize) -> Option<T> {
1491 if self.is_empty() || self.len() <= index {
1495 // There are three main cases:
1496 // Elements are contiguous
1497 // Elements are discontiguous and the removal is in the tail section
1498 // Elements are discontiguous and the removal is in the head section
1499 // - special case when elements are technically contiguous,
1500 // but self.head = 0
1502 // For each of those there are two more cases:
1503 // Insert is closer to tail
1504 // Insert is closer to head
1506 // Key: H - self.head
1508 // o - Valid element
1509 // x - Element marked for removal
1510 // R - Indicates element that is being removed
1511 // M - Indicates element was moved
1513 let idx = self.wrap_add(self.tail, index);
1515 let elem = unsafe { Some(self.buffer_read(idx)) };
1517 let distance_to_tail = index;
1518 let distance_to_head = self.len() - index;
1520 let contiguous = self.is_contiguous();
1522 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1523 (true, true, _) => {
1525 // contiguous, remove closer to tail:
1528 // [. . . o o x o o o o . . . . . .]
1531 // [. . . . o o o o o o . . . . . .]
1534 self.copy(self.tail + 1, self.tail, index);
1538 (true, false, _) => {
1540 // contiguous, remove closer to head:
1543 // [. . . o o o o x o o . . . . . .]
1546 // [. . . o o o o o o . . . . . . .]
1549 self.copy(idx, idx + 1, self.head - idx - 1);
1553 (false, true, true) => {
1555 // discontiguous, remove closer to tail, tail section:
1558 // [o o o o o o . . . . . o o x o o]
1561 // [o o o o o o . . . . . . o o o o]
1564 self.copy(self.tail + 1, self.tail, index);
1565 self.tail = self.wrap_add(self.tail, 1);
1568 (false, false, false) => {
1570 // discontiguous, remove closer to head, head section:
1573 // [o o o o x o o . . . . . . o o o]
1576 // [o o o o o o . . . . . . . o o o]
1579 self.copy(idx, idx + 1, self.head - idx - 1);
1583 (false, false, true) => {
1585 // discontiguous, remove closer to head, tail section:
1588 // [o o o . . . . . . o o o o o x o]
1591 // [o o . . . . . . . o o o o o o o]
1594 // or quasi-discontiguous, remove next to head, tail section:
1597 // [. . . . . . . . . o o o o o x o]
1600 // [. . . . . . . . . o o o o o o .]
1603 // draw in elements in the tail section
1604 self.copy(idx, idx + 1, self.cap() - idx - 1);
1606 // Prevents underflow.
1608 // copy first element into empty spot
1609 self.copy(self.cap() - 1, 0, 1);
1611 // move elements in the head section backwards
1612 self.copy(0, 1, self.head - 1);
1615 self.head = self.wrap_sub(self.head, 1);
1618 (false, true, false) => {
1620 // discontiguous, remove closer to tail, head section:
1623 // [o o x o o o o o o o . . . o o o]
1626 // [o o o o o o o o o o . . . . o o]
1629 // draw in elements up to idx
1630 self.copy(1, 0, idx);
1632 // copy last element into empty spot
1633 self.copy(0, self.cap() - 1, 1);
1635 // move elements from tail to end forward, excluding the last one
1636 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1638 self.tail = self.wrap_add(self.tail, 1);
1646 /// Splits the collection into two at the given index.
1648 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1649 /// and the returned `Self` contains elements `[at, len)`.
1651 /// Note that the capacity of `self` does not change.
1653 /// Element at index 0 is the front of the queue.
1657 /// Panics if `at > len`
1662 /// use std::collections::VecDeque;
1664 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1665 /// let buf2 = buf.split_off(1);
1666 /// // buf = [1], buf2 = [2, 3]
1667 /// assert_eq!(buf.len(), 1);
1668 /// assert_eq!(buf2.len(), 2);
1671 #[stable(feature = "split_off", since = "1.4.0")]
1672 pub fn split_off(&mut self, at: usize) -> Self {
1673 let len = self.len();
1674 assert!(at <= len, "`at` out of bounds");
1676 let other_len = len - at;
1677 let mut other = VecDeque::with_capacity(other_len);
1680 let (first_half, second_half) = self.as_slices();
1682 let first_len = first_half.len();
1683 let second_len = second_half.len();
1685 // `at` lies in the first half.
1686 let amount_in_first = first_len - at;
1688 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1692 // just take all of the second half.
1693 ptr::copy_nonoverlapping(second_half.as_ptr(),
1694 other.ptr().offset(amount_in_first as isize),
1697 // `at` lies in the second half, need to factor in the elements we skipped
1698 // in the first half.
1699 let offset = at - first_len;
1700 let amount_in_second = second_len - offset;
1701 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1707 // Cleanup where the ends of the buffers are
1708 self.head = self.wrap_sub(self.head, other_len);
1709 other.head = other.wrap_index(other_len);
1714 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1718 /// Panics if the new number of elements in self overflows a `usize`.
1723 /// use std::collections::VecDeque;
1725 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1726 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
1727 /// buf.append(&mut buf2);
1728 /// assert_eq!(buf.len(), 6);
1729 /// assert_eq!(buf2.len(), 0);
1732 #[stable(feature = "append", since = "1.4.0")]
1733 pub fn append(&mut self, other: &mut Self) {
1735 self.extend(other.drain(..));
1738 /// Retains only the elements specified by the predicate.
1740 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1741 /// This method operates in place and preserves the order of the retained
1747 /// use std::collections::VecDeque;
1749 /// let mut buf = VecDeque::new();
1750 /// buf.extend(1..5);
1751 /// buf.retain(|&x| x%2 == 0);
1753 /// let v: Vec<_> = buf.into_iter().collect();
1754 /// assert_eq!(&v[..], &[2, 4]);
1756 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1757 pub fn retain<F>(&mut self, mut f: F)
1758 where F: FnMut(&T) -> bool
1760 let len = self.len();
1766 self.swap(i - del, i);
1770 self.truncate(len - del);
1775 impl<T: Clone> VecDeque<T> {
1776 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1777 /// either by removing excess elements or by appending copies of a value to the back.
1782 /// #![feature(deque_extras)]
1784 /// use std::collections::VecDeque;
1786 /// let mut buf = VecDeque::new();
1787 /// buf.push_back(5);
1788 /// buf.push_back(10);
1789 /// buf.push_back(15);
1790 /// buf.resize(2, 0);
1791 /// buf.resize(6, 20);
1792 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
1793 /// assert_eq!(a, b);
1796 #[unstable(feature = "deque_extras",
1797 reason = "matches collection reform specification; waiting on panic semantics",
1799 pub fn resize(&mut self, new_len: usize, value: T) {
1800 let len = self.len();
1803 self.extend(repeat(value).take(new_len - len))
1805 self.truncate(new_len);
1810 /// Returns the index in the underlying buffer for a given logical element index.
1812 fn wrap_index(index: usize, size: usize) -> usize {
1813 // size is always a power of 2
1814 debug_assert!(size.is_power_of_two());
1818 /// Returns the two slices that cover the VecDeque's valid range
1819 trait RingSlices: Sized {
1820 fn slice(self, from: usize, to: usize) -> Self;
1821 fn split_at(self, i: usize) -> (Self, Self);
1823 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
1824 let contiguous = tail <= head;
1826 let (empty, buf) = buf.split_at(0);
1827 (buf.slice(tail, head), empty)
1829 let (mid, right) = buf.split_at(tail);
1830 let (left, _) = mid.split_at(head);
1836 impl<'a, T> RingSlices for &'a [T] {
1837 fn slice(self, from: usize, to: usize) -> Self {
1840 fn split_at(self, i: usize) -> (Self, Self) {
1845 impl<'a, T> RingSlices for &'a mut [T] {
1846 fn slice(self, from: usize, to: usize) -> Self {
1849 fn split_at(self, i: usize) -> (Self, Self) {
1850 (*self).split_at_mut(i)
1854 /// Calculate the number of elements left to be read in the buffer
1856 fn count(tail: usize, head: usize, size: usize) -> usize {
1857 // size is always a power of 2
1858 (head.wrapping_sub(tail)) & (size - 1)
1861 /// `VecDeque` iterator.
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 pub struct Iter<'a, T: 'a> {
1869 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1870 #[stable(feature = "rust1", since = "1.0.0")]
1871 impl<'a, T> Clone for Iter<'a, T> {
1872 fn clone(&self) -> Iter<'a, T> {
1881 #[stable(feature = "rust1", since = "1.0.0")]
1882 impl<'a, T> Iterator for Iter<'a, T> {
1886 fn next(&mut self) -> Option<&'a T> {
1887 if self.tail == self.head {
1890 let tail = self.tail;
1891 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1892 unsafe { Some(self.ring.get_unchecked(tail)) }
1896 fn size_hint(&self) -> (usize, Option<usize>) {
1897 let len = count(self.tail, self.head, self.ring.len());
1901 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
1902 where F: FnMut(Acc, Self::Item) -> Acc
1904 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
1905 accum = front.iter().fold(accum, &mut f);
1906 back.iter().fold(accum, &mut f)
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1913 fn next_back(&mut self) -> Option<&'a T> {
1914 if self.tail == self.head {
1917 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1918 unsafe { Some(self.ring.get_unchecked(self.head)) }
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1924 fn is_empty(&self) -> bool {
1925 self.head == self.tail
1929 #[unstable(feature = "fused", issue = "35602")]
1930 impl<'a, T> FusedIterator for Iter<'a, T> {}
1933 /// `VecDeque` mutable iterator.
1934 #[stable(feature = "rust1", since = "1.0.0")]
1935 pub struct IterMut<'a, T: 'a> {
1941 #[stable(feature = "rust1", since = "1.0.0")]
1942 impl<'a, T> Iterator for IterMut<'a, T> {
1943 type Item = &'a mut T;
1946 fn next(&mut self) -> Option<&'a mut T> {
1947 if self.tail == self.head {
1950 let tail = self.tail;
1951 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1954 let elem = self.ring.get_unchecked_mut(tail);
1955 Some(&mut *(elem as *mut _))
1960 fn size_hint(&self) -> (usize, Option<usize>) {
1961 let len = count(self.tail, self.head, self.ring.len());
1965 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
1966 where F: FnMut(Acc, Self::Item) -> Acc
1968 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
1969 accum = front.iter_mut().fold(accum, &mut f);
1970 back.iter_mut().fold(accum, &mut f)
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1977 fn next_back(&mut self) -> Option<&'a mut T> {
1978 if self.tail == self.head {
1981 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1984 let elem = self.ring.get_unchecked_mut(self.head);
1985 Some(&mut *(elem as *mut _))
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1992 fn is_empty(&self) -> bool {
1993 self.head == self.tail
1997 #[unstable(feature = "fused", issue = "35602")]
1998 impl<'a, T> FusedIterator for IterMut<'a, T> {}
2000 /// A by-value VecDeque iterator
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 pub struct IntoIter<T> {
2007 #[stable(feature = "rust1", since = "1.0.0")]
2008 impl<T> Iterator for IntoIter<T> {
2012 fn next(&mut self) -> Option<T> {
2013 self.inner.pop_front()
2017 fn size_hint(&self) -> (usize, Option<usize>) {
2018 let len = self.inner.len();
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 impl<T> DoubleEndedIterator for IntoIter<T> {
2026 fn next_back(&mut self) -> Option<T> {
2027 self.inner.pop_back()
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 impl<T> ExactSizeIterator for IntoIter<T> {
2033 fn is_empty(&self) -> bool {
2034 self.inner.is_empty()
2038 #[unstable(feature = "fused", issue = "35602")]
2039 impl<T> FusedIterator for IntoIter<T> {}
2041 /// A draining VecDeque iterator
2042 #[stable(feature = "drain", since = "1.6.0")]
2043 pub struct Drain<'a, T: 'a> {
2047 deque: Shared<VecDeque<T>>,
2050 #[stable(feature = "drain", since = "1.6.0")]
2051 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2052 #[stable(feature = "drain", since = "1.6.0")]
2053 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2055 #[stable(feature = "drain", since = "1.6.0")]
2056 impl<'a, T: 'a> Drop for Drain<'a, T> {
2057 fn drop(&mut self) {
2058 for _ in self.by_ref() {}
2060 let source_deque = unsafe { &mut **self.deque };
2062 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2065 // [. . . o o x x o o . . .]
2067 let orig_tail = source_deque.tail;
2068 let drain_tail = source_deque.head;
2069 let drain_head = self.after_tail;
2070 let orig_head = self.after_head;
2072 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2073 let head_len = count(drain_head, orig_head, source_deque.cap());
2075 // Restore the original head value
2076 source_deque.head = orig_head;
2078 match (tail_len, head_len) {
2080 source_deque.head = 0;
2081 source_deque.tail = 0;
2084 source_deque.tail = drain_head;
2087 source_deque.head = drain_tail;
2090 if tail_len <= head_len {
2091 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2092 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2094 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2095 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2102 #[stable(feature = "drain", since = "1.6.0")]
2103 impl<'a, T: 'a> Iterator for Drain<'a, T> {
2107 fn next(&mut self) -> Option<T> {
2108 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2112 fn size_hint(&self) -> (usize, Option<usize>) {
2113 self.iter.size_hint()
2117 #[stable(feature = "drain", since = "1.6.0")]
2118 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
2120 fn next_back(&mut self) -> Option<T> {
2121 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2125 #[stable(feature = "drain", since = "1.6.0")]
2126 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
2128 #[unstable(feature = "fused", issue = "35602")]
2129 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 impl<A: PartialEq> PartialEq for VecDeque<A> {
2133 fn eq(&self, other: &VecDeque<A>) -> bool {
2134 if self.len() != other.len() {
2137 let (sa, sb) = self.as_slices();
2138 let (oa, ob) = other.as_slices();
2139 if sa.len() == oa.len() {
2140 sa == oa && sb == ob
2141 } else if sa.len() < oa.len() {
2142 // Always divisible in three sections, for example:
2143 // self: [a b c|d e f]
2144 // other: [0 1 2 3|4 5]
2145 // front = 3, mid = 1,
2146 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2147 let front = sa.len();
2148 let mid = oa.len() - front;
2150 let (oa_front, oa_mid) = oa.split_at(front);
2151 let (sb_mid, sb_back) = sb.split_at(mid);
2152 debug_assert_eq!(sa.len(), oa_front.len());
2153 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2154 debug_assert_eq!(sb_back.len(), ob.len());
2155 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2157 let front = oa.len();
2158 let mid = sa.len() - front;
2160 let (sa_front, sa_mid) = sa.split_at(front);
2161 let (ob_mid, ob_back) = ob.split_at(mid);
2162 debug_assert_eq!(sa_front.len(), oa.len());
2163 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2164 debug_assert_eq!(sb.len(), ob_back.len());
2165 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2170 #[stable(feature = "rust1", since = "1.0.0")]
2171 impl<A: Eq> Eq for VecDeque<A> {}
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2175 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2176 self.iter().partial_cmp(other.iter())
2180 #[stable(feature = "rust1", since = "1.0.0")]
2181 impl<A: Ord> Ord for VecDeque<A> {
2183 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2184 self.iter().cmp(other.iter())
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 impl<A: Hash> Hash for VecDeque<A> {
2190 fn hash<H: Hasher>(&self, state: &mut H) {
2191 self.len().hash(state);
2192 let (a, b) = self.as_slices();
2193 Hash::hash_slice(a, state);
2194 Hash::hash_slice(b, state);
2198 #[stable(feature = "rust1", since = "1.0.0")]
2199 impl<A> Index<usize> for VecDeque<A> {
2203 fn index(&self, index: usize) -> &A {
2204 self.get(index).expect("Out of bounds access")
2208 #[stable(feature = "rust1", since = "1.0.0")]
2209 impl<A> IndexMut<usize> for VecDeque<A> {
2211 fn index_mut(&mut self, index: usize) -> &mut A {
2212 self.get_mut(index).expect("Out of bounds access")
2216 #[stable(feature = "rust1", since = "1.0.0")]
2217 impl<A> FromIterator<A> for VecDeque<A> {
2218 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2219 let iterator = iter.into_iter();
2220 let (lower, _) = iterator.size_hint();
2221 let mut deq = VecDeque::with_capacity(lower);
2222 deq.extend(iterator);
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 impl<T> IntoIterator for VecDeque<T> {
2230 type IntoIter = IntoIter<T>;
2232 /// Consumes the list into a front-to-back iterator yielding elements by
2234 fn into_iter(self) -> IntoIter<T> {
2235 IntoIter { inner: self }
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2242 type IntoIter = Iter<'a, T>;
2244 fn into_iter(self) -> Iter<'a, T> {
2249 #[stable(feature = "rust1", since = "1.0.0")]
2250 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2251 type Item = &'a mut T;
2252 type IntoIter = IterMut<'a, T>;
2254 fn into_iter(mut self) -> IterMut<'a, T> {
2259 #[stable(feature = "rust1", since = "1.0.0")]
2260 impl<A> Extend<A> for VecDeque<A> {
2261 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2263 self.push_back(elt);
2268 #[stable(feature = "extend_ref", since = "1.2.0")]
2269 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2270 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2271 self.extend(iter.into_iter().cloned());
2275 #[stable(feature = "rust1", since = "1.0.0")]
2276 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2277 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2278 f.debug_list().entries(self).finish()
2282 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2283 impl<T> From<Vec<T>> for VecDeque<T> {
2284 fn from(mut other: Vec<T>) -> Self {
2286 let other_buf = other.as_mut_ptr();
2287 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2288 let len = other.len();
2291 // We need to extend the buf if it's not a power of two, too small
2292 // or doesn't have at least one free space
2293 if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) ||
2294 (buf.cap() == len) {
2295 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2296 buf.reserve_exact(len, cap - len);
2308 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2309 impl<T> From<VecDeque<T>> for Vec<T> {
2310 fn from(other: VecDeque<T>) -> Self {
2312 let buf = other.buf.ptr();
2313 let len = other.len();
2314 let tail = other.tail;
2315 let head = other.head;
2316 let cap = other.cap();
2318 // Need to move the ring to the front of the buffer, as vec will expect this.
2319 if other.is_contiguous() {
2320 ptr::copy(buf.offset(tail as isize), buf, len);
2322 if (tail - head) >= cmp::min((cap - tail), head) {
2323 // There is enough free space in the centre for the shortest block so we can
2324 // do this in at most three copy moves.
2325 if (cap - tail) > head {
2326 // right hand block is the long one; move that enough for the left
2327 ptr::copy(buf.offset(tail as isize),
2328 buf.offset((tail - head) as isize),
2330 // copy left in the end
2331 ptr::copy(buf, buf.offset((cap - head) as isize), head);
2332 // shift the new thing to the start
2333 ptr::copy(buf.offset((tail - head) as isize), buf, len);
2335 // left hand block is the long one, we can do it in two!
2336 ptr::copy(buf, buf.offset((cap - tail) as isize), head);
2337 ptr::copy(buf.offset(tail as isize), buf, cap - tail);
2340 // Need to use N swaps to move the ring
2341 // We can use the space at the end of the ring as a temp store
2343 let mut left_edge: usize = 0;
2344 let mut right_edge: usize = tail;
2346 // The general problem looks like this
2347 // GHIJKLM...ABCDEF - before any swaps
2348 // ABCDEFM...GHIJKL - after 1 pass of swaps
2349 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2350 // - then restart the algorithm with a new (smaller) store
2351 // Sometimes the temp store is reached when the right edge is at the end
2352 // of the buffer - this means we've hit the right order with fewer swaps!
2355 // ABCDEF.. - after four only swaps we've finished
2357 while left_edge < len && right_edge != cap {
2358 let mut right_offset = 0;
2359 for i in left_edge..right_edge {
2360 right_offset = (i - left_edge) % (cap - right_edge);
2361 let src: isize = (right_edge + right_offset) as isize;
2362 ptr::swap(buf.offset(i as isize), buf.offset(src));
2364 let n_ops = right_edge - left_edge;
2366 right_edge += right_offset + 1;
2372 let out = Vec::from_raw_parts(buf, len, cap);
2383 use super::VecDeque;
2386 fn bench_push_back_100(b: &mut test::Bencher) {
2387 let mut deq = VecDeque::with_capacity(101);
2398 fn bench_push_front_100(b: &mut test::Bencher) {
2399 let mut deq = VecDeque::with_capacity(101);
2410 fn bench_pop_back_100(b: &mut test::Bencher) {
2411 let mut deq = VecDeque::<i32>::with_capacity(101);
2416 while !deq.is_empty() {
2417 test::black_box(deq.pop_back());
2423 fn bench_pop_front_100(b: &mut test::Bencher) {
2424 let mut deq = VecDeque::<i32>::with_capacity(101);
2429 while !deq.is_empty() {
2430 test::black_box(deq.pop_front());
2436 fn test_swap_front_back_remove() {
2437 fn test(back: bool) {
2438 // This test checks that every single combination of tail position and length is tested.
2439 // Capacity 15 should be large enough to cover every case.
2440 let mut tester = VecDeque::with_capacity(15);
2441 let usable_cap = tester.capacity();
2442 let final_len = usable_cap / 2;
2444 for len in 0..final_len {
2445 let expected = if back {
2448 (0..len).rev().collect()
2450 for tail_pos in 0..usable_cap {
2451 tester.tail = tail_pos;
2452 tester.head = tail_pos;
2454 for i in 0..len * 2 {
2455 tester.push_front(i);
2458 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2461 for i in 0..len * 2 {
2462 tester.push_back(i);
2465 let idx = tester.len() - 1 - i;
2466 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2469 assert!(tester.tail < tester.cap());
2470 assert!(tester.head < tester.cap());
2471 assert_eq!(tester, expected);
2481 // This test checks that every single combination of tail position, length, and
2482 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2484 let mut tester = VecDeque::with_capacity(15);
2485 // can't guarantee we got 15, so have to get what we got.
2486 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2487 // this test isn't covering what it wants to
2488 let cap = tester.capacity();
2491 // len is the length *after* insertion
2493 // 0, 1, 2, .., len - 1
2494 let expected = (0..).take(len).collect();
2495 for tail_pos in 0..cap {
2496 for to_insert in 0..len {
2497 tester.tail = tail_pos;
2498 tester.head = tail_pos;
2501 tester.push_back(i);
2504 tester.insert(to_insert, to_insert);
2505 assert!(tester.tail < tester.cap());
2506 assert!(tester.head < tester.cap());
2507 assert_eq!(tester, expected);
2515 // This test checks that every single combination of tail position, length, and
2516 // removal position is tested. Capacity 15 should be large enough to cover every case.
2518 let mut tester = VecDeque::with_capacity(15);
2519 // can't guarantee we got 15, so have to get what we got.
2520 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2521 // this test isn't covering what it wants to
2522 let cap = tester.capacity();
2524 // len is the length *after* removal
2525 for len in 0..cap - 1 {
2526 // 0, 1, 2, .., len - 1
2527 let expected = (0..).take(len).collect();
2528 for tail_pos in 0..cap {
2529 for to_remove in 0..len + 1 {
2530 tester.tail = tail_pos;
2531 tester.head = tail_pos;
2534 tester.push_back(1234);
2536 tester.push_back(i);
2538 if to_remove == len {
2539 tester.push_back(1234);
2541 tester.remove(to_remove);
2542 assert!(tester.tail < tester.cap());
2543 assert!(tester.head < tester.cap());
2544 assert_eq!(tester, expected);
2552 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2554 let cap = tester.capacity();
2555 for len in 0..cap + 1 {
2556 for tail in 0..cap + 1 {
2557 for drain_start in 0..len + 1 {
2558 for drain_end in drain_start..len + 1 {
2562 tester.push_back(i);
2565 // Check that we drain the correct values
2566 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2567 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2568 assert_eq!(drained, drained_expected);
2570 // We shouldn't have changed the capacity or made the
2571 // head or tail out of bounds
2572 assert_eq!(tester.capacity(), cap);
2573 assert!(tester.tail < tester.cap());
2574 assert!(tester.head < tester.cap());
2576 // We should see the correct values in the VecDeque
2577 let expected: VecDeque<_> = (0..drain_start)
2578 .chain(drain_end..len)
2580 assert_eq!(expected, tester);
2588 fn test_shrink_to_fit() {
2589 // This test checks that every single combination of head and tail position,
2590 // is tested. Capacity 15 should be large enough to cover every case.
2592 let mut tester = VecDeque::with_capacity(15);
2593 // can't guarantee we got 15, so have to get what we got.
2594 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2595 // this test isn't covering what it wants to
2596 let cap = tester.capacity();
2598 let max_cap = tester.capacity();
2600 for len in 0..cap + 1 {
2601 // 0, 1, 2, .., len - 1
2602 let expected = (0..).take(len).collect();
2603 for tail_pos in 0..max_cap + 1 {
2604 tester.tail = tail_pos;
2605 tester.head = tail_pos;
2608 tester.push_back(i);
2610 tester.shrink_to_fit();
2611 assert!(tester.capacity() <= cap);
2612 assert!(tester.tail < tester.cap());
2613 assert!(tester.head < tester.cap());
2614 assert_eq!(tester, expected);
2620 fn test_split_off() {
2621 // This test checks that every single combination of tail position, length, and
2622 // split position is tested. Capacity 15 should be large enough to cover every case.
2624 let mut tester = VecDeque::with_capacity(15);
2625 // can't guarantee we got 15, so have to get what we got.
2626 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2627 // this test isn't covering what it wants to
2628 let cap = tester.capacity();
2630 // len is the length *before* splitting
2632 // index to split at
2633 for at in 0..len + 1 {
2634 // 0, 1, 2, .., at - 1 (may be empty)
2635 let expected_self = (0..).take(at).collect();
2636 // at, at + 1, .., len - 1 (may be empty)
2637 let expected_other = (at..).take(len - at).collect();
2639 for tail_pos in 0..cap {
2640 tester.tail = tail_pos;
2641 tester.head = tail_pos;
2643 tester.push_back(i);
2645 let result = tester.split_off(at);
2646 assert!(tester.tail < tester.cap());
2647 assert!(tester.head < tester.cap());
2648 assert!(result.tail < result.cap());
2649 assert!(result.head < result.cap());
2650 assert_eq!(tester, expected_self);
2651 assert_eq!(result, expected_other);
2658 fn test_from_vec() {
2659 use super::super::vec::Vec;
2661 for len in 0..cap + 1 {
2662 let mut vec = Vec::with_capacity(cap);
2665 let vd = VecDeque::from(vec.clone());
2666 assert!(vd.cap().is_power_of_two());
2667 assert_eq!(vd.len(), vec.len());
2668 assert!(vd.into_iter().eq(vec));
2674 fn test_vec_from_vecdeque() {
2675 use super::super::vec::Vec;
2677 fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
2678 let mut vd = VecDeque::with_capacity(cap);
2679 for _ in 0..offset {
2685 let vec: Vec<_> = Vec::from(vd.clone());
2686 assert_eq!(vec.len(), vd.len());
2687 assert!(vec.into_iter().eq(vd));
2690 for cap_pwr in 0..7 {
2691 // Make capacity as a (2^x)-1, so that the ring size is 2^x
2692 let cap = (2i32.pow(cap_pwr) - 1) as usize;
2694 // In these cases there is enough free space to solve it with copies
2695 for len in 0..((cap + 1) / 2) {
2696 // Test contiguous cases
2697 for offset in 0..(cap - len) {
2698 create_vec_and_test_convert(cap, offset, len)
2701 // Test cases where block at end of buffer is bigger than block at start
2702 for offset in (cap - len)..(cap - (len / 2)) {
2703 create_vec_and_test_convert(cap, offset, len)
2706 // Test cases where block at start of buffer is bigger than block at end
2707 for offset in (cap - (len / 2))..cap {
2708 create_vec_and_test_convert(cap, offset, len)
2712 // Now there's not (necessarily) space to straighten the ring with simple copies,
2713 // the ring will use swapping when:
2714 // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
2715 // right block size > free space && left block size > free space
2716 for len in ((cap + 1) / 2)..cap {
2717 // Test contiguous cases
2718 for offset in 0..(cap - len) {
2719 create_vec_and_test_convert(cap, offset, len)
2722 // Test cases where block at end of buffer is bigger than block at start
2723 for offset in (cap - len)..(cap - (len / 2)) {
2724 create_vec_and_test_convert(cap, offset, len)
2727 // Test cases where block at start of buffer is bigger than block at end
2728 for offset in (cap - (len / 2))..cap {
2729 create_vec_and_test_convert(cap, offset, len)