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 /// #![feature(vec_deque_contains)]
944 /// use std::collections::VecDeque;
946 /// let mut vector: VecDeque<u32> = VecDeque::new();
948 /// vector.push_back(0);
949 /// vector.push_back(1);
951 /// assert_eq!(vector.contains(&1), true);
952 /// assert_eq!(vector.contains(&10), false);
954 #[unstable(feature = "vec_deque_contains", reason = "recently added",
956 pub fn contains(&self, x: &T) -> bool
957 where T: PartialEq<T>
959 let (a, b) = self.as_slices();
960 a.contains(x) || b.contains(x)
963 /// Provides a reference to the front element, or `None` if the sequence is
969 /// use std::collections::VecDeque;
971 /// let mut d = VecDeque::new();
972 /// assert_eq!(d.front(), None);
976 /// assert_eq!(d.front(), Some(&1));
978 #[stable(feature = "rust1", since = "1.0.0")]
979 pub fn front(&self) -> Option<&T> {
980 if !self.is_empty() {
987 /// Provides a mutable reference to the front element, or `None` if the
988 /// sequence is empty.
993 /// use std::collections::VecDeque;
995 /// let mut d = VecDeque::new();
996 /// assert_eq!(d.front_mut(), None);
1000 /// match d.front_mut() {
1001 /// Some(x) => *x = 9,
1004 /// assert_eq!(d.front(), Some(&9));
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub fn front_mut(&mut self) -> Option<&mut T> {
1008 if !self.is_empty() {
1015 /// Provides a reference to the back element, or `None` if the sequence is
1021 /// use std::collections::VecDeque;
1023 /// let mut d = VecDeque::new();
1024 /// assert_eq!(d.back(), None);
1028 /// assert_eq!(d.back(), Some(&2));
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 pub fn back(&self) -> Option<&T> {
1032 if !self.is_empty() {
1033 Some(&self[self.len() - 1])
1039 /// Provides a mutable reference to the back element, or `None` if the
1040 /// sequence is empty.
1045 /// use std::collections::VecDeque;
1047 /// let mut d = VecDeque::new();
1048 /// assert_eq!(d.back(), None);
1052 /// match d.back_mut() {
1053 /// Some(x) => *x = 9,
1056 /// assert_eq!(d.back(), Some(&9));
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 pub fn back_mut(&mut self) -> Option<&mut T> {
1060 let len = self.len();
1061 if !self.is_empty() {
1062 Some(&mut self[len - 1])
1068 /// Removes the first element and returns it, or `None` if the sequence is
1074 /// use std::collections::VecDeque;
1076 /// let mut d = VecDeque::new();
1080 /// assert_eq!(d.pop_front(), Some(1));
1081 /// assert_eq!(d.pop_front(), Some(2));
1082 /// assert_eq!(d.pop_front(), None);
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 pub fn pop_front(&mut self) -> Option<T> {
1086 if self.is_empty() {
1089 let tail = self.tail;
1090 self.tail = self.wrap_add(self.tail, 1);
1091 unsafe { Some(self.buffer_read(tail)) }
1095 /// Inserts an element first in the sequence.
1100 /// use std::collections::VecDeque;
1102 /// let mut d = VecDeque::new();
1103 /// d.push_front(1);
1104 /// d.push_front(2);
1105 /// assert_eq!(d.front(), Some(&2));
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 pub fn push_front(&mut self, value: T) {
1110 let old_cap = self.cap();
1113 self.handle_cap_increase(old_cap);
1115 debug_assert!(!self.is_full());
1118 self.tail = self.wrap_sub(self.tail, 1);
1119 let tail = self.tail;
1121 self.buffer_write(tail, value);
1125 /// Appends an element to the back of a buffer
1130 /// use std::collections::VecDeque;
1132 /// let mut buf = VecDeque::new();
1133 /// buf.push_back(1);
1134 /// buf.push_back(3);
1135 /// assert_eq!(3, *buf.back().unwrap());
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 pub fn push_back(&mut self, value: T) {
1140 let old_cap = self.cap();
1143 self.handle_cap_increase(old_cap);
1145 debug_assert!(!self.is_full());
1148 let head = self.head;
1149 self.head = self.wrap_add(self.head, 1);
1150 unsafe { self.buffer_write(head, value) }
1153 /// Removes the last element from a buffer and returns it, or `None` if
1159 /// use std::collections::VecDeque;
1161 /// let mut buf = VecDeque::new();
1162 /// assert_eq!(buf.pop_back(), None);
1163 /// buf.push_back(1);
1164 /// buf.push_back(3);
1165 /// assert_eq!(buf.pop_back(), Some(3));
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 pub fn pop_back(&mut self) -> Option<T> {
1169 if self.is_empty() {
1172 self.head = self.wrap_sub(self.head, 1);
1173 let head = self.head;
1174 unsafe { Some(self.buffer_read(head)) }
1179 fn is_contiguous(&self) -> bool {
1180 self.tail <= self.head
1183 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1186 /// This does not preserve ordering, but is O(1).
1188 /// Returns `None` if `index` is out of bounds.
1190 /// Element at index 0 is the front of the queue.
1195 /// use std::collections::VecDeque;
1197 /// let mut buf = VecDeque::new();
1198 /// assert_eq!(buf.swap_remove_back(0), None);
1199 /// buf.push_back(1);
1200 /// buf.push_back(2);
1201 /// buf.push_back(3);
1203 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1204 /// assert_eq!(buf.len(), 2);
1205 /// assert_eq!(buf[0], 3);
1206 /// assert_eq!(buf[1], 2);
1208 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1209 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1210 let length = self.len();
1211 if length > 0 && index < length - 1 {
1212 self.swap(index, length - 1);
1213 } else if index >= length {
1219 /// Removes an element from anywhere in the `VecDeque` and returns it,
1220 /// replacing it with the first element.
1222 /// This does not preserve ordering, but is O(1).
1224 /// Returns `None` if `index` is out of bounds.
1226 /// Element at index 0 is the front of the queue.
1231 /// use std::collections::VecDeque;
1233 /// let mut buf = VecDeque::new();
1234 /// assert_eq!(buf.swap_remove_front(0), None);
1235 /// buf.push_back(1);
1236 /// buf.push_back(2);
1237 /// buf.push_back(3);
1239 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1240 /// assert_eq!(buf.len(), 2);
1241 /// assert_eq!(buf[0], 2);
1242 /// assert_eq!(buf[1], 1);
1244 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1245 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1246 let length = self.len();
1247 if length > 0 && index < length && index != 0 {
1248 self.swap(index, 0);
1249 } else if index >= length {
1255 /// Inserts an element at `index` within the `VecDeque`. Whichever
1256 /// end is closer to the insertion point will be moved to make room,
1257 /// and all the affected elements will be moved to new positions.
1259 /// Element at index 0 is the front of the queue.
1263 /// Panics if `index` is greater than `VecDeque`'s length
1267 /// use std::collections::VecDeque;
1269 /// let mut buf = VecDeque::new();
1270 /// buf.push_back(10);
1271 /// buf.push_back(12);
1272 /// buf.insert(1, 11);
1273 /// assert_eq!(Some(&11), buf.get(1));
1275 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1276 pub fn insert(&mut self, index: usize, value: T) {
1277 assert!(index <= self.len(), "index out of bounds");
1279 let old_cap = self.cap();
1282 self.handle_cap_increase(old_cap);
1284 debug_assert!(!self.is_full());
1287 // Move the least number of elements in the ring buffer and insert
1290 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1292 // There are three main cases:
1293 // Elements are contiguous
1294 // - special case when tail is 0
1295 // Elements are discontiguous and the insert is in the tail section
1296 // Elements are discontiguous and the insert is in the head section
1298 // For each of those there are two more cases:
1299 // Insert is closer to tail
1300 // Insert is closer to head
1302 // Key: H - self.head
1304 // o - Valid element
1305 // I - Insertion element
1306 // A - The element that should be after the insertion point
1307 // M - Indicates element was moved
1309 let idx = self.wrap_add(self.tail, index);
1311 let distance_to_tail = index;
1312 let distance_to_head = self.len() - index;
1314 let contiguous = self.is_contiguous();
1317 distance_to_tail <= distance_to_head,
1319 (true, true, _) if index == 0 => {
1324 // [A o o o o o o . . . . . . . . .]
1327 // [A o o o o o o o . . . . . I]
1330 self.tail = self.wrap_sub(self.tail, 1);
1332 (true, true, _) => {
1334 // contiguous, insert closer to tail:
1337 // [. . . o o A o o o o . . . . . .]
1340 // [. . o o I A o o o o . . . . . .]
1343 // contiguous, insert closer to tail and tail is 0:
1347 // [o o A o o o o . . . . . . . . .]
1350 // [o I A o o o o o . . . . . . . o]
1353 let new_tail = self.wrap_sub(self.tail, 1);
1355 self.copy(new_tail, self.tail, 1);
1356 // Already moved the tail, so we only copy `index - 1` elements.
1357 self.copy(self.tail, self.tail + 1, index - 1);
1359 self.tail = new_tail;
1362 (true, false, _) => {
1364 // contiguous, insert closer to head:
1367 // [. . . o o o o A o o . . . . . .]
1370 // [. . . o o o o I A o o . . . . .]
1373 self.copy(idx + 1, idx, self.head - idx);
1374 self.head = self.wrap_add(self.head, 1);
1377 (false, true, true) => {
1379 // discontiguous, insert closer to tail, tail section:
1382 // [o o o o o o . . . . . o o A o o]
1385 // [o o o o o o . . . . o o I A o o]
1388 self.copy(self.tail - 1, self.tail, index);
1392 (false, false, true) => {
1394 // discontiguous, insert closer to head, tail section:
1397 // [o o . . . . . . . o o o o o A o]
1400 // [o o o . . . . . . o o o o o I A]
1403 // copy elements up to new head
1404 self.copy(1, 0, self.head);
1406 // copy last element into empty spot at bottom of buffer
1407 self.copy(0, self.cap() - 1, 1);
1409 // move elements from idx to end forward not including ^ element
1410 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1415 (false, true, false) if idx == 0 => {
1417 // discontiguous, insert is closer to tail, head section,
1418 // and is at index zero in the internal buffer:
1421 // [A o o o o o o o o o . . . o o o]
1424 // [A o o o o o o o o o . . o o o I]
1427 // copy elements up to new tail
1428 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1430 // copy last element into empty spot at bottom of buffer
1431 self.copy(self.cap() - 1, 0, 1);
1436 (false, true, false) => {
1438 // discontiguous, insert closer to tail, head section:
1441 // [o o o A o o o o o o . . . o o o]
1444 // [o o I A o o o o o o . . o o o o]
1447 // copy elements up to new tail
1448 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1450 // copy last element into empty spot at bottom of buffer
1451 self.copy(self.cap() - 1, 0, 1);
1453 // move elements from idx-1 to end forward not including ^ element
1454 self.copy(0, 1, idx - 1);
1459 (false, false, false) => {
1461 // discontiguous, insert closer to head, head section:
1464 // [o o o o A o o . . . . . . o o o]
1467 // [o o o o I A o o . . . . . o o o]
1470 self.copy(idx + 1, idx, self.head - idx);
1476 // tail might've been changed so we need to recalculate
1477 let new_idx = self.wrap_add(self.tail, index);
1479 self.buffer_write(new_idx, value);
1483 /// Removes and returns the element at `index` from the `VecDeque`.
1484 /// Whichever end is closer to the removal point will be moved to make
1485 /// room, and all the affected elements will be moved to new positions.
1486 /// Returns `None` if `index` is out of bounds.
1488 /// Element at index 0 is the front of the queue.
1493 /// use std::collections::VecDeque;
1495 /// let mut buf = VecDeque::new();
1496 /// buf.push_back(1);
1497 /// buf.push_back(2);
1498 /// buf.push_back(3);
1500 /// assert_eq!(buf.remove(1), Some(2));
1501 /// assert_eq!(buf.get(1), Some(&3));
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 pub fn remove(&mut self, index: usize) -> Option<T> {
1505 if self.is_empty() || self.len() <= index {
1509 // There are three main cases:
1510 // Elements are contiguous
1511 // Elements are discontiguous and the removal is in the tail section
1512 // Elements are discontiguous and the removal is in the head section
1513 // - special case when elements are technically contiguous,
1514 // but self.head = 0
1516 // For each of those there are two more cases:
1517 // Insert is closer to tail
1518 // Insert is closer to head
1520 // Key: H - self.head
1522 // o - Valid element
1523 // x - Element marked for removal
1524 // R - Indicates element that is being removed
1525 // M - Indicates element was moved
1527 let idx = self.wrap_add(self.tail, index);
1529 let elem = unsafe { Some(self.buffer_read(idx)) };
1531 let distance_to_tail = index;
1532 let distance_to_head = self.len() - index;
1534 let contiguous = self.is_contiguous();
1537 distance_to_tail <= distance_to_head,
1539 (true, true, _) => {
1541 // contiguous, remove closer to tail:
1544 // [. . . o o x o o o o . . . . . .]
1547 // [. . . . o o o o o o . . . . . .]
1550 self.copy(self.tail + 1, self.tail, index);
1554 (true, false, _) => {
1556 // contiguous, remove closer to head:
1559 // [. . . o o o o x o o . . . . . .]
1562 // [. . . o o o o o o . . . . . . .]
1565 self.copy(idx, idx + 1, self.head - idx - 1);
1569 (false, true, true) => {
1571 // discontiguous, remove closer to tail, tail section:
1574 // [o o o o o o . . . . . o o x o o]
1577 // [o o o o o o . . . . . . o o o o]
1580 self.copy(self.tail + 1, self.tail, index);
1581 self.tail = self.wrap_add(self.tail, 1);
1584 (false, false, false) => {
1586 // discontiguous, remove closer to head, head section:
1589 // [o o o o x o o . . . . . . o o o]
1592 // [o o o o o o . . . . . . . o o o]
1595 self.copy(idx, idx + 1, self.head - idx - 1);
1599 (false, false, true) => {
1601 // discontiguous, remove closer to head, tail section:
1604 // [o o o . . . . . . o o o o o x o]
1607 // [o o . . . . . . . o o o o o o o]
1610 // or quasi-discontiguous, remove next to head, tail section:
1613 // [. . . . . . . . . o o o o o x o]
1616 // [. . . . . . . . . o o o o o o .]
1619 // draw in elements in the tail section
1620 self.copy(idx, idx + 1, self.cap() - idx - 1);
1622 // Prevents underflow.
1624 // copy first element into empty spot
1625 self.copy(self.cap() - 1, 0, 1);
1627 // move elements in the head section backwards
1628 self.copy(0, 1, self.head - 1);
1631 self.head = self.wrap_sub(self.head, 1);
1634 (false, true, false) => {
1636 // discontiguous, remove closer to tail, head section:
1639 // [o o x o o o o o o o . . . o o o]
1642 // [o o o o o o o o o o . . . . o o]
1645 // draw in elements up to idx
1646 self.copy(1, 0, idx);
1648 // copy last element into empty spot
1649 self.copy(0, self.cap() - 1, 1);
1651 // move elements from tail to end forward, excluding the last one
1652 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1654 self.tail = self.wrap_add(self.tail, 1);
1662 /// Splits the collection into two at the given index.
1664 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1665 /// and the returned `Self` contains elements `[at, len)`.
1667 /// Note that the capacity of `self` does not change.
1669 /// Element at index 0 is the front of the queue.
1673 /// Panics if `at > len`
1678 /// use std::collections::VecDeque;
1680 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1681 /// let buf2 = buf.split_off(1);
1682 /// // buf = [1], buf2 = [2, 3]
1683 /// assert_eq!(buf.len(), 1);
1684 /// assert_eq!(buf2.len(), 2);
1687 #[stable(feature = "split_off", since = "1.4.0")]
1688 pub fn split_off(&mut self, at: usize) -> Self {
1689 let len = self.len();
1690 assert!(at <= len, "`at` out of bounds");
1692 let other_len = len - at;
1693 let mut other = VecDeque::with_capacity(other_len);
1696 let (first_half, second_half) = self.as_slices();
1698 let first_len = first_half.len();
1699 let second_len = second_half.len();
1701 // `at` lies in the first half.
1702 let amount_in_first = first_len - at;
1704 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1708 // just take all of the second half.
1709 ptr::copy_nonoverlapping(second_half.as_ptr(),
1710 other.ptr().offset(amount_in_first as isize),
1713 // `at` lies in the second half, need to factor in the elements we skipped
1714 // in the first half.
1715 let offset = at - first_len;
1716 let amount_in_second = second_len - offset;
1717 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1723 // Cleanup where the ends of the buffers are
1724 self.head = self.wrap_sub(self.head, other_len);
1725 other.head = other.wrap_index(other_len);
1730 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1734 /// Panics if the new number of elements in self overflows a `usize`.
1739 /// use std::collections::VecDeque;
1741 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1742 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
1743 /// buf.append(&mut buf2);
1744 /// assert_eq!(buf.len(), 6);
1745 /// assert_eq!(buf2.len(), 0);
1748 #[stable(feature = "append", since = "1.4.0")]
1749 pub fn append(&mut self, other: &mut Self) {
1751 self.extend(other.drain(..));
1754 /// Retains only the elements specified by the predicate.
1756 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1757 /// This method operates in place and preserves the order of the retained
1763 /// use std::collections::VecDeque;
1765 /// let mut buf = VecDeque::new();
1766 /// buf.extend(1..5);
1767 /// buf.retain(|&x| x%2 == 0);
1769 /// let v: Vec<_> = buf.into_iter().collect();
1770 /// assert_eq!(&v[..], &[2, 4]);
1772 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1773 pub fn retain<F>(&mut self, mut f: F)
1774 where F: FnMut(&T) -> bool
1776 let len = self.len();
1782 self.swap(i - del, i);
1786 self.truncate(len - del);
1791 impl<T: Clone> VecDeque<T> {
1792 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1793 /// either by removing excess elements or by appending copies of a value to the back.
1798 /// #![feature(deque_extras)]
1800 /// use std::collections::VecDeque;
1802 /// let mut buf = VecDeque::new();
1803 /// buf.push_back(5);
1804 /// buf.push_back(10);
1805 /// buf.push_back(15);
1806 /// buf.resize(2, 0);
1807 /// buf.resize(6, 20);
1808 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
1809 /// assert_eq!(a, b);
1812 #[unstable(feature = "deque_extras",
1813 reason = "matches collection reform specification; waiting on panic semantics",
1815 pub fn resize(&mut self, new_len: usize, value: T) {
1816 let len = self.len();
1819 self.extend(repeat(value).take(new_len - len))
1821 self.truncate(new_len);
1826 /// Returns the index in the underlying buffer for a given logical element index.
1828 fn wrap_index(index: usize, size: usize) -> usize {
1829 // size is always a power of 2
1830 debug_assert!(size.is_power_of_two());
1834 /// Calculate the number of elements left to be read in the buffer
1836 fn count(tail: usize, head: usize, size: usize) -> usize {
1837 // size is always a power of 2
1838 (head.wrapping_sub(tail)) & (size - 1)
1841 /// `VecDeque` iterator.
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 pub struct Iter<'a, T: 'a> {
1849 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1850 #[stable(feature = "rust1", since = "1.0.0")]
1851 impl<'a, T> Clone for Iter<'a, T> {
1852 fn clone(&self) -> Iter<'a, T> {
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 impl<'a, T> Iterator for Iter<'a, T> {
1866 fn next(&mut self) -> Option<&'a T> {
1867 if self.tail == self.head {
1870 let tail = self.tail;
1871 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1872 unsafe { Some(self.ring.get_unchecked(tail)) }
1876 fn size_hint(&self) -> (usize, Option<usize>) {
1877 let len = count(self.tail, self.head, self.ring.len());
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1885 fn next_back(&mut self) -> Option<&'a T> {
1886 if self.tail == self.head {
1889 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1890 unsafe { Some(self.ring.get_unchecked(self.head)) }
1894 #[stable(feature = "rust1", since = "1.0.0")]
1895 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1897 /// `VecDeque` mutable iterator.
1898 #[stable(feature = "rust1", since = "1.0.0")]
1899 pub struct IterMut<'a, T: 'a> {
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 impl<'a, T> Iterator for IterMut<'a, T> {
1907 type Item = &'a mut T;
1910 fn next(&mut self) -> Option<&'a mut T> {
1911 if self.tail == self.head {
1914 let tail = self.tail;
1915 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1918 let elem = self.ring.get_unchecked_mut(tail);
1919 Some(&mut *(elem as *mut _))
1924 fn size_hint(&self) -> (usize, Option<usize>) {
1925 let len = count(self.tail, self.head, self.ring.len());
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1933 fn next_back(&mut self) -> Option<&'a mut T> {
1934 if self.tail == self.head {
1937 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1940 let elem = self.ring.get_unchecked_mut(self.head);
1941 Some(&mut *(elem as *mut _))
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1949 /// A by-value VecDeque iterator
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 pub struct IntoIter<T> {
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 impl<T> Iterator for IntoIter<T> {
1961 fn next(&mut self) -> Option<T> {
1962 self.inner.pop_front()
1966 fn size_hint(&self) -> (usize, Option<usize>) {
1967 let len = self.inner.len();
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 impl<T> DoubleEndedIterator for IntoIter<T> {
1975 fn next_back(&mut self) -> Option<T> {
1976 self.inner.pop_back()
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 impl<T> ExactSizeIterator for IntoIter<T> {}
1983 /// A draining VecDeque iterator
1984 #[stable(feature = "drain", since = "1.6.0")]
1985 pub struct Drain<'a, T: 'a> {
1989 deque: Shared<VecDeque<T>>,
1992 #[stable(feature = "drain", since = "1.6.0")]
1993 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1994 #[stable(feature = "drain", since = "1.6.0")]
1995 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1997 #[stable(feature = "rust1", since = "1.0.0")]
1998 impl<'a, T: 'a> Drop for Drain<'a, T> {
1999 fn drop(&mut self) {
2000 for _ in self.by_ref() {}
2002 let source_deque = unsafe { &mut **self.deque };
2004 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2007 // [. . . o o x x o o . . .]
2009 let orig_tail = source_deque.tail;
2010 let drain_tail = source_deque.head;
2011 let drain_head = self.after_tail;
2012 let orig_head = self.after_head;
2014 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2015 let head_len = count(drain_head, orig_head, source_deque.cap());
2017 // Restore the original head value
2018 source_deque.head = orig_head;
2020 match (tail_len, head_len) {
2022 source_deque.head = 0;
2023 source_deque.tail = 0;
2026 source_deque.tail = drain_head;
2029 source_deque.head = drain_tail;
2033 if tail_len <= head_len {
2034 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2035 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2037 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2038 source_deque.wrap_copy(drain_tail, drain_head, head_len);
2046 #[stable(feature = "rust1", since = "1.0.0")]
2047 impl<'a, T: 'a> Iterator for Drain<'a, T> {
2051 fn next(&mut self) -> Option<T> {
2052 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2056 fn size_hint(&self) -> (usize, Option<usize>) {
2057 self.iter.size_hint()
2061 #[stable(feature = "rust1", since = "1.0.0")]
2062 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
2064 fn next_back(&mut self) -> Option<T> {
2065 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl<A: PartialEq> PartialEq for VecDeque<A> {
2074 fn eq(&self, other: &VecDeque<A>) -> bool {
2075 if self.len() != other.len() {
2078 let (sa, sb) = self.as_slices();
2079 let (oa, ob) = other.as_slices();
2080 if sa.len() == oa.len() {
2081 sa == oa && sb == ob
2082 } else if sa.len() < oa.len() {
2083 // Always divisible in three sections, for example:
2084 // self: [a b c|d e f]
2085 // other: [0 1 2 3|4 5]
2086 // front = 3, mid = 1,
2087 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2088 let front = sa.len();
2089 let mid = oa.len() - front;
2091 let (oa_front, oa_mid) = oa.split_at(front);
2092 let (sb_mid, sb_back) = sb.split_at(mid);
2093 debug_assert_eq!(sa.len(), oa_front.len());
2094 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2095 debug_assert_eq!(sb_back.len(), ob.len());
2096 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2098 let front = oa.len();
2099 let mid = sa.len() - front;
2101 let (sa_front, sa_mid) = sa.split_at(front);
2102 let (ob_mid, ob_back) = ob.split_at(mid);
2103 debug_assert_eq!(sa_front.len(), oa.len());
2104 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2105 debug_assert_eq!(sb.len(), ob_back.len());
2106 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 impl<A: Eq> Eq for VecDeque<A> {}
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2116 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2117 self.iter().partial_cmp(other.iter())
2121 #[stable(feature = "rust1", since = "1.0.0")]
2122 impl<A: Ord> Ord for VecDeque<A> {
2124 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2125 self.iter().cmp(other.iter())
2129 #[stable(feature = "rust1", since = "1.0.0")]
2130 impl<A: Hash> Hash for VecDeque<A> {
2131 fn hash<H: Hasher>(&self, state: &mut H) {
2132 self.len().hash(state);
2133 let (a, b) = self.as_slices();
2134 Hash::hash_slice(a, state);
2135 Hash::hash_slice(b, state);
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 impl<A> Index<usize> for VecDeque<A> {
2144 fn index(&self, index: usize) -> &A {
2145 self.get(index).expect("Out of bounds access")
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 impl<A> IndexMut<usize> for VecDeque<A> {
2152 fn index_mut(&mut self, index: usize) -> &mut A {
2153 self.get_mut(index).expect("Out of bounds access")
2157 #[stable(feature = "rust1", since = "1.0.0")]
2158 impl<A> FromIterator<A> for VecDeque<A> {
2159 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2160 let iterator = iter.into_iter();
2161 let (lower, _) = iterator.size_hint();
2162 let mut deq = VecDeque::with_capacity(lower);
2163 deq.extend(iterator);
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 impl<T> IntoIterator for VecDeque<T> {
2171 type IntoIter = IntoIter<T>;
2173 /// Consumes the list into a front-to-back iterator yielding elements by
2175 fn into_iter(self) -> IntoIter<T> {
2176 IntoIter { inner: self }
2180 #[stable(feature = "rust1", since = "1.0.0")]
2181 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2183 type IntoIter = Iter<'a, T>;
2185 fn into_iter(self) -> Iter<'a, T> {
2190 #[stable(feature = "rust1", since = "1.0.0")]
2191 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2192 type Item = &'a mut T;
2193 type IntoIter = IterMut<'a, T>;
2195 fn into_iter(mut self) -> IterMut<'a, T> {
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 impl<A> Extend<A> for VecDeque<A> {
2202 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2204 self.push_back(elt);
2209 #[stable(feature = "extend_ref", since = "1.2.0")]
2210 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2211 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2212 self.extend(iter.into_iter().cloned());
2216 #[stable(feature = "rust1", since = "1.0.0")]
2217 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2218 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2219 f.debug_list().entries(self).finish()
2223 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2224 impl<T> From<Vec<T>> for VecDeque<T> {
2225 fn from(mut other: Vec<T>) -> Self {
2227 let other_buf = other.as_mut_ptr();
2228 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2229 let len = other.len();
2232 // We need to extend the buf if it's not a power of two, too small
2233 // or doesn't have at least one free space
2234 if !buf.cap().is_power_of_two()
2235 || (buf.cap() < (MINIMUM_CAPACITY + 1))
2236 || (buf.cap() == len)
2238 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2239 buf.reserve_exact(len, cap - len);
2251 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2252 impl<T> From<VecDeque<T>> for Vec<T> {
2253 fn from(other: VecDeque<T>) -> Self {
2255 let buf = other.buf.ptr();
2256 let len = other.len();
2257 let tail = other.tail;
2258 let head = other.head;
2259 let cap = other.cap();
2261 // Need to move the ring to the front of the buffer, as vec will expect this.
2262 if other.is_contiguous() {
2263 ptr::copy(buf.offset(tail as isize), buf, len);
2265 if (tail - head) >= cmp::min((cap - tail), head) {
2266 // There is enough free space in the centre for the shortest block so we can
2267 // do this in at most three copy moves.
2268 if (cap - tail) > head {
2269 // right hand block is the long one; move that enough for the left
2271 buf.offset(tail as isize),
2272 buf.offset((tail - head) as isize),
2274 // copy left in the end
2275 ptr::copy(buf, buf.offset((cap - head) as isize), head);
2276 // shift the new thing to the start
2277 ptr::copy(buf.offset((tail-head) as isize), buf, len);
2279 // left hand block is the long one, we can do it in two!
2280 ptr::copy(buf, buf.offset((cap-tail) as isize), head);
2281 ptr::copy(buf.offset(tail as isize), buf, cap-tail);
2284 // Need to use N swaps to move the ring
2285 // We can use the space at the end of the ring as a temp store
2287 let mut left_edge: usize = 0;
2288 let mut right_edge: usize = tail;
2290 // The general problem looks like this
2291 // GHIJKLM...ABCDEF - before any swaps
2292 // ABCDEFM...GHIJKL - after 1 pass of swaps
2293 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2294 // - then restart the algorithm with a new (smaller) store
2295 // Sometimes the temp store is reached when the right edge is at the end
2296 // of the buffer - this means we've hit the right order with fewer swaps!
2299 // ABCDEF.. - after four only swaps we've finished
2301 while left_edge < len && right_edge != cap {
2302 let mut right_offset = 0;
2303 for i in left_edge..right_edge {
2304 right_offset = (i - left_edge) % (cap - right_edge);
2305 let src: isize = (right_edge + right_offset) as isize;
2306 ptr::swap(buf.offset(i as isize), buf.offset(src));
2308 let n_ops = right_edge - left_edge;
2310 right_edge += right_offset + 1;
2316 let out = Vec::from_raw_parts(buf, len, cap);
2325 use core::iter::Iterator;
2326 use core::option::Option::Some;
2330 use super::VecDeque;
2333 fn bench_push_back_100(b: &mut test::Bencher) {
2334 let mut deq = VecDeque::with_capacity(101);
2345 fn bench_push_front_100(b: &mut test::Bencher) {
2346 let mut deq = VecDeque::with_capacity(101);
2357 fn bench_pop_back_100(b: &mut test::Bencher) {
2358 let mut deq = VecDeque::<i32>::with_capacity(101);
2363 while !deq.is_empty() {
2364 test::black_box(deq.pop_back());
2370 fn bench_pop_front_100(b: &mut test::Bencher) {
2371 let mut deq = VecDeque::<i32>::with_capacity(101);
2376 while !deq.is_empty() {
2377 test::black_box(deq.pop_front());
2383 fn test_swap_front_back_remove() {
2384 fn test(back: bool) {
2385 // This test checks that every single combination of tail position and length is tested.
2386 // Capacity 15 should be large enough to cover every case.
2387 let mut tester = VecDeque::with_capacity(15);
2388 let usable_cap = tester.capacity();
2389 let final_len = usable_cap / 2;
2391 for len in 0..final_len {
2392 let expected = if back {
2395 (0..len).rev().collect()
2397 for tail_pos in 0..usable_cap {
2398 tester.tail = tail_pos;
2399 tester.head = tail_pos;
2401 for i in 0..len * 2 {
2402 tester.push_front(i);
2405 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2408 for i in 0..len * 2 {
2409 tester.push_back(i);
2412 let idx = tester.len() - 1 - i;
2413 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2416 assert!(tester.tail < tester.cap());
2417 assert!(tester.head < tester.cap());
2418 assert_eq!(tester, expected);
2428 // This test checks that every single combination of tail position, length, and
2429 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2431 let mut tester = VecDeque::with_capacity(15);
2432 // can't guarantee we got 15, so have to get what we got.
2433 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2434 // this test isn't covering what it wants to
2435 let cap = tester.capacity();
2438 // len is the length *after* insertion
2440 // 0, 1, 2, .., len - 1
2441 let expected = (0..).take(len).collect();
2442 for tail_pos in 0..cap {
2443 for to_insert in 0..len {
2444 tester.tail = tail_pos;
2445 tester.head = tail_pos;
2448 tester.push_back(i);
2451 tester.insert(to_insert, to_insert);
2452 assert!(tester.tail < tester.cap());
2453 assert!(tester.head < tester.cap());
2454 assert_eq!(tester, expected);
2462 // This test checks that every single combination of tail position, length, and
2463 // removal position is tested. Capacity 15 should be large enough to cover every case.
2465 let mut tester = VecDeque::with_capacity(15);
2466 // can't guarantee we got 15, so have to get what we got.
2467 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2468 // this test isn't covering what it wants to
2469 let cap = tester.capacity();
2471 // len is the length *after* removal
2472 for len in 0..cap - 1 {
2473 // 0, 1, 2, .., len - 1
2474 let expected = (0..).take(len).collect();
2475 for tail_pos in 0..cap {
2476 for to_remove in 0..len + 1 {
2477 tester.tail = tail_pos;
2478 tester.head = tail_pos;
2481 tester.push_back(1234);
2483 tester.push_back(i);
2485 if to_remove == len {
2486 tester.push_back(1234);
2488 tester.remove(to_remove);
2489 assert!(tester.tail < tester.cap());
2490 assert!(tester.head < tester.cap());
2491 assert_eq!(tester, expected);
2499 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2501 let cap = tester.capacity();
2502 for len in 0..cap + 1 {
2503 for tail in 0..cap + 1 {
2504 for drain_start in 0..len + 1 {
2505 for drain_end in drain_start..len + 1 {
2509 tester.push_back(i);
2512 // Check that we drain the correct values
2513 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2514 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2515 assert_eq!(drained, drained_expected);
2517 // We shouldn't have changed the capacity or made the
2518 // head or tail out of bounds
2519 assert_eq!(tester.capacity(), cap);
2520 assert!(tester.tail < tester.cap());
2521 assert!(tester.head < tester.cap());
2523 // We should see the correct values in the VecDeque
2524 let expected: VecDeque<_> = (0..drain_start)
2525 .chain(drain_end..len)
2527 assert_eq!(expected, tester);
2535 fn test_shrink_to_fit() {
2536 // This test checks that every single combination of head and tail position,
2537 // is tested. Capacity 15 should be large enough to cover every case.
2539 let mut tester = VecDeque::with_capacity(15);
2540 // can't guarantee we got 15, so have to get what we got.
2541 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2542 // this test isn't covering what it wants to
2543 let cap = tester.capacity();
2545 let max_cap = tester.capacity();
2547 for len in 0..cap + 1 {
2548 // 0, 1, 2, .., len - 1
2549 let expected = (0..).take(len).collect();
2550 for tail_pos in 0..max_cap + 1 {
2551 tester.tail = tail_pos;
2552 tester.head = tail_pos;
2555 tester.push_back(i);
2557 tester.shrink_to_fit();
2558 assert!(tester.capacity() <= cap);
2559 assert!(tester.tail < tester.cap());
2560 assert!(tester.head < tester.cap());
2561 assert_eq!(tester, expected);
2567 fn test_split_off() {
2568 // This test checks that every single combination of tail position, length, and
2569 // split position is tested. Capacity 15 should be large enough to cover every case.
2571 let mut tester = VecDeque::with_capacity(15);
2572 // can't guarantee we got 15, so have to get what we got.
2573 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2574 // this test isn't covering what it wants to
2575 let cap = tester.capacity();
2577 // len is the length *before* splitting
2579 // index to split at
2580 for at in 0..len + 1 {
2581 // 0, 1, 2, .., at - 1 (may be empty)
2582 let expected_self = (0..).take(at).collect();
2583 // at, at + 1, .., len - 1 (may be empty)
2584 let expected_other = (at..).take(len - at).collect();
2586 for tail_pos in 0..cap {
2587 tester.tail = tail_pos;
2588 tester.head = tail_pos;
2590 tester.push_back(i);
2592 let result = tester.split_off(at);
2593 assert!(tester.tail < tester.cap());
2594 assert!(tester.head < tester.cap());
2595 assert!(result.tail < result.cap());
2596 assert!(result.head < result.cap());
2597 assert_eq!(tester, expected_self);
2598 assert_eq!(result, expected_other);
2605 fn test_from_vec() {
2606 use super::super::vec::Vec;
2608 for len in 0..cap + 1 {
2609 let mut vec = Vec::with_capacity(cap);
2612 let vd = VecDeque::from(vec.clone());
2613 assert!(vd.cap().is_power_of_two());
2614 assert_eq!(vd.len(), vec.len());
2615 assert!(vd.into_iter().eq(vec));
2621 fn test_vec_from_vecdeque() {
2622 use super::super::vec::Vec;
2624 fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
2625 let mut vd = VecDeque::with_capacity(cap);
2626 for _ in 0..offset {
2632 let vec: Vec<_> = Vec::from(vd.clone());
2633 assert_eq!(vec.len(), vd.len());
2634 assert!(vec.into_iter().eq(vd));
2637 for cap_pwr in 0..7 {
2638 // Make capacity as a (2^x)-1, so that the ring size is 2^x
2639 let cap = (2i32.pow(cap_pwr) - 1) as usize;
2641 // In these cases there is enough free space to solve it with copies
2642 for len in 0..((cap+1)/2) {
2643 // Test contiguous cases
2644 for offset in 0..(cap-len) {
2645 create_vec_and_test_convert(cap, offset, len)
2648 // Test cases where block at end of buffer is bigger than block at start
2649 for offset in (cap-len)..(cap-(len/2)) {
2650 create_vec_and_test_convert(cap, offset, len)
2653 // Test cases where block at start of buffer is bigger than block at end
2654 for offset in (cap-(len/2))..cap {
2655 create_vec_and_test_convert(cap, offset, len)
2659 // Now there's not (necessarily) space to straighten the ring with simple copies,
2660 // the ring will use swapping when:
2661 // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
2662 // right block size > free space && left block size > free space
2663 for len in ((cap+1)/2)..cap {
2664 // Test contiguous cases
2665 for offset in 0..(cap-len) {
2666 create_vec_and_test_convert(cap, offset, len)
2669 // Test cases where block at end of buffer is bigger than block at start
2670 for offset in (cap-len)..(cap-(len/2)) {
2671 create_vec_and_test_convert(cap, offset, len)
2674 // Test cases where block at start of buffer is bigger than block at end
2675 for offset in (cap-(len/2))..cap {
2676 create_vec_and_test_convert(cap, offset, len)