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};
27 use core::ptr::Shared;
30 use core::hash::{Hash, Hasher};
33 use alloc::raw_vec::RawVec;
35 use super::range::RangeArgument;
38 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
39 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
40 #[cfg(target_pointer_width = "32")]
41 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
42 #[cfg(target_pointer_width = "64")]
43 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
45 /// `VecDeque` is a growable ring buffer, which can be used as a double-ended
46 /// queue efficiently.
48 /// The "default" usage of this type as a queue is to use `push_back` to add to
49 /// the queue, and `pop_front` to remove from the queue. `extend` and `append`
50 /// push onto the back in this manner, and iterating over `VecDeque` goes front
52 #[stable(feature = "rust1", since = "1.0.0")]
53 pub struct VecDeque<T> {
54 // tail and head are pointers into the buffer. Tail always points
55 // to the first element that could be read, Head always points
56 // to where data should be written.
57 // If tail == head the buffer is empty. The length of the ringbuffer
58 // is defined as the distance between the two.
64 #[stable(feature = "rust1", since = "1.0.0")]
65 impl<T: Clone> Clone for VecDeque<T> {
66 fn clone(&self) -> VecDeque<T> {
67 self.iter().cloned().collect()
71 #[stable(feature = "rust1", since = "1.0.0")]
72 impl<T> Drop for VecDeque<T> {
73 #[unsafe_destructor_blind_to_params]
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> {
88 fn default() -> VecDeque<T> {
94 /// Marginally more convenient
96 fn ptr(&self) -> *mut T {
100 /// Marginally more convenient
102 fn cap(&self) -> usize {
103 if mem::size_of::<T>() == 0 {
104 // For zero sized types, we are always at maximum capacity
111 /// Turn ptr into a slice
113 unsafe fn buffer_as_slice(&self) -> &[T] {
114 slice::from_raw_parts(self.ptr(), self.cap())
117 /// Turn ptr into a mut slice
119 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
120 slice::from_raw_parts_mut(self.ptr(), self.cap())
123 /// Moves an element out of the buffer
125 unsafe fn buffer_read(&mut self, off: usize) -> T {
126 ptr::read(self.ptr().offset(off as isize))
129 /// Writes an element into the buffer, moving it.
131 unsafe fn buffer_write(&mut self, off: usize, value: T) {
132 ptr::write(self.ptr().offset(off as isize), value);
135 /// Returns true if and only if the buffer is at capacity
137 fn is_full(&self) -> bool {
138 self.cap() - self.len() == 1
141 /// Returns the index in the underlying buffer for a given logical element
144 fn wrap_index(&self, idx: usize) -> usize {
145 wrap_index(idx, self.cap())
148 /// Returns the index in the underlying buffer for a given logical element
151 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
152 wrap_index(idx.wrapping_add(addend), self.cap())
155 /// Returns the index in the underlying buffer for a given logical element
156 /// index - subtrahend.
158 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
159 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
162 /// Copies a contiguous block of memory len long from src to dst
164 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
165 debug_assert!(dst + len <= self.cap(),
166 "cpy dst={} src={} len={} cap={}",
171 debug_assert!(src + len <= self.cap(),
172 "cpy dst={} src={} len={} cap={}",
177 ptr::copy(self.ptr().offset(src as isize),
178 self.ptr().offset(dst as isize),
182 /// Copies a contiguous block of memory len long from src to dst
184 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
185 debug_assert!(dst + len <= self.cap(),
186 "cno dst={} src={} len={} cap={}",
191 debug_assert!(src + len <= self.cap(),
192 "cno dst={} src={} len={} cap={}",
197 ptr::copy_nonoverlapping(self.ptr().offset(src as isize),
198 self.ptr().offset(dst as isize),
202 /// Copies a potentially wrapping block of memory len long from src to dest.
203 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
204 /// most one continuous overlapping region between src and dest).
205 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
207 fn diff(a: usize, b: usize) -> usize {
214 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
215 "wrc dst={} src={} len={} cap={}",
221 if src == dst || len == 0 {
225 let dst_after_src = self.wrap_sub(dst, src) < len;
227 let src_pre_wrap_len = self.cap() - src;
228 let dst_pre_wrap_len = self.cap() - dst;
229 let src_wraps = src_pre_wrap_len < len;
230 let dst_wraps = dst_pre_wrap_len < len;
232 match (dst_after_src, src_wraps, dst_wraps) {
233 (_, false, false) => {
234 // src doesn't wrap, dst doesn't wrap
237 // 1 [_ _ A A B B C C _]
238 // 2 [_ _ A A A A B B _]
241 self.copy(dst, src, len);
243 (false, false, true) => {
244 // dst before src, src doesn't wrap, dst wraps
247 // 1 [A A B B _ _ _ C C]
248 // 2 [A A B B _ _ _ A A]
249 // 3 [B B B B _ _ _ A A]
252 self.copy(dst, src, dst_pre_wrap_len);
253 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
255 (true, false, true) => {
256 // src before dst, src doesn't wrap, dst wraps
259 // 1 [C C _ _ _ A A B B]
260 // 2 [B B _ _ _ A A B B]
261 // 3 [B B _ _ _ A A A A]
264 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
265 self.copy(dst, src, dst_pre_wrap_len);
267 (false, true, false) => {
268 // dst before src, src wraps, dst doesn't wrap
271 // 1 [C C _ _ _ A A B B]
272 // 2 [C C _ _ _ B B B B]
273 // 3 [C C _ _ _ B B C C]
276 self.copy(dst, src, src_pre_wrap_len);
277 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
279 (true, true, false) => {
280 // src before dst, src wraps, dst doesn't wrap
283 // 1 [A A B B _ _ _ C C]
284 // 2 [A A A A _ _ _ C C]
285 // 3 [C C A A _ _ _ C C]
288 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
289 self.copy(dst, src, src_pre_wrap_len);
291 (false, true, true) => {
292 // dst before src, src wraps, dst wraps
295 // 1 [A B C D _ E F G H]
296 // 2 [A B C D _ E G H H]
297 // 3 [A B C D _ E G H A]
298 // 4 [B C C D _ E G H A]
301 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
302 let delta = dst_pre_wrap_len - src_pre_wrap_len;
303 self.copy(dst, src, src_pre_wrap_len);
304 self.copy(dst + src_pre_wrap_len, 0, delta);
305 self.copy(0, delta, len - dst_pre_wrap_len);
307 (true, true, true) => {
308 // src before dst, src wraps, dst wraps
311 // 1 [A B C D _ E F G H]
312 // 2 [A A B D _ E F G H]
313 // 3 [H A B D _ E F G H]
314 // 4 [H A B D _ E F F G]
317 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
318 let delta = src_pre_wrap_len - dst_pre_wrap_len;
319 self.copy(delta, 0, len - src_pre_wrap_len);
320 self.copy(0, self.cap() - delta, delta);
321 self.copy(dst, src, dst_pre_wrap_len);
326 /// Frobs the head and tail sections around to handle the fact that we
327 /// just reallocated. Unsafe because it trusts old_cap.
329 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
330 let new_cap = self.cap();
332 // Move the shortest contiguous section of the ring buffer
334 // [o o o o o o o . ]
336 // A [o o o o o o o . . . . . . . . . ]
338 // [o o . o o o o o ]
340 // B [. . . o o o o o o o . . . . . . ]
342 // [o o o o o . o o ]
344 // C [o o o o o . . . . . . . . . o o ]
346 if self.tail <= self.head {
349 } else if self.head < old_cap - self.tail {
351 self.copy_nonoverlapping(old_cap, 0, self.head);
352 self.head += old_cap;
353 debug_assert!(self.head > self.tail);
356 let new_tail = new_cap - (old_cap - self.tail);
357 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
358 self.tail = new_tail;
359 debug_assert!(self.head < self.tail);
361 debug_assert!(self.head < self.cap());
362 debug_assert!(self.tail < self.cap());
363 debug_assert!(self.cap().count_ones() == 1);
367 impl<T> VecDeque<T> {
368 /// Creates an empty `VecDeque`.
373 /// use std::collections::VecDeque;
375 /// let vector: VecDeque<u32> = VecDeque::new();
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn new() -> VecDeque<T> {
379 VecDeque::with_capacity(INITIAL_CAPACITY)
382 /// Creates an empty `VecDeque` with space for at least `n` elements.
387 /// use std::collections::VecDeque;
389 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
391 #[stable(feature = "rust1", since = "1.0.0")]
392 pub fn with_capacity(n: usize) -> VecDeque<T> {
393 // +1 since the ringbuffer always leaves one space empty
394 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
395 assert!(cap > n, "capacity overflow");
400 buf: RawVec::with_capacity(cap),
404 /// Retrieves an element in the `VecDeque` by index.
406 /// Element at index 0 is the front of the queue.
411 /// use std::collections::VecDeque;
413 /// let mut buf = VecDeque::new();
414 /// buf.push_back(3);
415 /// buf.push_back(4);
416 /// buf.push_back(5);
417 /// assert_eq!(buf.get(1), Some(&4));
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn get(&self, index: usize) -> Option<&T> {
421 if index < self.len() {
422 let idx = self.wrap_add(self.tail, index);
423 unsafe { Some(&*self.ptr().offset(idx as isize)) }
429 /// Retrieves an element in the `VecDeque` mutably by index.
431 /// Element at index 0 is the front of the queue.
436 /// use std::collections::VecDeque;
438 /// let mut buf = VecDeque::new();
439 /// buf.push_back(3);
440 /// buf.push_back(4);
441 /// buf.push_back(5);
442 /// if let Some(elem) = buf.get_mut(1) {
446 /// assert_eq!(buf[1], 7);
448 #[stable(feature = "rust1", since = "1.0.0")]
449 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
450 if index < self.len() {
451 let idx = self.wrap_add(self.tail, index);
452 unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
458 /// Swaps elements at indices `i` and `j`.
460 /// `i` and `j` may be equal.
462 /// Fails if there is no element with either index.
464 /// Element at index 0 is the front of the queue.
469 /// use std::collections::VecDeque;
471 /// let mut buf = VecDeque::new();
472 /// buf.push_back(3);
473 /// buf.push_back(4);
474 /// buf.push_back(5);
476 /// assert_eq!(buf[0], 5);
477 /// assert_eq!(buf[2], 3);
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn swap(&mut self, i: usize, j: usize) {
481 assert!(i < self.len());
482 assert!(j < self.len());
483 let ri = self.wrap_add(self.tail, i);
484 let rj = self.wrap_add(self.tail, j);
486 ptr::swap(self.ptr().offset(ri as isize),
487 self.ptr().offset(rj as isize))
491 /// Returns the number of elements the `VecDeque` can hold without
497 /// use std::collections::VecDeque;
499 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
500 /// assert!(buf.capacity() >= 10);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn capacity(&self) -> usize {
508 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
509 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
511 /// Note that the allocator may give the collection more space than it requests. Therefore
512 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
513 /// insertions are expected.
517 /// Panics if the new capacity overflows `usize`.
522 /// use std::collections::VecDeque;
524 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
525 /// buf.reserve_exact(10);
526 /// assert!(buf.capacity() >= 11);
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn reserve_exact(&mut self, additional: usize) {
530 self.reserve(additional);
533 /// Reserves capacity for at least `additional` more elements to be inserted in the given
534 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
538 /// Panics if the new capacity overflows `usize`.
543 /// use std::collections::VecDeque;
545 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
547 /// assert!(buf.capacity() >= 11);
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn reserve(&mut self, additional: usize) {
551 let old_cap = self.cap();
552 let used_cap = self.len() + 1;
553 let new_cap = used_cap.checked_add(additional)
554 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
555 .expect("capacity overflow");
557 if new_cap > self.capacity() {
558 self.buf.reserve_exact(used_cap, new_cap - used_cap);
560 self.handle_cap_increase(old_cap);
565 /// Shrinks the capacity of the `VecDeque` as much as possible.
567 /// It will drop down as close as possible to the length but the allocator may still inform the
568 /// `VecDeque` that there is space for a few more elements.
573 /// use std::collections::VecDeque;
575 /// let mut buf = VecDeque::with_capacity(15);
576 /// buf.extend(0..4);
577 /// assert_eq!(buf.capacity(), 15);
578 /// buf.shrink_to_fit();
579 /// assert!(buf.capacity() >= 4);
581 #[stable(feature = "deque_extras_15", since = "1.5.0")]
582 pub fn shrink_to_fit(&mut self) {
583 // +1 since the ringbuffer always leaves one space empty
584 // len + 1 can't overflow for an existing, well-formed ringbuffer.
585 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
586 if target_cap < self.cap() {
587 // There are three cases of interest:
588 // All elements are out of desired bounds
589 // Elements are contiguous, and head is out of desired bounds
590 // Elements are discontiguous, and tail is out of desired bounds
592 // At all other times, element positions are unaffected.
594 // Indicates that elements at the head should be moved.
595 let head_outside = self.head == 0 || self.head >= target_cap;
596 // Move elements from out of desired bounds (positions after target_cap)
597 if self.tail >= target_cap && head_outside {
599 // [. . . . . . . . o o o o o o o . ]
601 // [o o o o o o o . ]
603 self.copy_nonoverlapping(0, self.tail, self.len());
605 self.head = self.len();
607 } else if self.tail != 0 && self.tail < target_cap && head_outside {
609 // [. . . o o o o o o o . . . . . . ]
611 // [o o . o o o o o ]
612 let len = self.wrap_sub(self.head, target_cap);
614 self.copy_nonoverlapping(0, target_cap, len);
617 debug_assert!(self.head < self.tail);
618 } else if self.tail >= target_cap {
620 // [o o o o o . . . . . . . . . o o ]
622 // [o o o o o . o o ]
623 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
624 let len = self.cap() - self.tail;
625 let new_tail = target_cap - len;
627 self.copy_nonoverlapping(new_tail, self.tail, len);
629 self.tail = new_tail;
630 debug_assert!(self.head < self.tail);
633 self.buf.shrink_to_fit(target_cap);
635 debug_assert!(self.head < self.cap());
636 debug_assert!(self.tail < self.cap());
637 debug_assert!(self.cap().count_ones() == 1);
641 /// Shortens a `VecDeque`, dropping excess elements from the back.
643 /// If `len` is greater than the `VecDeque`'s current length, this has no
649 /// #![feature(deque_extras)]
651 /// use std::collections::VecDeque;
653 /// let mut buf = VecDeque::new();
654 /// buf.push_back(5);
655 /// buf.push_back(10);
656 /// buf.push_back(15);
658 /// assert_eq!(buf.len(), 1);
659 /// assert_eq!(Some(&5), buf.get(0));
661 #[unstable(feature = "deque_extras",
662 reason = "matches collection reform specification; waiting on panic semantics",
664 pub fn truncate(&mut self, len: usize) {
665 for _ in len..self.len() {
670 /// Returns a front-to-back iterator.
675 /// use std::collections::VecDeque;
677 /// let mut buf = VecDeque::new();
678 /// buf.push_back(5);
679 /// buf.push_back(3);
680 /// buf.push_back(4);
681 /// let b: &[_] = &[&5, &3, &4];
682 /// let c: Vec<&i32> = buf.iter().collect();
683 /// assert_eq!(&c[..], b);
685 #[stable(feature = "rust1", since = "1.0.0")]
686 pub fn iter(&self) -> Iter<T> {
690 ring: unsafe { self.buffer_as_slice() },
694 /// Returns a front-to-back iterator that returns mutable references.
699 /// use std::collections::VecDeque;
701 /// let mut buf = VecDeque::new();
702 /// buf.push_back(5);
703 /// buf.push_back(3);
704 /// buf.push_back(4);
705 /// for num in buf.iter_mut() {
708 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
709 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn iter_mut(&mut self) -> IterMut<T> {
716 ring: unsafe { self.buffer_as_mut_slice() },
720 /// Returns a pair of slices which contain, in order, the contents of the
726 /// use std::collections::VecDeque;
728 /// let mut vector: VecDeque<u32> = VecDeque::new();
730 /// vector.push_back(0);
731 /// vector.push_back(1);
732 /// vector.push_back(2);
734 /// assert_eq!(vector.as_slices(), (&[0u32, 1, 2] as &[u32], &[] as &[u32]));
736 /// vector.push_front(10);
737 /// vector.push_front(9);
739 /// assert_eq!(vector.as_slices(), (&[9u32, 10] as &[u32], &[0u32, 1, 2] as &[u32]));
742 #[stable(feature = "deque_extras_15", since = "1.5.0")]
743 pub fn as_slices(&self) -> (&[T], &[T]) {
745 let contiguous = self.is_contiguous();
746 let buf = self.buffer_as_slice();
748 let (empty, buf) = buf.split_at(0);
749 (&buf[self.tail..self.head], empty)
751 let (mid, right) = buf.split_at(self.tail);
752 let (left, _) = mid.split_at(self.head);
758 /// Returns a pair of slices which contain, in order, the contents of the
764 /// use std::collections::VecDeque;
766 /// let mut vector: VecDeque<u32> = VecDeque::new();
768 /// vector.push_back(0);
769 /// vector.push_back(1);
771 /// vector.push_front(10);
772 /// vector.push_front(9);
774 /// vector.as_mut_slices().0[0] = 42;
775 /// vector.as_mut_slices().1[0] = 24;
776 /// assert_eq!(vector.as_slices(), (&[42u32, 10] as &[u32], &[24u32, 1] as &[u32]));
779 #[stable(feature = "deque_extras_15", since = "1.5.0")]
780 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
782 let contiguous = self.is_contiguous();
783 let head = self.head;
784 let tail = self.tail;
785 let buf = self.buffer_as_mut_slice();
788 let (empty, buf) = buf.split_at_mut(0);
789 (&mut buf[tail..head], empty)
791 let (mid, right) = buf.split_at_mut(tail);
792 let (left, _) = mid.split_at_mut(head);
799 /// Returns the number of elements in the `VecDeque`.
804 /// use std::collections::VecDeque;
806 /// let mut v = VecDeque::new();
807 /// assert_eq!(v.len(), 0);
809 /// assert_eq!(v.len(), 1);
811 #[stable(feature = "rust1", since = "1.0.0")]
812 pub fn len(&self) -> usize {
813 count(self.tail, self.head, self.cap())
816 /// Returns true if the buffer contains no elements
821 /// use std::collections::VecDeque;
823 /// let mut v = VecDeque::new();
824 /// assert!(v.is_empty());
826 /// assert!(!v.is_empty());
828 #[stable(feature = "rust1", since = "1.0.0")]
829 pub fn is_empty(&self) -> bool {
833 /// Create a draining iterator that removes the specified range in the
834 /// `VecDeque` and yields the removed items.
836 /// Note 1: The element range is removed even if the iterator is not
837 /// consumed until the end.
839 /// Note 2: It is unspecified how many elements are removed from the deque,
840 /// if the `Drain` value is not dropped, but the borrow it holds expires
841 /// (eg. due to mem::forget).
845 /// Panics if the starting point is greater than the end point or if
846 /// the end point is greater than the length of the vector.
851 /// use std::collections::VecDeque;
853 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
854 /// assert_eq!(vec![3].into_iter().collect::<VecDeque<_>>(), v.drain(2..).collect());
855 /// assert_eq!(vec![1, 2].into_iter().collect::<VecDeque<_>>(), v);
857 /// // A full range clears all contents
859 /// assert!(v.is_empty());
862 #[stable(feature = "drain", since = "1.6.0")]
863 pub fn drain<R>(&mut self, range: R) -> Drain<T>
864 where R: RangeArgument<usize>
868 // When the Drain is first created, the source deque is shortened to
869 // make sure no uninitialized or moved-from elements are accessible at
870 // all if the Drain's destructor never gets to run.
872 // Drain will ptr::read out the values to remove.
873 // When finished, the remaining data will be copied back to cover the hole,
874 // and the head/tail values will be restored correctly.
876 let len = self.len();
877 let start = *range.start().unwrap_or(&0);
878 let end = *range.end().unwrap_or(&len);
879 assert!(start <= end, "drain lower bound was too large");
880 assert!(end <= len, "drain upper bound was too large");
882 // The deque's elements are parted into three segments:
883 // * self.tail -> drain_tail
884 // * drain_tail -> drain_head
885 // * drain_head -> self.head
887 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
889 // We store drain_tail as self.head, and drain_head and self.head as
890 // after_tail and after_head respectively on the Drain. This also
891 // truncates the effective array such that if the Drain is leaked, we
892 // have forgotten about the potentially moved values after the start of
896 // [. . . o o x x o o . . .]
898 let drain_tail = self.wrap_add(self.tail, start);
899 let drain_head = self.wrap_add(self.tail, end);
900 let head = self.head;
902 // "forget" about the values after the start of the drain until after
903 // the drain is complete and the Drain destructor is run.
904 self.head = drain_tail;
907 deque: unsafe { Shared::new(self as *mut _) },
908 after_tail: drain_head,
913 ring: unsafe { self.buffer_as_mut_slice() },
918 /// Clears the buffer, removing all values.
923 /// use std::collections::VecDeque;
925 /// let mut v = VecDeque::new();
928 /// assert!(v.is_empty());
930 #[stable(feature = "rust1", since = "1.0.0")]
932 pub fn clear(&mut self) {
936 /// Returns `true` if the `VecDeque` contains an element equal to the
942 /// use std::collections::VecDeque;
944 /// let mut vector: VecDeque<u32> = VecDeque::new();
946 /// vector.push_back(0);
947 /// vector.push_back(1);
949 /// assert_eq!(vector.contains(&1), true);
950 /// assert_eq!(vector.contains(&10), false);
952 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
953 pub fn contains(&self, x: &T) -> bool
954 where T: PartialEq<T>
956 let (a, b) = self.as_slices();
957 a.contains(x) || b.contains(x)
960 /// Provides a reference to the front element, or `None` if the sequence is
966 /// use std::collections::VecDeque;
968 /// let mut d = VecDeque::new();
969 /// assert_eq!(d.front(), None);
973 /// assert_eq!(d.front(), Some(&1));
975 #[stable(feature = "rust1", since = "1.0.0")]
976 pub fn front(&self) -> Option<&T> {
977 if !self.is_empty() {
984 /// Provides a mutable reference to the front element, or `None` if the
985 /// sequence is empty.
990 /// use std::collections::VecDeque;
992 /// let mut d = VecDeque::new();
993 /// assert_eq!(d.front_mut(), None);
997 /// match d.front_mut() {
998 /// Some(x) => *x = 9,
1001 /// assert_eq!(d.front(), Some(&9));
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 pub fn front_mut(&mut self) -> Option<&mut T> {
1005 if !self.is_empty() {
1012 /// Provides a reference to the back element, or `None` if the sequence is
1018 /// use std::collections::VecDeque;
1020 /// let mut d = VecDeque::new();
1021 /// assert_eq!(d.back(), None);
1025 /// assert_eq!(d.back(), Some(&2));
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 pub fn back(&self) -> Option<&T> {
1029 if !self.is_empty() {
1030 Some(&self[self.len() - 1])
1036 /// Provides a mutable reference to the back element, or `None` if the
1037 /// sequence is empty.
1042 /// use std::collections::VecDeque;
1044 /// let mut d = VecDeque::new();
1045 /// assert_eq!(d.back(), None);
1049 /// match d.back_mut() {
1050 /// Some(x) => *x = 9,
1053 /// assert_eq!(d.back(), Some(&9));
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn back_mut(&mut self) -> Option<&mut T> {
1057 let len = self.len();
1058 if !self.is_empty() {
1059 Some(&mut self[len - 1])
1065 /// Removes the first element and returns it, or `None` if the sequence is
1071 /// use std::collections::VecDeque;
1073 /// let mut d = VecDeque::new();
1077 /// assert_eq!(d.pop_front(), Some(1));
1078 /// assert_eq!(d.pop_front(), Some(2));
1079 /// assert_eq!(d.pop_front(), None);
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub fn pop_front(&mut self) -> Option<T> {
1083 if self.is_empty() {
1086 let tail = self.tail;
1087 self.tail = self.wrap_add(self.tail, 1);
1088 unsafe { Some(self.buffer_read(tail)) }
1092 /// Inserts an element first in the sequence.
1097 /// use std::collections::VecDeque;
1099 /// let mut d = VecDeque::new();
1100 /// d.push_front(1);
1101 /// d.push_front(2);
1102 /// assert_eq!(d.front(), Some(&2));
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 pub fn push_front(&mut self, value: T) {
1107 let old_cap = self.cap();
1110 self.handle_cap_increase(old_cap);
1112 debug_assert!(!self.is_full());
1115 self.tail = self.wrap_sub(self.tail, 1);
1116 let tail = self.tail;
1118 self.buffer_write(tail, value);
1122 /// Appends an element to the back of a buffer
1127 /// use std::collections::VecDeque;
1129 /// let mut buf = VecDeque::new();
1130 /// buf.push_back(1);
1131 /// buf.push_back(3);
1132 /// assert_eq!(3, *buf.back().unwrap());
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 pub fn push_back(&mut self, value: T) {
1137 let old_cap = self.cap();
1140 self.handle_cap_increase(old_cap);
1142 debug_assert!(!self.is_full());
1145 let head = self.head;
1146 self.head = self.wrap_add(self.head, 1);
1147 unsafe { self.buffer_write(head, value) }
1150 /// Removes the last element from a buffer and returns it, or `None` if
1156 /// use std::collections::VecDeque;
1158 /// let mut buf = VecDeque::new();
1159 /// assert_eq!(buf.pop_back(), None);
1160 /// buf.push_back(1);
1161 /// buf.push_back(3);
1162 /// assert_eq!(buf.pop_back(), Some(3));
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 pub fn pop_back(&mut self) -> Option<T> {
1166 if self.is_empty() {
1169 self.head = self.wrap_sub(self.head, 1);
1170 let head = self.head;
1171 unsafe { Some(self.buffer_read(head)) }
1176 fn is_contiguous(&self) -> bool {
1177 self.tail <= self.head
1180 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1183 /// This does not preserve ordering, but is O(1).
1185 /// Returns `None` if `index` is out of bounds.
1187 /// Element at index 0 is the front of the queue.
1192 /// use std::collections::VecDeque;
1194 /// let mut buf = VecDeque::new();
1195 /// assert_eq!(buf.swap_remove_back(0), None);
1196 /// buf.push_back(1);
1197 /// buf.push_back(2);
1198 /// buf.push_back(3);
1200 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1201 /// assert_eq!(buf.len(), 2);
1202 /// assert_eq!(buf[0], 3);
1203 /// assert_eq!(buf[1], 2);
1205 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1206 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1207 let length = self.len();
1208 if length > 0 && index < length - 1 {
1209 self.swap(index, length - 1);
1210 } else if index >= length {
1216 /// Removes an element from anywhere in the `VecDeque` and returns it,
1217 /// replacing it with the first element.
1219 /// This does not preserve ordering, but is O(1).
1221 /// Returns `None` if `index` is out of bounds.
1223 /// Element at index 0 is the front of the queue.
1228 /// use std::collections::VecDeque;
1230 /// let mut buf = VecDeque::new();
1231 /// assert_eq!(buf.swap_remove_front(0), None);
1232 /// buf.push_back(1);
1233 /// buf.push_back(2);
1234 /// buf.push_back(3);
1236 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1237 /// assert_eq!(buf.len(), 2);
1238 /// assert_eq!(buf[0], 2);
1239 /// assert_eq!(buf[1], 1);
1241 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1242 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1243 let length = self.len();
1244 if length > 0 && index < length && index != 0 {
1245 self.swap(index, 0);
1246 } else if index >= length {
1252 /// Inserts an element at `index` within the `VecDeque`. Whichever
1253 /// end is closer to the insertion point will be moved to make room,
1254 /// and all the affected elements will be moved to new positions.
1256 /// Element at index 0 is the front of the queue.
1260 /// Panics if `index` is greater than `VecDeque`'s length
1264 /// use std::collections::VecDeque;
1266 /// let mut buf = VecDeque::new();
1267 /// buf.push_back(10);
1268 /// buf.push_back(12);
1269 /// buf.insert(1, 11);
1270 /// assert_eq!(Some(&11), buf.get(1));
1272 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1273 pub fn insert(&mut self, index: usize, value: T) {
1274 assert!(index <= self.len(), "index out of bounds");
1276 let old_cap = self.cap();
1279 self.handle_cap_increase(old_cap);
1281 debug_assert!(!self.is_full());
1284 // Move the least number of elements in the ring buffer and insert
1287 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1289 // There are three main cases:
1290 // Elements are contiguous
1291 // - special case when tail is 0
1292 // Elements are discontiguous and the insert is in the tail section
1293 // Elements are discontiguous and the insert is in the head section
1295 // For each of those there are two more cases:
1296 // Insert is closer to tail
1297 // Insert is closer to head
1299 // Key: H - self.head
1301 // o - Valid element
1302 // I - Insertion element
1303 // A - The element that should be after the insertion point
1304 // M - Indicates element was moved
1306 let idx = self.wrap_add(self.tail, index);
1308 let distance_to_tail = index;
1309 let distance_to_head = self.len() - index;
1311 let contiguous = self.is_contiguous();
1314 distance_to_tail <= distance_to_head,
1316 (true, true, _) if index == 0 => {
1321 // [A o o o o o o . . . . . . . . .]
1324 // [A o o o o o o o . . . . . I]
1327 self.tail = self.wrap_sub(self.tail, 1);
1329 (true, true, _) => {
1331 // contiguous, insert closer to tail:
1334 // [. . . o o A o o o o . . . . . .]
1337 // [. . o o I A o o o o . . . . . .]
1340 // contiguous, insert closer to tail and tail is 0:
1344 // [o o A o o o o . . . . . . . . .]
1347 // [o I A o o o o o . . . . . . . o]
1350 let new_tail = self.wrap_sub(self.tail, 1);
1352 self.copy(new_tail, self.tail, 1);
1353 // Already moved the tail, so we only copy `index - 1` elements.
1354 self.copy(self.tail, self.tail + 1, index - 1);
1356 self.tail = new_tail;
1359 (true, false, _) => {
1361 // contiguous, insert closer to head:
1364 // [. . . o o o o A o o . . . . . .]
1367 // [. . . o o o o I A o o . . . . .]
1370 self.copy(idx + 1, idx, self.head - idx);
1371 self.head = self.wrap_add(self.head, 1);
1374 (false, true, true) => {
1376 // discontiguous, insert closer to tail, tail section:
1379 // [o o o o o o . . . . . o o A o o]
1382 // [o o o o o o . . . . o o I A o o]
1385 self.copy(self.tail - 1, self.tail, index);
1389 (false, false, true) => {
1391 // discontiguous, insert closer to head, tail section:
1394 // [o o . . . . . . . o o o o o A o]
1397 // [o o o . . . . . . o o o o o I A]
1400 // copy elements up to new head
1401 self.copy(1, 0, self.head);
1403 // copy last element into empty spot at bottom of buffer
1404 self.copy(0, self.cap() - 1, 1);
1406 // move elements from idx to end forward not including ^ element
1407 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1412 (false, true, false) if idx == 0 => {
1414 // discontiguous, insert is closer to tail, head section,
1415 // and is at index zero in the internal buffer:
1418 // [A o o o o o o o o o . . . o o o]
1421 // [A o o o o o o o o o . . o o o I]
1424 // copy elements up to new tail
1425 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1427 // copy last element into empty spot at bottom of buffer
1428 self.copy(self.cap() - 1, 0, 1);
1433 (false, true, false) => {
1435 // discontiguous, insert closer to tail, head section:
1438 // [o o o A o o o o o o . . . o o o]
1441 // [o o I A o o o o o o . . o o o o]
1444 // copy elements up to new tail
1445 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1447 // copy last element into empty spot at bottom of buffer
1448 self.copy(self.cap() - 1, 0, 1);
1450 // move elements from idx-1 to end forward not including ^ element
1451 self.copy(0, 1, idx - 1);
1456 (false, false, false) => {
1458 // discontiguous, insert closer to head, head section:
1461 // [o o o o A o o . . . . . . o o o]
1464 // [o o o o I A o o . . . . . o o o]
1467 self.copy(idx + 1, idx, self.head - idx);
1473 // tail might've been changed so we need to recalculate
1474 let new_idx = self.wrap_add(self.tail, index);
1476 self.buffer_write(new_idx, value);
1480 /// Removes and returns the element at `index` from the `VecDeque`.
1481 /// Whichever end is closer to the removal point will be moved to make
1482 /// room, and all the affected elements will be moved to new positions.
1483 /// Returns `None` if `index` is out of bounds.
1485 /// Element at index 0 is the front of the queue.
1490 /// use std::collections::VecDeque;
1492 /// let mut buf = VecDeque::new();
1493 /// buf.push_back(1);
1494 /// buf.push_back(2);
1495 /// buf.push_back(3);
1497 /// assert_eq!(buf.remove(1), Some(2));
1498 /// assert_eq!(buf.get(1), Some(&3));
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 pub fn remove(&mut self, index: usize) -> Option<T> {
1502 if self.is_empty() || self.len() <= index {
1506 // There are three main cases:
1507 // Elements are contiguous
1508 // Elements are discontiguous and the removal is in the tail section
1509 // Elements are discontiguous and the removal is in the head section
1510 // - special case when elements are technically contiguous,
1511 // but self.head = 0
1513 // For each of those there are two more cases:
1514 // Insert is closer to tail
1515 // Insert is closer to head
1517 // Key: H - self.head
1519 // o - Valid element
1520 // x - Element marked for removal
1521 // R - Indicates element that is being removed
1522 // M - Indicates element was moved
1524 let idx = self.wrap_add(self.tail, index);
1526 let elem = unsafe { Some(self.buffer_read(idx)) };
1528 let distance_to_tail = index;
1529 let distance_to_head = self.len() - index;
1531 let contiguous = self.is_contiguous();
1534 distance_to_tail <= distance_to_head,
1536 (true, true, _) => {
1538 // contiguous, remove closer to tail:
1541 // [. . . o o x o o o o . . . . . .]
1544 // [. . . . o o o o o o . . . . . .]
1547 self.copy(self.tail + 1, self.tail, index);
1551 (true, false, _) => {
1553 // contiguous, remove closer to head:
1556 // [. . . o o o o x o o . . . . . .]
1559 // [. . . o o o o o o . . . . . . .]
1562 self.copy(idx, idx + 1, self.head - idx - 1);
1566 (false, true, true) => {
1568 // discontiguous, remove closer to tail, tail section:
1571 // [o o o o o o . . . . . o o x o o]
1574 // [o o o o o o . . . . . . o o o o]
1577 self.copy(self.tail + 1, self.tail, index);
1578 self.tail = self.wrap_add(self.tail, 1);
1581 (false, false, false) => {
1583 // discontiguous, remove closer to head, head section:
1586 // [o o o o x o o . . . . . . o o o]
1589 // [o o o o o o . . . . . . . o o o]
1592 self.copy(idx, idx + 1, self.head - idx - 1);
1596 (false, false, true) => {
1598 // discontiguous, remove closer to head, tail section:
1601 // [o o o . . . . . . o o o o o x o]
1604 // [o o . . . . . . . o o o o o o o]
1607 // or quasi-discontiguous, remove next to head, tail section:
1610 // [. . . . . . . . . o o o o o x o]
1613 // [. . . . . . . . . o o o o o o .]
1616 // draw in elements in the tail section
1617 self.copy(idx, idx + 1, self.cap() - idx - 1);
1619 // Prevents underflow.
1621 // copy first element into empty spot
1622 self.copy(self.cap() - 1, 0, 1);
1624 // move elements in the head section backwards
1625 self.copy(0, 1, self.head - 1);
1628 self.head = self.wrap_sub(self.head, 1);
1631 (false, true, false) => {
1633 // discontiguous, remove closer to tail, head section:
1636 // [o o x o o o o o o o . . . o o o]
1639 // [o o o o o o o o o o . . . . o o]
1642 // draw in elements up to idx
1643 self.copy(1, 0, idx);
1645 // copy last element into empty spot
1646 self.copy(0, self.cap() - 1, 1);
1648 // move elements from tail to end forward, excluding the last one
1649 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1651 self.tail = self.wrap_add(self.tail, 1);
1659 /// Splits the collection into two at the given index.
1661 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1662 /// and the returned `Self` contains elements `[at, len)`.
1664 /// Note that the capacity of `self` does not change.
1666 /// Element at index 0 is the front of the queue.
1670 /// Panics if `at > len`
1675 /// use std::collections::VecDeque;
1677 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1678 /// let buf2 = buf.split_off(1);
1679 /// // buf = [1], buf2 = [2, 3]
1680 /// assert_eq!(buf.len(), 1);
1681 /// assert_eq!(buf2.len(), 2);
1684 #[stable(feature = "split_off", since = "1.4.0")]
1685 pub fn split_off(&mut self, at: usize) -> Self {
1686 let len = self.len();
1687 assert!(at <= len, "`at` out of bounds");
1689 let other_len = len - at;
1690 let mut other = VecDeque::with_capacity(other_len);
1693 let (first_half, second_half) = self.as_slices();
1695 let first_len = first_half.len();
1696 let second_len = second_half.len();
1698 // `at` lies in the first half.
1699 let amount_in_first = first_len - at;
1701 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1705 // just take all of the second half.
1706 ptr::copy_nonoverlapping(second_half.as_ptr(),
1707 other.ptr().offset(amount_in_first as isize),
1710 // `at` lies in the second half, need to factor in the elements we skipped
1711 // in the first half.
1712 let offset = at - first_len;
1713 let amount_in_second = second_len - offset;
1714 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1720 // Cleanup where the ends of the buffers are
1721 self.head = self.wrap_sub(self.head, other_len);
1722 other.head = other.wrap_index(other_len);
1727 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1731 /// Panics if the new number of elements in self overflows a `usize`.
1736 /// use std::collections::VecDeque;
1738 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1739 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
1740 /// buf.append(&mut buf2);
1741 /// assert_eq!(buf.len(), 6);
1742 /// assert_eq!(buf2.len(), 0);
1745 #[stable(feature = "append", since = "1.4.0")]
1746 pub fn append(&mut self, other: &mut Self) {
1748 self.extend(other.drain(..));
1751 /// Retains only the elements specified by the predicate.
1753 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1754 /// This method operates in place and preserves the order of the retained
1760 /// use std::collections::VecDeque;
1762 /// let mut buf = VecDeque::new();
1763 /// buf.extend(1..5);
1764 /// buf.retain(|&x| x%2 == 0);
1766 /// let v: Vec<_> = buf.into_iter().collect();
1767 /// assert_eq!(&v[..], &[2, 4]);
1769 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1770 pub fn retain<F>(&mut self, mut f: F)
1771 where F: FnMut(&T) -> bool
1773 let len = self.len();
1779 self.swap(i - del, i);
1783 self.truncate(len - del);
1788 impl<T: Clone> VecDeque<T> {
1789 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1790 /// either by removing excess elements or by appending copies of a value to the back.
1795 /// #![feature(deque_extras)]
1797 /// use std::collections::VecDeque;
1799 /// let mut buf = VecDeque::new();
1800 /// buf.push_back(5);
1801 /// buf.push_back(10);
1802 /// buf.push_back(15);
1803 /// buf.resize(2, 0);
1804 /// buf.resize(6, 20);
1805 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
1806 /// assert_eq!(a, b);
1809 #[unstable(feature = "deque_extras",
1810 reason = "matches collection reform specification; waiting on panic semantics",
1812 pub fn resize(&mut self, new_len: usize, value: T) {
1813 let len = self.len();
1816 self.extend(repeat(value).take(new_len - len))
1818 self.truncate(new_len);
1823 /// Returns the index in the underlying buffer for a given logical element index.
1825 fn wrap_index(index: usize, size: usize) -> usize {
1826 // size is always a power of 2
1827 debug_assert!(size.is_power_of_two());
1831 /// Calculate the number of elements left to be read in the buffer
1833 fn count(tail: usize, head: usize, size: usize) -> usize {
1834 // size is always a power of 2
1835 (head.wrapping_sub(tail)) & (size - 1)
1838 /// `VecDeque` iterator.
1839 #[stable(feature = "rust1", since = "1.0.0")]
1840 pub struct Iter<'a, T: 'a> {
1846 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 impl<'a, T> Clone for Iter<'a, T> {
1849 fn clone(&self) -> Iter<'a, T> {
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 impl<'a, T> Iterator for Iter<'a, T> {
1863 fn next(&mut self) -> Option<&'a T> {
1864 if self.tail == self.head {
1867 let tail = self.tail;
1868 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1869 unsafe { Some(self.ring.get_unchecked(tail)) }
1873 fn size_hint(&self) -> (usize, Option<usize>) {
1874 let len = count(self.tail, self.head, self.ring.len());
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1882 fn next_back(&mut self) -> Option<&'a T> {
1883 if self.tail == self.head {
1886 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1887 unsafe { Some(self.ring.get_unchecked(self.head)) }
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1894 /// `VecDeque` mutable iterator.
1895 #[stable(feature = "rust1", since = "1.0.0")]
1896 pub struct IterMut<'a, T: 'a> {
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<'a, T> Iterator for IterMut<'a, T> {
1904 type Item = &'a mut T;
1907 fn next(&mut self) -> Option<&'a mut T> {
1908 if self.tail == self.head {
1911 let tail = self.tail;
1912 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1915 let elem = self.ring.get_unchecked_mut(tail);
1916 Some(&mut *(elem as *mut _))
1921 fn size_hint(&self) -> (usize, Option<usize>) {
1922 let len = count(self.tail, self.head, self.ring.len());
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1930 fn next_back(&mut self) -> Option<&'a mut T> {
1931 if self.tail == self.head {
1934 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1937 let elem = self.ring.get_unchecked_mut(self.head);
1938 Some(&mut *(elem as *mut _))
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1946 /// A by-value VecDeque iterator
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 pub struct IntoIter<T> {
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 impl<T> Iterator for IntoIter<T> {
1958 fn next(&mut self) -> Option<T> {
1959 self.inner.pop_front()
1963 fn size_hint(&self) -> (usize, Option<usize>) {
1964 let len = self.inner.len();
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl<T> DoubleEndedIterator for IntoIter<T> {
1972 fn next_back(&mut self) -> Option<T> {
1973 self.inner.pop_back()
1977 #[stable(feature = "rust1", since = "1.0.0")]
1978 impl<T> ExactSizeIterator for IntoIter<T> {}
1980 /// A draining VecDeque iterator
1981 #[stable(feature = "drain", since = "1.6.0")]
1982 pub struct Drain<'a, T: 'a> {
1986 deque: Shared<VecDeque<T>>,
1989 #[stable(feature = "drain", since = "1.6.0")]
1990 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1991 #[stable(feature = "drain", since = "1.6.0")]
1992 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 impl<'a, T: 'a> Drop for Drain<'a, T> {
1996 fn drop(&mut self) {
1997 for _ in self.by_ref() {}
1999 let source_deque = unsafe { &mut **self.deque };
2001 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2004 // [. . . o o x x o o . . .]
2006 let orig_tail = source_deque.tail;
2007 let drain_tail = source_deque.head;
2008 let drain_head = self.after_tail;
2009 let orig_head = self.after_head;
2011 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2012 let head_len = count(drain_head, orig_head, source_deque.cap());
2014 // Restore the original head value
2015 source_deque.head = orig_head;
2017 match (tail_len, head_len) {
2019 source_deque.head = 0;
2020 source_deque.tail = 0;
2023 source_deque.tail = drain_head;
2026 source_deque.head = drain_tail;
2030 if tail_len <= head_len {
2031 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2032 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2034 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2035 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 impl<'a, T: 'a> Iterator for Drain<'a, T> {
2048 fn next(&mut self) -> Option<T> {
2049 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2053 fn size_hint(&self) -> (usize, Option<usize>) {
2054 self.iter.size_hint()
2058 #[stable(feature = "rust1", since = "1.0.0")]
2059 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
2061 fn next_back(&mut self) -> Option<T> {
2062 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 impl<A: PartialEq> PartialEq for VecDeque<A> {
2071 fn eq(&self, other: &VecDeque<A>) -> bool {
2072 if self.len() != other.len() {
2075 let (sa, sb) = self.as_slices();
2076 let (oa, ob) = other.as_slices();
2077 if sa.len() == oa.len() {
2078 sa == oa && sb == ob
2079 } else if sa.len() < oa.len() {
2080 // Always divisible in three sections, for example:
2081 // self: [a b c|d e f]
2082 // other: [0 1 2 3|4 5]
2083 // front = 3, mid = 1,
2084 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2085 let front = sa.len();
2086 let mid = oa.len() - front;
2088 let (oa_front, oa_mid) = oa.split_at(front);
2089 let (sb_mid, sb_back) = sb.split_at(mid);
2090 debug_assert_eq!(sa.len(), oa_front.len());
2091 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2092 debug_assert_eq!(sb_back.len(), ob.len());
2093 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2095 let front = oa.len();
2096 let mid = sa.len() - front;
2098 let (sa_front, sa_mid) = sa.split_at(front);
2099 let (ob_mid, ob_back) = ob.split_at(mid);
2100 debug_assert_eq!(sa_front.len(), oa.len());
2101 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2102 debug_assert_eq!(sb.len(), ob_back.len());
2103 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 impl<A: Eq> Eq for VecDeque<A> {}
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2113 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2114 self.iter().partial_cmp(other.iter())
2118 #[stable(feature = "rust1", since = "1.0.0")]
2119 impl<A: Ord> Ord for VecDeque<A> {
2121 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2122 self.iter().cmp(other.iter())
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 impl<A: Hash> Hash for VecDeque<A> {
2128 fn hash<H: Hasher>(&self, state: &mut H) {
2129 self.len().hash(state);
2130 let (a, b) = self.as_slices();
2131 Hash::hash_slice(a, state);
2132 Hash::hash_slice(b, state);
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 impl<A> Index<usize> for VecDeque<A> {
2141 fn index(&self, index: usize) -> &A {
2142 self.get(index).expect("Out of bounds access")
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 impl<A> IndexMut<usize> for VecDeque<A> {
2149 fn index_mut(&mut self, index: usize) -> &mut A {
2150 self.get_mut(index).expect("Out of bounds access")
2154 #[stable(feature = "rust1", since = "1.0.0")]
2155 impl<A> FromIterator<A> for VecDeque<A> {
2156 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2157 let iterator = iter.into_iter();
2158 let (lower, _) = iterator.size_hint();
2159 let mut deq = VecDeque::with_capacity(lower);
2160 deq.extend(iterator);
2165 #[stable(feature = "rust1", since = "1.0.0")]
2166 impl<T> IntoIterator for VecDeque<T> {
2168 type IntoIter = IntoIter<T>;
2170 /// Consumes the list into a front-to-back iterator yielding elements by
2172 fn into_iter(self) -> IntoIter<T> {
2173 IntoIter { inner: self }
2177 #[stable(feature = "rust1", since = "1.0.0")]
2178 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2180 type IntoIter = Iter<'a, T>;
2182 fn into_iter(self) -> Iter<'a, T> {
2187 #[stable(feature = "rust1", since = "1.0.0")]
2188 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2189 type Item = &'a mut T;
2190 type IntoIter = IterMut<'a, T>;
2192 fn into_iter(mut self) -> IterMut<'a, T> {
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 impl<A> Extend<A> for VecDeque<A> {
2199 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2201 self.push_back(elt);
2206 #[stable(feature = "extend_ref", since = "1.2.0")]
2207 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2208 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2209 self.extend(iter.into_iter().cloned());
2213 #[stable(feature = "rust1", since = "1.0.0")]
2214 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2215 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2216 f.debug_list().entries(self).finish()
2220 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2221 impl<T> From<Vec<T>> for VecDeque<T> {
2222 fn from(mut other: Vec<T>) -> Self {
2224 let other_buf = other.as_mut_ptr();
2225 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2226 let len = other.len();
2229 // We need to extend the buf if it's not a power of two, too small
2230 // or doesn't have at least one free space
2231 if !buf.cap().is_power_of_two()
2232 || (buf.cap() < (MINIMUM_CAPACITY + 1))
2233 || (buf.cap() == len)
2235 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2236 buf.reserve_exact(len, cap - len);
2248 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2249 impl<T> From<VecDeque<T>> for Vec<T> {
2250 fn from(other: VecDeque<T>) -> Self {
2252 let buf = other.buf.ptr();
2253 let len = other.len();
2254 let tail = other.tail;
2255 let head = other.head;
2256 let cap = other.cap();
2258 // Need to move the ring to the front of the buffer, as vec will expect this.
2259 if other.is_contiguous() {
2260 ptr::copy(buf.offset(tail as isize), buf, len);
2262 if (tail - head) >= cmp::min((cap - tail), head) {
2263 // There is enough free space in the centre for the shortest block so we can
2264 // do this in at most three copy moves.
2265 if (cap - tail) > head {
2266 // right hand block is the long one; move that enough for the left
2268 buf.offset(tail as isize),
2269 buf.offset((tail - head) as isize),
2271 // copy left in the end
2272 ptr::copy(buf, buf.offset((cap - head) as isize), head);
2273 // shift the new thing to the start
2274 ptr::copy(buf.offset((tail-head) as isize), buf, len);
2276 // left hand block is the long one, we can do it in two!
2277 ptr::copy(buf, buf.offset((cap-tail) as isize), head);
2278 ptr::copy(buf.offset(tail as isize), buf, cap-tail);
2281 // Need to use N swaps to move the ring
2282 // We can use the space at the end of the ring as a temp store
2284 let mut left_edge: usize = 0;
2285 let mut right_edge: usize = tail;
2287 // The general problem looks like this
2288 // GHIJKLM...ABCDEF - before any swaps
2289 // ABCDEFM...GHIJKL - after 1 pass of swaps
2290 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2291 // - then restart the algorithm with a new (smaller) store
2292 // Sometimes the temp store is reached when the right edge is at the end
2293 // of the buffer - this means we've hit the right order with fewer swaps!
2296 // ABCDEF.. - after four only swaps we've finished
2298 while left_edge < len && right_edge != cap {
2299 let mut right_offset = 0;
2300 for i in left_edge..right_edge {
2301 right_offset = (i - left_edge) % (cap - right_edge);
2302 let src: isize = (right_edge + right_offset) as isize;
2303 ptr::swap(buf.offset(i as isize), buf.offset(src));
2305 let n_ops = right_edge - left_edge;
2307 right_edge += right_offset + 1;
2313 let out = Vec::from_raw_parts(buf, len, cap);
2322 use core::iter::Iterator;
2323 use core::option::Option::Some;
2327 use super::VecDeque;
2330 fn bench_push_back_100(b: &mut test::Bencher) {
2331 let mut deq = VecDeque::with_capacity(101);
2342 fn bench_push_front_100(b: &mut test::Bencher) {
2343 let mut deq = VecDeque::with_capacity(101);
2354 fn bench_pop_back_100(b: &mut test::Bencher) {
2355 let mut deq = VecDeque::<i32>::with_capacity(101);
2360 while !deq.is_empty() {
2361 test::black_box(deq.pop_back());
2367 fn bench_pop_front_100(b: &mut test::Bencher) {
2368 let mut deq = VecDeque::<i32>::with_capacity(101);
2373 while !deq.is_empty() {
2374 test::black_box(deq.pop_front());
2380 fn test_swap_front_back_remove() {
2381 fn test(back: bool) {
2382 // This test checks that every single combination of tail position and length is tested.
2383 // Capacity 15 should be large enough to cover every case.
2384 let mut tester = VecDeque::with_capacity(15);
2385 let usable_cap = tester.capacity();
2386 let final_len = usable_cap / 2;
2388 for len in 0..final_len {
2389 let expected = if back {
2392 (0..len).rev().collect()
2394 for tail_pos in 0..usable_cap {
2395 tester.tail = tail_pos;
2396 tester.head = tail_pos;
2398 for i in 0..len * 2 {
2399 tester.push_front(i);
2402 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2405 for i in 0..len * 2 {
2406 tester.push_back(i);
2409 let idx = tester.len() - 1 - i;
2410 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2413 assert!(tester.tail < tester.cap());
2414 assert!(tester.head < tester.cap());
2415 assert_eq!(tester, expected);
2425 // This test checks that every single combination of tail position, length, and
2426 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2428 let mut tester = VecDeque::with_capacity(15);
2429 // can't guarantee we got 15, so have to get what we got.
2430 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2431 // this test isn't covering what it wants to
2432 let cap = tester.capacity();
2435 // len is the length *after* insertion
2437 // 0, 1, 2, .., len - 1
2438 let expected = (0..).take(len).collect();
2439 for tail_pos in 0..cap {
2440 for to_insert in 0..len {
2441 tester.tail = tail_pos;
2442 tester.head = tail_pos;
2445 tester.push_back(i);
2448 tester.insert(to_insert, to_insert);
2449 assert!(tester.tail < tester.cap());
2450 assert!(tester.head < tester.cap());
2451 assert_eq!(tester, expected);
2459 // This test checks that every single combination of tail position, length, and
2460 // removal position is tested. Capacity 15 should be large enough to cover every case.
2462 let mut tester = VecDeque::with_capacity(15);
2463 // can't guarantee we got 15, so have to get what we got.
2464 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2465 // this test isn't covering what it wants to
2466 let cap = tester.capacity();
2468 // len is the length *after* removal
2469 for len in 0..cap - 1 {
2470 // 0, 1, 2, .., len - 1
2471 let expected = (0..).take(len).collect();
2472 for tail_pos in 0..cap {
2473 for to_remove in 0..len + 1 {
2474 tester.tail = tail_pos;
2475 tester.head = tail_pos;
2478 tester.push_back(1234);
2480 tester.push_back(i);
2482 if to_remove == len {
2483 tester.push_back(1234);
2485 tester.remove(to_remove);
2486 assert!(tester.tail < tester.cap());
2487 assert!(tester.head < tester.cap());
2488 assert_eq!(tester, expected);
2496 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2498 let cap = tester.capacity();
2499 for len in 0..cap + 1 {
2500 for tail in 0..cap + 1 {
2501 for drain_start in 0..len + 1 {
2502 for drain_end in drain_start..len + 1 {
2506 tester.push_back(i);
2509 // Check that we drain the correct values
2510 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2511 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2512 assert_eq!(drained, drained_expected);
2514 // We shouldn't have changed the capacity or made the
2515 // head or tail out of bounds
2516 assert_eq!(tester.capacity(), cap);
2517 assert!(tester.tail < tester.cap());
2518 assert!(tester.head < tester.cap());
2520 // We should see the correct values in the VecDeque
2521 let expected: VecDeque<_> = (0..drain_start)
2522 .chain(drain_end..len)
2524 assert_eq!(expected, tester);
2532 fn test_shrink_to_fit() {
2533 // This test checks that every single combination of head and tail position,
2534 // is tested. Capacity 15 should be large enough to cover every case.
2536 let mut tester = VecDeque::with_capacity(15);
2537 // can't guarantee we got 15, so have to get what we got.
2538 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2539 // this test isn't covering what it wants to
2540 let cap = tester.capacity();
2542 let max_cap = tester.capacity();
2544 for len in 0..cap + 1 {
2545 // 0, 1, 2, .., len - 1
2546 let expected = (0..).take(len).collect();
2547 for tail_pos in 0..max_cap + 1 {
2548 tester.tail = tail_pos;
2549 tester.head = tail_pos;
2552 tester.push_back(i);
2554 tester.shrink_to_fit();
2555 assert!(tester.capacity() <= cap);
2556 assert!(tester.tail < tester.cap());
2557 assert!(tester.head < tester.cap());
2558 assert_eq!(tester, expected);
2564 fn test_split_off() {
2565 // This test checks that every single combination of tail position, length, and
2566 // split position is tested. Capacity 15 should be large enough to cover every case.
2568 let mut tester = VecDeque::with_capacity(15);
2569 // can't guarantee we got 15, so have to get what we got.
2570 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2571 // this test isn't covering what it wants to
2572 let cap = tester.capacity();
2574 // len is the length *before* splitting
2576 // index to split at
2577 for at in 0..len + 1 {
2578 // 0, 1, 2, .., at - 1 (may be empty)
2579 let expected_self = (0..).take(at).collect();
2580 // at, at + 1, .., len - 1 (may be empty)
2581 let expected_other = (at..).take(len - at).collect();
2583 for tail_pos in 0..cap {
2584 tester.tail = tail_pos;
2585 tester.head = tail_pos;
2587 tester.push_back(i);
2589 let result = tester.split_off(at);
2590 assert!(tester.tail < tester.cap());
2591 assert!(tester.head < tester.cap());
2592 assert!(result.tail < result.cap());
2593 assert!(result.head < result.cap());
2594 assert_eq!(tester, expected_self);
2595 assert_eq!(result, expected_other);
2602 fn test_from_vec() {
2603 use super::super::vec::Vec;
2605 for len in 0..cap + 1 {
2606 let mut vec = Vec::with_capacity(cap);
2609 let vd = VecDeque::from(vec.clone());
2610 assert!(vd.cap().is_power_of_two());
2611 assert_eq!(vd.len(), vec.len());
2612 assert!(vd.into_iter().eq(vec));
2618 fn test_vec_from_vecdeque() {
2619 use super::super::vec::Vec;
2621 fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
2622 let mut vd = VecDeque::with_capacity(cap);
2623 for _ in 0..offset {
2629 let vec: Vec<_> = Vec::from(vd.clone());
2630 assert_eq!(vec.len(), vd.len());
2631 assert!(vec.into_iter().eq(vd));
2634 for cap_pwr in 0..7 {
2635 // Make capacity as a (2^x)-1, so that the ring size is 2^x
2636 let cap = (2i32.pow(cap_pwr) - 1) as usize;
2638 // In these cases there is enough free space to solve it with copies
2639 for len in 0..((cap+1)/2) {
2640 // Test contiguous cases
2641 for offset in 0..(cap-len) {
2642 create_vec_and_test_convert(cap, offset, len)
2645 // Test cases where block at end of buffer is bigger than block at start
2646 for offset in (cap-len)..(cap-(len/2)) {
2647 create_vec_and_test_convert(cap, offset, len)
2650 // Test cases where block at start of buffer is bigger than block at end
2651 for offset in (cap-(len/2))..cap {
2652 create_vec_and_test_convert(cap, offset, len)
2656 // Now there's not (necessarily) space to straighten the ring with simple copies,
2657 // the ring will use swapping when:
2658 // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
2659 // right block size > free space && left block size > free space
2660 for len in ((cap+1)/2)..cap {
2661 // Test contiguous cases
2662 for offset in 0..(cap-len) {
2663 create_vec_and_test_convert(cap, offset, len)
2666 // Test cases where block at end of buffer is bigger than block at start
2667 for offset in (cap-len)..(cap-(len/2)) {
2668 create_vec_and_test_convert(cap, offset, len)
2671 // Test cases where block at start of buffer is bigger than block at end
2672 for offset in (cap-(len/2))..cap {
2673 create_vec_and_test_convert(cap, offset, len)