1 //! A double-ended queue implemented with a growable ring buffer.
3 //! This queue has `O(1)` amortized inserts and removals from both ends of the
4 //! container. It also has `O(1)` indexing like a vector. The contained elements
5 //! are not required to be copyable, and the queue will be sendable if the
6 //! contained type is sendable.
8 #![stable(feature = "rust1", since = "1.0.0")]
10 use core::array::LengthAtMost32;
11 use core::cmp::{self, Ordering};
13 use core::hash::{Hash, Hasher};
14 use core::iter::{once, repeat_with, FromIterator, FusedIterator};
15 use core::mem::{self, replace, ManuallyDrop};
16 use core::ops::Bound::{Excluded, Included, Unbounded};
17 use core::ops::{Index, IndexMut, RangeBounds, Try};
18 use core::ptr::{self, NonNull};
21 use crate::collections::TryReserveError;
22 use crate::raw_vec::RawVec;
25 #[stable(feature = "drain", since = "1.6.0")]
26 pub use self::drain::Drain;
33 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
34 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
35 #[cfg(target_pointer_width = "16")]
36 const MAXIMUM_ZST_CAPACITY: usize = 1 << (16 - 1); // Largest possible power of two
37 #[cfg(target_pointer_width = "32")]
38 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
39 #[cfg(target_pointer_width = "64")]
40 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
42 /// A double-ended queue implemented with a growable ring buffer.
44 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
45 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
46 /// push onto the back in this manner, and iterating over `VecDeque` goes front
49 /// [`push_back`]: #method.push_back
50 /// [`pop_front`]: #method.pop_front
51 /// [`extend`]: #method.extend
52 /// [`append`]: #method.append
53 #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_type")]
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub struct VecDeque<T> {
56 // tail and head are pointers into the buffer. Tail always points
57 // to the first element that could be read, Head always points
58 // to where data should be written.
59 // If tail == head the buffer is empty. The length of the ringbuffer
60 // is defined as the distance between the two.
66 /// PairSlices pairs up equal length slice parts of two deques
68 /// For example, given deques "A" and "B" with the following division into slices:
70 /// A: [0 1 2] [3 4 5]
73 /// It produces the following sequence of matching slices:
79 /// and the uneven remainder of either A or B is skipped.
80 struct PairSlices<'a, 'b, T> {
87 impl<'a, 'b, T> PairSlices<'a, 'b, T> {
88 fn from(to: &'a mut VecDeque<T>, from: &'b VecDeque<T>) -> Self {
89 let (a0, a1) = to.as_mut_slices();
90 let (b0, b1) = from.as_slices();
91 PairSlices { a0, a1, b0, b1 }
94 fn has_remainder(&self) -> bool {
98 fn remainder(self) -> impl Iterator<Item = &'b [T]> {
99 once(self.b0).chain(once(self.b1))
103 impl<'a, 'b, T> Iterator for PairSlices<'a, 'b, T> {
104 type Item = (&'a mut [T], &'b [T]);
105 fn next(&mut self) -> Option<Self::Item> {
106 // Get next part length
107 let part = cmp::min(self.a0.len(), self.b0.len());
111 let (p0, p1) = replace(&mut self.a0, &mut []).split_at_mut(part);
112 let (q0, q1) = self.b0.split_at(part);
114 // Move a1 into a0, if it's empty (and b1, b0 the same way).
117 if self.a0.is_empty() {
118 self.a0 = replace(&mut self.a1, &mut []);
120 if self.b0.is_empty() {
121 self.b0 = replace(&mut self.b1, &[]);
127 #[stable(feature = "rust1", since = "1.0.0")]
128 impl<T: Clone> Clone for VecDeque<T> {
129 fn clone(&self) -> VecDeque<T> {
130 self.iter().cloned().collect()
133 fn clone_from(&mut self, other: &Self) {
134 self.truncate(other.len());
136 let mut iter = PairSlices::from(self, other);
137 while let Some((dst, src)) = iter.next() {
138 dst.clone_from_slice(&src);
141 if iter.has_remainder() {
142 for remainder in iter.remainder() {
143 self.extend(remainder.iter().cloned());
149 #[stable(feature = "rust1", since = "1.0.0")]
150 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
152 /// Runs the destructor for all items in the slice when it gets dropped (normally or
153 /// during unwinding).
154 struct Dropper<'a, T>(&'a mut [T]);
156 impl<'a, T> Drop for Dropper<'a, T> {
159 ptr::drop_in_place(self.0);
164 let (front, back) = self.as_mut_slices();
166 let _back_dropper = Dropper(back);
168 ptr::drop_in_place(front);
170 // RawVec handles deallocation
174 #[stable(feature = "rust1", since = "1.0.0")]
175 impl<T> Default for VecDeque<T> {
176 /// Creates an empty `VecDeque<T>`.
178 fn default() -> VecDeque<T> {
183 impl<T> VecDeque<T> {
184 /// Marginally more convenient
186 fn ptr(&self) -> *mut T {
190 /// Marginally more convenient
192 fn cap(&self) -> usize {
193 if mem::size_of::<T>() == 0 {
194 // For zero sized types, we are always at maximum capacity
201 /// Turn ptr into a slice
203 unsafe fn buffer_as_slice(&self) -> &[T] {
204 slice::from_raw_parts(self.ptr(), self.cap())
207 /// Turn ptr into a mut slice
209 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
210 slice::from_raw_parts_mut(self.ptr(), self.cap())
213 /// Moves an element out of the buffer
215 unsafe fn buffer_read(&mut self, off: usize) -> T {
216 ptr::read(self.ptr().add(off))
219 /// Writes an element into the buffer, moving it.
221 unsafe fn buffer_write(&mut self, off: usize, value: T) {
222 ptr::write(self.ptr().add(off), value);
225 /// Returns `true` if the buffer is at full capacity.
227 fn is_full(&self) -> bool {
228 self.cap() - self.len() == 1
231 /// Returns the index in the underlying buffer for a given logical element
234 fn wrap_index(&self, idx: usize) -> usize {
235 wrap_index(idx, self.cap())
238 /// Returns the index in the underlying buffer for a given logical element
241 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
242 wrap_index(idx.wrapping_add(addend), self.cap())
245 /// Returns the index in the underlying buffer for a given logical element
246 /// index - subtrahend.
248 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
249 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
252 /// Copies a contiguous block of memory len long from src to dst
254 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
256 dst + len <= self.cap(),
257 "cpy dst={} src={} len={} cap={}",
264 src + len <= self.cap(),
265 "cpy dst={} src={} len={} cap={}",
271 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
274 /// Copies a contiguous block of memory len long from src to dst
276 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
278 dst + len <= self.cap(),
279 "cno dst={} src={} len={} cap={}",
286 src + len <= self.cap(),
287 "cno dst={} src={} len={} cap={}",
293 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
296 /// Copies a potentially wrapping block of memory len long from src to dest.
297 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
298 /// most one continuous overlapping region between src and dest).
299 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
301 fn diff(a: usize, b: usize) -> usize {
302 if a <= b { b - a } else { a - b }
305 cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
306 "wrc dst={} src={} len={} cap={}",
313 if src == dst || len == 0 {
317 let dst_after_src = self.wrap_sub(dst, src) < len;
319 let src_pre_wrap_len = self.cap() - src;
320 let dst_pre_wrap_len = self.cap() - dst;
321 let src_wraps = src_pre_wrap_len < len;
322 let dst_wraps = dst_pre_wrap_len < len;
324 match (dst_after_src, src_wraps, dst_wraps) {
325 (_, false, false) => {
326 // src doesn't wrap, dst doesn't wrap
329 // 1 [_ _ A A B B C C _]
330 // 2 [_ _ A A A A B B _]
333 self.copy(dst, src, len);
335 (false, false, true) => {
336 // dst before src, src doesn't wrap, dst wraps
339 // 1 [A A B B _ _ _ C C]
340 // 2 [A A B B _ _ _ A A]
341 // 3 [B B B B _ _ _ A A]
344 self.copy(dst, src, dst_pre_wrap_len);
345 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
347 (true, false, true) => {
348 // src before dst, src doesn't wrap, dst wraps
351 // 1 [C C _ _ _ A A B B]
352 // 2 [B B _ _ _ A A B B]
353 // 3 [B B _ _ _ A A A A]
356 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
357 self.copy(dst, src, dst_pre_wrap_len);
359 (false, true, false) => {
360 // dst before src, src wraps, dst doesn't wrap
363 // 1 [C C _ _ _ A A B B]
364 // 2 [C C _ _ _ B B B B]
365 // 3 [C C _ _ _ B B C C]
368 self.copy(dst, src, src_pre_wrap_len);
369 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
371 (true, true, false) => {
372 // src before dst, src wraps, dst doesn't wrap
375 // 1 [A A B B _ _ _ C C]
376 // 2 [A A A A _ _ _ C C]
377 // 3 [C C A A _ _ _ C C]
380 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
381 self.copy(dst, src, src_pre_wrap_len);
383 (false, true, true) => {
384 // dst before src, src wraps, dst wraps
387 // 1 [A B C D _ E F G H]
388 // 2 [A B C D _ E G H H]
389 // 3 [A B C D _ E G H A]
390 // 4 [B C C D _ E G H A]
393 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
394 let delta = dst_pre_wrap_len - src_pre_wrap_len;
395 self.copy(dst, src, src_pre_wrap_len);
396 self.copy(dst + src_pre_wrap_len, 0, delta);
397 self.copy(0, delta, len - dst_pre_wrap_len);
399 (true, true, true) => {
400 // src before dst, src wraps, dst wraps
403 // 1 [A B C D _ E F G H]
404 // 2 [A A B D _ E F G H]
405 // 3 [H A B D _ E F G H]
406 // 4 [H A B D _ E F F G]
409 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
410 let delta = src_pre_wrap_len - dst_pre_wrap_len;
411 self.copy(delta, 0, len - src_pre_wrap_len);
412 self.copy(0, self.cap() - delta, delta);
413 self.copy(dst, src, dst_pre_wrap_len);
418 /// Frobs the head and tail sections around to handle the fact that we
419 /// just reallocated. Unsafe because it trusts old_capacity.
421 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
422 let new_capacity = self.cap();
424 // Move the shortest contiguous section of the ring buffer
426 // [o o o o o o o . ]
428 // A [o o o o o o o . . . . . . . . . ]
430 // [o o . o o o o o ]
432 // B [. . . o o o o o o o . . . . . . ]
434 // [o o o o o . o o ]
436 // C [o o o o o . . . . . . . . . o o ]
438 if self.tail <= self.head {
441 } else if self.head < old_capacity - self.tail {
443 self.copy_nonoverlapping(old_capacity, 0, self.head);
444 self.head += old_capacity;
445 debug_assert!(self.head > self.tail);
448 let new_tail = new_capacity - (old_capacity - self.tail);
449 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
450 self.tail = new_tail;
451 debug_assert!(self.head < self.tail);
453 debug_assert!(self.head < self.cap());
454 debug_assert!(self.tail < self.cap());
455 debug_assert!(self.cap().count_ones() == 1);
459 impl<T> VecDeque<T> {
460 /// Creates an empty `VecDeque`.
465 /// use std::collections::VecDeque;
467 /// let vector: VecDeque<u32> = VecDeque::new();
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn new() -> VecDeque<T> {
471 VecDeque::with_capacity(INITIAL_CAPACITY)
474 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
479 /// use std::collections::VecDeque;
481 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
483 #[stable(feature = "rust1", since = "1.0.0")]
484 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
485 // +1 since the ringbuffer always leaves one space empty
486 let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
487 assert!(cap > capacity, "capacity overflow");
489 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity(cap) }
492 /// Provides a reference to the element at the given index.
494 /// Element at index 0 is the front of the queue.
499 /// use std::collections::VecDeque;
501 /// let mut buf = VecDeque::new();
502 /// buf.push_back(3);
503 /// buf.push_back(4);
504 /// buf.push_back(5);
505 /// assert_eq!(buf.get(1), Some(&4));
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn get(&self, index: usize) -> Option<&T> {
509 if index < self.len() {
510 let idx = self.wrap_add(self.tail, index);
511 unsafe { Some(&*self.ptr().add(idx)) }
517 /// Provides a mutable reference to the element at the given index.
519 /// Element at index 0 is the front of the queue.
524 /// use std::collections::VecDeque;
526 /// let mut buf = VecDeque::new();
527 /// buf.push_back(3);
528 /// buf.push_back(4);
529 /// buf.push_back(5);
530 /// if let Some(elem) = buf.get_mut(1) {
534 /// assert_eq!(buf[1], 7);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
538 if index < self.len() {
539 let idx = self.wrap_add(self.tail, index);
540 unsafe { Some(&mut *self.ptr().add(idx)) }
546 /// Swaps elements at indices `i` and `j`.
548 /// `i` and `j` may be equal.
550 /// Element at index 0 is the front of the queue.
554 /// Panics if either index is out of bounds.
559 /// use std::collections::VecDeque;
561 /// let mut buf = VecDeque::new();
562 /// buf.push_back(3);
563 /// buf.push_back(4);
564 /// buf.push_back(5);
565 /// assert_eq!(buf, [3, 4, 5]);
567 /// assert_eq!(buf, [5, 4, 3]);
569 #[stable(feature = "rust1", since = "1.0.0")]
570 pub fn swap(&mut self, i: usize, j: usize) {
571 assert!(i < self.len());
572 assert!(j < self.len());
573 let ri = self.wrap_add(self.tail, i);
574 let rj = self.wrap_add(self.tail, j);
575 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
578 /// Returns the number of elements the `VecDeque` can hold without
584 /// use std::collections::VecDeque;
586 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
587 /// assert!(buf.capacity() >= 10);
590 #[stable(feature = "rust1", since = "1.0.0")]
591 pub fn capacity(&self) -> usize {
595 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
596 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
598 /// Note that the allocator may give the collection more space than it requests. Therefore
599 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
600 /// insertions are expected.
604 /// Panics if the new capacity overflows `usize`.
609 /// use std::collections::VecDeque;
611 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
612 /// buf.reserve_exact(10);
613 /// assert!(buf.capacity() >= 11);
616 /// [`reserve`]: #method.reserve
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn reserve_exact(&mut self, additional: usize) {
619 self.reserve(additional);
622 /// Reserves capacity for at least `additional` more elements to be inserted in the given
623 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
627 /// Panics if the new capacity overflows `usize`.
632 /// use std::collections::VecDeque;
634 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
636 /// assert!(buf.capacity() >= 11);
638 #[stable(feature = "rust1", since = "1.0.0")]
639 pub fn reserve(&mut self, additional: usize) {
640 let old_cap = self.cap();
641 let used_cap = self.len() + 1;
642 let new_cap = used_cap
643 .checked_add(additional)
644 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
645 .expect("capacity overflow");
647 if new_cap > old_cap {
648 self.buf.reserve_exact(used_cap, new_cap - used_cap);
650 self.handle_capacity_increase(old_cap);
655 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
656 /// be inserted in the given `VecDeque<T>`. After calling `reserve_exact`,
657 /// capacity will be greater than or equal to `self.len() + additional`.
658 /// Does nothing if the capacity is already sufficient.
660 /// Note that the allocator may give the collection more space than it
661 /// requests. Therefore, capacity can not be relied upon to be precisely
662 /// minimal. Prefer `reserve` if future insertions are expected.
666 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
672 /// #![feature(try_reserve)]
673 /// use std::collections::TryReserveError;
674 /// use std::collections::VecDeque;
676 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
677 /// let mut output = VecDeque::new();
679 /// // Pre-reserve the memory, exiting if we can't
680 /// output.try_reserve_exact(data.len())?;
682 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
683 /// output.extend(data.iter().map(|&val| {
684 /// val * 2 + 5 // very complicated
689 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
691 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
692 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
693 self.try_reserve(additional)
696 /// Tries to reserve capacity for at least `additional` more elements to be inserted
697 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
698 /// frequent reallocations. After calling `reserve`, capacity will be
699 /// greater than or equal to `self.len() + additional`. Does nothing if
700 /// capacity is already sufficient.
704 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
710 /// #![feature(try_reserve)]
711 /// use std::collections::TryReserveError;
712 /// use std::collections::VecDeque;
714 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
715 /// let mut output = VecDeque::new();
717 /// // Pre-reserve the memory, exiting if we can't
718 /// output.try_reserve(data.len())?;
720 /// // Now we know this can't OOM in the middle of our complex work
721 /// output.extend(data.iter().map(|&val| {
722 /// val * 2 + 5 // very complicated
727 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
729 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
730 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
731 let old_cap = self.cap();
732 let used_cap = self.len() + 1;
733 let new_cap = used_cap
734 .checked_add(additional)
735 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
736 .ok_or(TryReserveError::CapacityOverflow)?;
738 if new_cap > old_cap {
739 self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
741 self.handle_capacity_increase(old_cap);
747 /// Shrinks the capacity of the `VecDeque` as much as possible.
749 /// It will drop down as close as possible to the length but the allocator may still inform the
750 /// `VecDeque` that there is space for a few more elements.
755 /// use std::collections::VecDeque;
757 /// let mut buf = VecDeque::with_capacity(15);
758 /// buf.extend(0..4);
759 /// assert_eq!(buf.capacity(), 15);
760 /// buf.shrink_to_fit();
761 /// assert!(buf.capacity() >= 4);
763 #[stable(feature = "deque_extras_15", since = "1.5.0")]
764 pub fn shrink_to_fit(&mut self) {
768 /// Shrinks the capacity of the `VecDeque` with a lower bound.
770 /// The capacity will remain at least as large as both the length
771 /// and the supplied value.
773 /// Panics if the current capacity is smaller than the supplied
774 /// minimum capacity.
779 /// #![feature(shrink_to)]
780 /// use std::collections::VecDeque;
782 /// let mut buf = VecDeque::with_capacity(15);
783 /// buf.extend(0..4);
784 /// assert_eq!(buf.capacity(), 15);
785 /// buf.shrink_to(6);
786 /// assert!(buf.capacity() >= 6);
787 /// buf.shrink_to(0);
788 /// assert!(buf.capacity() >= 4);
790 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
791 pub fn shrink_to(&mut self, min_capacity: usize) {
792 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
794 // +1 since the ringbuffer always leaves one space empty
795 // len + 1 can't overflow for an existing, well-formed ringbuffer.
796 let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
797 .next_power_of_two();
799 if target_cap < self.cap() {
800 // There are three cases of interest:
801 // All elements are out of desired bounds
802 // Elements are contiguous, and head is out of desired bounds
803 // Elements are discontiguous, and tail is out of desired bounds
805 // At all other times, element positions are unaffected.
807 // Indicates that elements at the head should be moved.
808 let head_outside = self.head == 0 || self.head >= target_cap;
809 // Move elements from out of desired bounds (positions after target_cap)
810 if self.tail >= target_cap && head_outside {
812 // [. . . . . . . . o o o o o o o . ]
814 // [o o o o o o o . ]
816 self.copy_nonoverlapping(0, self.tail, self.len());
818 self.head = self.len();
820 } else if self.tail != 0 && self.tail < target_cap && head_outside {
822 // [. . . o o o o o o o . . . . . . ]
824 // [o o . o o o o o ]
825 let len = self.wrap_sub(self.head, target_cap);
827 self.copy_nonoverlapping(0, target_cap, len);
830 debug_assert!(self.head < self.tail);
831 } else if self.tail >= target_cap {
833 // [o o o o o . . . . . . . . . o o ]
835 // [o o o o o . o o ]
836 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
837 let len = self.cap() - self.tail;
838 let new_tail = target_cap - len;
840 self.copy_nonoverlapping(new_tail, self.tail, len);
842 self.tail = new_tail;
843 debug_assert!(self.head < self.tail);
846 self.buf.shrink_to_fit(target_cap);
848 debug_assert!(self.head < self.cap());
849 debug_assert!(self.tail < self.cap());
850 debug_assert!(self.cap().count_ones() == 1);
854 /// Shortens the `VecDeque`, keeping the first `len` elements and dropping
857 /// If `len` is greater than the `VecDeque`'s current length, this has no
863 /// use std::collections::VecDeque;
865 /// let mut buf = VecDeque::new();
866 /// buf.push_back(5);
867 /// buf.push_back(10);
868 /// buf.push_back(15);
869 /// assert_eq!(buf, [5, 10, 15]);
871 /// assert_eq!(buf, [5]);
873 #[stable(feature = "deque_extras", since = "1.16.0")]
874 pub fn truncate(&mut self, len: usize) {
875 /// Runs the destructor for all items in the slice when it gets dropped (normally or
876 /// during unwinding).
877 struct Dropper<'a, T>(&'a mut [T]);
879 impl<'a, T> Drop for Dropper<'a, T> {
882 ptr::drop_in_place(self.0);
889 // * Any slice passed to `drop_in_place` is valid; the second case has
890 // `len <= front.len()` and returning on `len > self.len()` ensures
891 // `begin <= back.len()` in the first case
892 // * The head of the VecDeque is moved before calling `drop_in_place`,
893 // so no value is dropped twice if `drop_in_place` panics
895 if len > self.len() {
898 let num_dropped = self.len() - len;
899 let (front, back) = self.as_mut_slices();
900 if len > front.len() {
901 let begin = len - front.len();
902 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
903 self.head = self.wrap_sub(self.head, num_dropped);
904 ptr::drop_in_place(drop_back);
906 let drop_back = back as *mut _;
907 let drop_front = front.get_unchecked_mut(len..) as *mut _;
908 self.head = self.wrap_sub(self.head, num_dropped);
910 // Make sure the second half is dropped even when a destructor
911 // in the first one panics.
912 let _back_dropper = Dropper(&mut *drop_back);
913 ptr::drop_in_place(drop_front);
918 /// Returns a front-to-back iterator.
923 /// use std::collections::VecDeque;
925 /// let mut buf = VecDeque::new();
926 /// buf.push_back(5);
927 /// buf.push_back(3);
928 /// buf.push_back(4);
929 /// let b: &[_] = &[&5, &3, &4];
930 /// let c: Vec<&i32> = buf.iter().collect();
931 /// assert_eq!(&c[..], b);
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn iter(&self) -> Iter<'_, T> {
935 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } }
938 /// Returns a front-to-back iterator that returns mutable references.
943 /// use std::collections::VecDeque;
945 /// let mut buf = VecDeque::new();
946 /// buf.push_back(5);
947 /// buf.push_back(3);
948 /// buf.push_back(4);
949 /// for num in buf.iter_mut() {
952 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
953 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
955 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
957 IterMut { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_mut_slice() } }
960 /// Returns a pair of slices which contain, in order, the contents of the
963 /// If [`make_contiguous`](#method.make_contiguous) was previously called, all elements
964 /// of the `VecDeque` will be in the first slice and the second slice will be empty.
969 /// use std::collections::VecDeque;
971 /// let mut vector = VecDeque::new();
973 /// vector.push_back(0);
974 /// vector.push_back(1);
975 /// vector.push_back(2);
977 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
979 /// vector.push_front(10);
980 /// vector.push_front(9);
982 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
985 #[stable(feature = "deque_extras_15", since = "1.5.0")]
986 pub fn as_slices(&self) -> (&[T], &[T]) {
988 let buf = self.buffer_as_slice();
989 RingSlices::ring_slices(buf, self.head, self.tail)
993 /// Returns a pair of slices which contain, in order, the contents of the
996 /// If [`make_contiguous`](#method.make_contiguous) was previously called, all elements
997 /// of the `VecDeque` will be in the first slice and the second slice will be empty.
1002 /// use std::collections::VecDeque;
1004 /// let mut vector = VecDeque::new();
1006 /// vector.push_back(0);
1007 /// vector.push_back(1);
1009 /// vector.push_front(10);
1010 /// vector.push_front(9);
1012 /// vector.as_mut_slices().0[0] = 42;
1013 /// vector.as_mut_slices().1[0] = 24;
1014 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
1017 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1018 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1020 let head = self.head;
1021 let tail = self.tail;
1022 let buf = self.buffer_as_mut_slice();
1023 RingSlices::ring_slices(buf, head, tail)
1027 /// Returns the number of elements in the `VecDeque`.
1032 /// use std::collections::VecDeque;
1034 /// let mut v = VecDeque::new();
1035 /// assert_eq!(v.len(), 0);
1037 /// assert_eq!(v.len(), 1);
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 pub fn len(&self) -> usize {
1041 count(self.tail, self.head, self.cap())
1044 /// Returns `true` if the `VecDeque` is empty.
1049 /// use std::collections::VecDeque;
1051 /// let mut v = VecDeque::new();
1052 /// assert!(v.is_empty());
1053 /// v.push_front(1);
1054 /// assert!(!v.is_empty());
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 pub fn is_empty(&self) -> bool {
1058 self.tail == self.head
1061 /// Creates a draining iterator that removes the specified range in the
1062 /// `VecDeque` and yields the removed items.
1064 /// Note 1: The element range is removed even if the iterator is not
1065 /// consumed until the end.
1067 /// Note 2: It is unspecified how many elements are removed from the deque,
1068 /// if the `Drain` value is not dropped, but the borrow it holds expires
1069 /// (e.g., due to `mem::forget`).
1073 /// Panics if the starting point is greater than the end point or if
1074 /// the end point is greater than the length of the vector.
1079 /// use std::collections::VecDeque;
1081 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1082 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
1083 /// assert_eq!(drained, [3]);
1084 /// assert_eq!(v, [1, 2]);
1086 /// // A full range clears all contents
1088 /// assert!(v.is_empty());
1091 #[stable(feature = "drain", since = "1.6.0")]
1092 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1094 R: RangeBounds<usize>,
1098 // When the Drain is first created, the source deque is shortened to
1099 // make sure no uninitialized or moved-from elements are accessible at
1100 // all if the Drain's destructor never gets to run.
1102 // Drain will ptr::read out the values to remove.
1103 // When finished, the remaining data will be copied back to cover the hole,
1104 // and the head/tail values will be restored correctly.
1106 let len = self.len();
1107 let start = match range.start_bound() {
1109 Excluded(&n) => n + 1,
1112 let end = match range.end_bound() {
1113 Included(&n) => n + 1,
1117 assert!(start <= end, "drain lower bound was too large");
1118 assert!(end <= len, "drain upper bound was too large");
1120 // The deque's elements are parted into three segments:
1121 // * self.tail -> drain_tail
1122 // * drain_tail -> drain_head
1123 // * drain_head -> self.head
1125 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1127 // We store drain_tail as self.head, and drain_head and self.head as
1128 // after_tail and after_head respectively on the Drain. This also
1129 // truncates the effective array such that if the Drain is leaked, we
1130 // have forgotten about the potentially moved values after the start of
1134 // [. . . o o x x o o . . .]
1136 let drain_tail = self.wrap_add(self.tail, start);
1137 let drain_head = self.wrap_add(self.tail, end);
1138 let head = self.head;
1140 // "forget" about the values after the start of the drain until after
1141 // the drain is complete and the Drain destructor is run.
1142 self.head = drain_tail;
1145 deque: NonNull::from(&mut *self),
1146 after_tail: drain_head,
1151 // Crucially, we only create shared references from `self` here and read from
1152 // it. We do not write to `self` nor reborrow to a mutable reference.
1153 // Hence the raw pointer we created above, for `deque`, remains valid.
1154 ring: unsafe { self.buffer_as_slice() },
1159 /// Clears the `VecDeque`, removing all values.
1164 /// use std::collections::VecDeque;
1166 /// let mut v = VecDeque::new();
1169 /// assert!(v.is_empty());
1171 #[stable(feature = "rust1", since = "1.0.0")]
1173 pub fn clear(&mut self) {
1177 /// Returns `true` if the `VecDeque` contains an element equal to the
1183 /// use std::collections::VecDeque;
1185 /// let mut vector: VecDeque<u32> = VecDeque::new();
1187 /// vector.push_back(0);
1188 /// vector.push_back(1);
1190 /// assert_eq!(vector.contains(&1), true);
1191 /// assert_eq!(vector.contains(&10), false);
1193 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1194 pub fn contains(&self, x: &T) -> bool
1198 let (a, b) = self.as_slices();
1199 a.contains(x) || b.contains(x)
1202 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1208 /// use std::collections::VecDeque;
1210 /// let mut d = VecDeque::new();
1211 /// assert_eq!(d.front(), None);
1215 /// assert_eq!(d.front(), Some(&1));
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub fn front(&self) -> Option<&T> {
1219 if !self.is_empty() { Some(&self[0]) } else { None }
1222 /// Provides a mutable reference to the front element, or `None` if the
1223 /// `VecDeque` is empty.
1228 /// use std::collections::VecDeque;
1230 /// let mut d = VecDeque::new();
1231 /// assert_eq!(d.front_mut(), None);
1235 /// match d.front_mut() {
1236 /// Some(x) => *x = 9,
1239 /// assert_eq!(d.front(), Some(&9));
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 pub fn front_mut(&mut self) -> Option<&mut T> {
1243 if !self.is_empty() { Some(&mut self[0]) } else { None }
1246 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1252 /// use std::collections::VecDeque;
1254 /// let mut d = VecDeque::new();
1255 /// assert_eq!(d.back(), None);
1259 /// assert_eq!(d.back(), Some(&2));
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 pub fn back(&self) -> Option<&T> {
1263 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
1266 /// Provides a mutable reference to the back element, or `None` if the
1267 /// `VecDeque` is empty.
1272 /// use std::collections::VecDeque;
1274 /// let mut d = VecDeque::new();
1275 /// assert_eq!(d.back(), None);
1279 /// match d.back_mut() {
1280 /// Some(x) => *x = 9,
1283 /// assert_eq!(d.back(), Some(&9));
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 pub fn back_mut(&mut self) -> Option<&mut T> {
1287 let len = self.len();
1288 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
1291 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1297 /// use std::collections::VecDeque;
1299 /// let mut d = VecDeque::new();
1303 /// assert_eq!(d.pop_front(), Some(1));
1304 /// assert_eq!(d.pop_front(), Some(2));
1305 /// assert_eq!(d.pop_front(), None);
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 pub fn pop_front(&mut self) -> Option<T> {
1309 if self.is_empty() {
1312 let tail = self.tail;
1313 self.tail = self.wrap_add(self.tail, 1);
1314 unsafe { Some(self.buffer_read(tail)) }
1318 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1324 /// use std::collections::VecDeque;
1326 /// let mut buf = VecDeque::new();
1327 /// assert_eq!(buf.pop_back(), None);
1328 /// buf.push_back(1);
1329 /// buf.push_back(3);
1330 /// assert_eq!(buf.pop_back(), Some(3));
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 pub fn pop_back(&mut self) -> Option<T> {
1334 if self.is_empty() {
1337 self.head = self.wrap_sub(self.head, 1);
1338 let head = self.head;
1339 unsafe { Some(self.buffer_read(head)) }
1343 /// Prepends an element to the `VecDeque`.
1348 /// use std::collections::VecDeque;
1350 /// let mut d = VecDeque::new();
1351 /// d.push_front(1);
1352 /// d.push_front(2);
1353 /// assert_eq!(d.front(), Some(&2));
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 pub fn push_front(&mut self, value: T) {
1357 self.grow_if_necessary();
1359 self.tail = self.wrap_sub(self.tail, 1);
1360 let tail = self.tail;
1362 self.buffer_write(tail, value);
1366 /// Appends an element to the back of the `VecDeque`.
1371 /// use std::collections::VecDeque;
1373 /// let mut buf = VecDeque::new();
1374 /// buf.push_back(1);
1375 /// buf.push_back(3);
1376 /// assert_eq!(3, *buf.back().unwrap());
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 pub fn push_back(&mut self, value: T) {
1380 self.grow_if_necessary();
1382 let head = self.head;
1383 self.head = self.wrap_add(self.head, 1);
1384 unsafe { self.buffer_write(head, value) }
1388 fn is_contiguous(&self) -> bool {
1389 self.tail <= self.head
1392 /// Removes an element from anywhere in the `VecDeque` and returns it,
1393 /// replacing it with the first element.
1395 /// This does not preserve ordering, but is `O(1)`.
1397 /// Returns `None` if `index` is out of bounds.
1399 /// Element at index 0 is the front of the queue.
1404 /// use std::collections::VecDeque;
1406 /// let mut buf = VecDeque::new();
1407 /// assert_eq!(buf.swap_remove_front(0), None);
1408 /// buf.push_back(1);
1409 /// buf.push_back(2);
1410 /// buf.push_back(3);
1411 /// assert_eq!(buf, [1, 2, 3]);
1413 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1414 /// assert_eq!(buf, [2, 1]);
1416 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1417 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1418 let length = self.len();
1419 if length > 0 && index < length && index != 0 {
1420 self.swap(index, 0);
1421 } else if index >= length {
1427 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1430 /// This does not preserve ordering, but is `O(1)`.
1432 /// Returns `None` if `index` is out of bounds.
1434 /// Element at index 0 is the front of the queue.
1439 /// use std::collections::VecDeque;
1441 /// let mut buf = VecDeque::new();
1442 /// assert_eq!(buf.swap_remove_back(0), None);
1443 /// buf.push_back(1);
1444 /// buf.push_back(2);
1445 /// buf.push_back(3);
1446 /// assert_eq!(buf, [1, 2, 3]);
1448 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1449 /// assert_eq!(buf, [3, 2]);
1451 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1452 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1453 let length = self.len();
1454 if length > 0 && index < length - 1 {
1455 self.swap(index, length - 1);
1456 } else if index >= length {
1462 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1463 /// greater than or equal to `index` towards the back.
1465 /// Element at index 0 is the front of the queue.
1469 /// Panics if `index` is greater than `VecDeque`'s length
1474 /// use std::collections::VecDeque;
1476 /// let mut vec_deque = VecDeque::new();
1477 /// vec_deque.push_back('a');
1478 /// vec_deque.push_back('b');
1479 /// vec_deque.push_back('c');
1480 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1482 /// vec_deque.insert(1, 'd');
1483 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1485 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1486 pub fn insert(&mut self, index: usize, value: T) {
1487 assert!(index <= self.len(), "index out of bounds");
1488 self.grow_if_necessary();
1490 // Move the least number of elements in the ring buffer and insert
1493 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1495 // There are three main cases:
1496 // Elements are contiguous
1497 // - special case when tail is 0
1498 // Elements are discontiguous and the insert is in the tail section
1499 // Elements are discontiguous and the insert is in the head section
1501 // For each of those there are two more cases:
1502 // Insert is closer to tail
1503 // Insert is closer to head
1505 // Key: H - self.head
1507 // o - Valid element
1508 // I - Insertion element
1509 // A - The element that should be after the insertion point
1510 // M - Indicates element was moved
1512 let idx = self.wrap_add(self.tail, index);
1514 let distance_to_tail = index;
1515 let distance_to_head = self.len() - index;
1517 let contiguous = self.is_contiguous();
1519 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1520 (true, true, _) if index == 0 => {
1525 // [A o o o o o o . . . . . . . . .]
1528 // [A o o o o o o o . . . . . I]
1531 self.tail = self.wrap_sub(self.tail, 1);
1533 (true, true, _) => {
1535 // contiguous, insert closer to tail:
1538 // [. . . o o A o o o o . . . . . .]
1541 // [. . o o I A o o o o . . . . . .]
1544 // contiguous, insert closer to tail and tail is 0:
1548 // [o o A o o o o . . . . . . . . .]
1551 // [o I A o o o o o . . . . . . . o]
1554 let new_tail = self.wrap_sub(self.tail, 1);
1556 self.copy(new_tail, self.tail, 1);
1557 // Already moved the tail, so we only copy `index - 1` elements.
1558 self.copy(self.tail, self.tail + 1, index - 1);
1560 self.tail = new_tail;
1563 (true, false, _) => {
1565 // contiguous, insert closer to head:
1568 // [. . . o o o o A o o . . . . . .]
1571 // [. . . o o o o I A o o . . . . .]
1574 self.copy(idx + 1, idx, self.head - idx);
1575 self.head = self.wrap_add(self.head, 1);
1578 (false, true, true) => {
1580 // discontiguous, insert closer to tail, tail section:
1583 // [o o o o o o . . . . . o o A o o]
1586 // [o o o o o o . . . . o o I A o o]
1589 self.copy(self.tail - 1, self.tail, index);
1593 (false, false, true) => {
1595 // discontiguous, insert closer to head, tail section:
1598 // [o o . . . . . . . o o o o o A o]
1601 // [o o o . . . . . . o o o o o I A]
1604 // copy elements up to new head
1605 self.copy(1, 0, self.head);
1607 // copy last element into empty spot at bottom of buffer
1608 self.copy(0, self.cap() - 1, 1);
1610 // move elements from idx to end forward not including ^ element
1611 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1616 (false, true, false) if idx == 0 => {
1618 // discontiguous, insert is closer to tail, head section,
1619 // and is at index zero in the internal buffer:
1622 // [A o o o o o o o o o . . . o o o]
1625 // [A o o o o o o o o o . . o o o I]
1628 // copy elements up to new tail
1629 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1631 // copy last element into empty spot at bottom of buffer
1632 self.copy(self.cap() - 1, 0, 1);
1637 (false, true, false) => {
1639 // discontiguous, insert closer to tail, head section:
1642 // [o o o A o o o o o o . . . o o o]
1645 // [o o I A o o o o o o . . o o o o]
1648 // copy elements up to new tail
1649 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1651 // copy last element into empty spot at bottom of buffer
1652 self.copy(self.cap() - 1, 0, 1);
1654 // move elements from idx-1 to end forward not including ^ element
1655 self.copy(0, 1, idx - 1);
1660 (false, false, false) => {
1662 // discontiguous, insert closer to head, head section:
1665 // [o o o o A o o . . . . . . o o o]
1668 // [o o o o I A o o . . . . . o o o]
1671 self.copy(idx + 1, idx, self.head - idx);
1677 // tail might've been changed so we need to recalculate
1678 let new_idx = self.wrap_add(self.tail, index);
1680 self.buffer_write(new_idx, value);
1684 /// Removes and returns the element at `index` from the `VecDeque`.
1685 /// Whichever end is closer to the removal point will be moved to make
1686 /// room, and all the affected elements will be moved to new positions.
1687 /// Returns `None` if `index` is out of bounds.
1689 /// Element at index 0 is the front of the queue.
1694 /// use std::collections::VecDeque;
1696 /// let mut buf = VecDeque::new();
1697 /// buf.push_back(1);
1698 /// buf.push_back(2);
1699 /// buf.push_back(3);
1700 /// assert_eq!(buf, [1, 2, 3]);
1702 /// assert_eq!(buf.remove(1), Some(2));
1703 /// assert_eq!(buf, [1, 3]);
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 pub fn remove(&mut self, index: usize) -> Option<T> {
1707 if self.is_empty() || self.len() <= index {
1711 // There are three main cases:
1712 // Elements are contiguous
1713 // Elements are discontiguous and the removal is in the tail section
1714 // Elements are discontiguous and the removal is in the head section
1715 // - special case when elements are technically contiguous,
1716 // but self.head = 0
1718 // For each of those there are two more cases:
1719 // Insert is closer to tail
1720 // Insert is closer to head
1722 // Key: H - self.head
1724 // o - Valid element
1725 // x - Element marked for removal
1726 // R - Indicates element that is being removed
1727 // M - Indicates element was moved
1729 let idx = self.wrap_add(self.tail, index);
1731 let elem = unsafe { Some(self.buffer_read(idx)) };
1733 let distance_to_tail = index;
1734 let distance_to_head = self.len() - index;
1736 let contiguous = self.is_contiguous();
1738 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1739 (true, true, _) => {
1741 // contiguous, remove closer to tail:
1744 // [. . . o o x o o o o . . . . . .]
1747 // [. . . . o o o o o o . . . . . .]
1750 self.copy(self.tail + 1, self.tail, index);
1754 (true, false, _) => {
1756 // contiguous, remove closer to head:
1759 // [. . . o o o o x o o . . . . . .]
1762 // [. . . o o o o o o . . . . . . .]
1765 self.copy(idx, idx + 1, self.head - idx - 1);
1769 (false, true, true) => {
1771 // discontiguous, remove closer to tail, tail section:
1774 // [o o o o o o . . . . . o o x o o]
1777 // [o o o o o o . . . . . . o o o o]
1780 self.copy(self.tail + 1, self.tail, index);
1781 self.tail = self.wrap_add(self.tail, 1);
1784 (false, false, false) => {
1786 // discontiguous, remove closer to head, head section:
1789 // [o o o o x o o . . . . . . o o o]
1792 // [o o o o o o . . . . . . . o o o]
1795 self.copy(idx, idx + 1, self.head - idx - 1);
1799 (false, false, true) => {
1801 // discontiguous, remove closer to head, tail section:
1804 // [o o o . . . . . . o o o o o x o]
1807 // [o o . . . . . . . o o o o o o o]
1810 // or quasi-discontiguous, remove next to head, tail section:
1813 // [. . . . . . . . . o o o o o x o]
1816 // [. . . . . . . . . o o o o o o .]
1819 // draw in elements in the tail section
1820 self.copy(idx, idx + 1, self.cap() - idx - 1);
1822 // Prevents underflow.
1824 // copy first element into empty spot
1825 self.copy(self.cap() - 1, 0, 1);
1827 // move elements in the head section backwards
1828 self.copy(0, 1, self.head - 1);
1831 self.head = self.wrap_sub(self.head, 1);
1834 (false, true, false) => {
1836 // discontiguous, remove closer to tail, head section:
1839 // [o o x o o o o o o o . . . o o o]
1842 // [o o o o o o o o o o . . . . o o]
1845 // draw in elements up to idx
1846 self.copy(1, 0, idx);
1848 // copy last element into empty spot
1849 self.copy(0, self.cap() - 1, 1);
1851 // move elements from tail to end forward, excluding the last one
1852 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1854 self.tail = self.wrap_add(self.tail, 1);
1862 /// Splits the `VecDeque` into two at the given index.
1864 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1865 /// and the returned `VecDeque` contains elements `[at, len)`.
1867 /// Note that the capacity of `self` does not change.
1869 /// Element at index 0 is the front of the queue.
1873 /// Panics if `at > len`.
1878 /// use std::collections::VecDeque;
1880 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1881 /// let buf2 = buf.split_off(1);
1882 /// assert_eq!(buf, [1]);
1883 /// assert_eq!(buf2, [2, 3]);
1886 #[must_use = "use `.truncate()` if you don't need the other half"]
1887 #[stable(feature = "split_off", since = "1.4.0")]
1888 pub fn split_off(&mut self, at: usize) -> Self {
1889 let len = self.len();
1890 assert!(at <= len, "`at` out of bounds");
1892 let other_len = len - at;
1893 let mut other = VecDeque::with_capacity(other_len);
1896 let (first_half, second_half) = self.as_slices();
1898 let first_len = first_half.len();
1899 let second_len = second_half.len();
1901 // `at` lies in the first half.
1902 let amount_in_first = first_len - at;
1904 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
1906 // just take all of the second half.
1907 ptr::copy_nonoverlapping(
1908 second_half.as_ptr(),
1909 other.ptr().add(amount_in_first),
1913 // `at` lies in the second half, need to factor in the elements we skipped
1914 // in the first half.
1915 let offset = at - first_len;
1916 let amount_in_second = second_len - offset;
1917 ptr::copy_nonoverlapping(
1918 second_half.as_ptr().add(offset),
1925 // Cleanup where the ends of the buffers are
1926 self.head = self.wrap_sub(self.head, other_len);
1927 other.head = other.wrap_index(other_len);
1932 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1936 /// Panics if the new number of elements in self overflows a `usize`.
1941 /// use std::collections::VecDeque;
1943 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1944 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1945 /// buf.append(&mut buf2);
1946 /// assert_eq!(buf, [1, 2, 3, 4]);
1947 /// assert_eq!(buf2, []);
1950 #[stable(feature = "append", since = "1.4.0")]
1951 pub fn append(&mut self, other: &mut Self) {
1953 self.extend(other.drain(..));
1956 /// Retains only the elements specified by the predicate.
1958 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1959 /// This method operates in place, visiting each element exactly once in the
1960 /// original order, and preserves the order of the retained elements.
1965 /// use std::collections::VecDeque;
1967 /// let mut buf = VecDeque::new();
1968 /// buf.extend(1..5);
1969 /// buf.retain(|&x| x % 2 == 0);
1970 /// assert_eq!(buf, [2, 4]);
1973 /// The exact order may be useful for tracking external state, like an index.
1976 /// use std::collections::VecDeque;
1978 /// let mut buf = VecDeque::new();
1979 /// buf.extend(1..6);
1981 /// let keep = [false, true, true, false, true];
1983 /// buf.retain(|_| (keep[i], i += 1).0);
1984 /// assert_eq!(buf, [2, 3, 5]);
1986 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1987 pub fn retain<F>(&mut self, mut f: F)
1989 F: FnMut(&T) -> bool,
1991 let len = self.len();
1997 self.swap(i - del, i);
2001 self.truncate(len - del);
2005 // This may panic or abort
2007 fn grow_if_necessary(&mut self) {
2009 let old_cap = self.cap();
2012 self.handle_capacity_increase(old_cap);
2014 debug_assert!(!self.is_full());
2018 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
2019 /// either by removing excess elements from the back or by appending
2020 /// elements generated by calling `generator` to the back.
2025 /// use std::collections::VecDeque;
2027 /// let mut buf = VecDeque::new();
2028 /// buf.push_back(5);
2029 /// buf.push_back(10);
2030 /// buf.push_back(15);
2031 /// assert_eq!(buf, [5, 10, 15]);
2033 /// buf.resize_with(5, Default::default);
2034 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2036 /// buf.resize_with(2, || unreachable!());
2037 /// assert_eq!(buf, [5, 10]);
2039 /// let mut state = 100;
2040 /// buf.resize_with(5, || { state += 1; state });
2041 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2043 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2044 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2045 let len = self.len();
2048 self.extend(repeat_with(generator).take(new_len - len))
2050 self.truncate(new_len);
2054 /// Rearranges the internal storage of this deque so it is one contiguous slice, which is then returned.
2056 /// This method does not allocate and does not change the order of the inserted elements.
2057 /// As it returns a mutable slice, this can be used to sort or binary search a deque.
2059 /// Once the internal storage is contiguous, the [`as_slices`](#method.as_slices) and
2060 /// [`as_mut_slices`](#method.as_mut_slices) methods will return the entire contents of the
2061 /// `VecDeque` in a single slice.
2065 /// Sorting the content of a deque.
2068 /// #![feature(deque_make_contiguous)]
2070 /// use std::collections::VecDeque;
2072 /// let mut buf = VecDeque::with_capacity(15);
2074 /// buf.push_back(2);
2075 /// buf.push_back(1);
2076 /// buf.push_front(3);
2078 /// // sorting the deque
2079 /// buf.make_contiguous().sort();
2080 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2082 /// // sorting it in reverse order
2083 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2084 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2087 /// Getting immutable access to the contiguous slice.
2090 /// #![feature(deque_make_contiguous)]
2092 /// use std::collections::VecDeque;
2094 /// let mut buf = VecDeque::new();
2096 /// buf.push_back(2);
2097 /// buf.push_back(1);
2098 /// buf.push_front(3);
2100 /// buf.make_contiguous();
2101 /// if let (slice, &[]) = buf.as_slices() {
2102 /// // we can now be sure that `slice` contains all elements of the deque,
2103 /// // while still having immutable access to `buf`.
2104 /// assert_eq!(buf.len(), slice.len());
2105 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2108 #[unstable(feature = "deque_make_contiguous", issue = "70929")]
2109 pub fn make_contiguous(&mut self) -> &mut [T] {
2110 if self.is_contiguous() {
2111 let tail = self.tail;
2112 let head = self.head;
2113 return unsafe { &mut self.buffer_as_mut_slice()[tail..head] };
2116 let buf = self.buf.ptr();
2117 let cap = self.cap();
2118 let len = self.len();
2120 let free = self.tail - self.head;
2121 let tail_len = cap - self.tail;
2123 if free >= tail_len {
2124 // there is enough free space to copy the tail in one go,
2125 // this means that we first shift the head backwards, and then
2126 // copy the tail to the correct position.
2128 // from: DEFGH....ABC
2131 ptr::copy(buf, buf.add(tail_len), self.head);
2133 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2139 } else if free >= self.head {
2140 // there is enough free space to copy the head in one go,
2141 // this means that we first shift the tail forwards, and then
2142 // copy the head to the correct position.
2144 // from: FGH....ABCDE
2147 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2149 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2152 self.tail = self.head;
2153 self.head = self.tail + len;
2156 // free is smaller than both head and tail,
2157 // this means we have to slowly "swap" the tail and the head.
2159 // from: EFGHI...ABCD or HIJK.ABCDEFG
2160 // to: ABCDEFGHI... or ABCDEFGHIJK.
2161 let mut left_edge: usize = 0;
2162 let mut right_edge: usize = self.tail;
2164 // The general problem looks like this
2165 // GHIJKLM...ABCDEF - before any swaps
2166 // ABCDEFM...GHIJKL - after 1 pass of swaps
2167 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2168 // - then restart the algorithm with a new (smaller) store
2169 // Sometimes the temp store is reached when the right edge is at the end
2170 // of the buffer - this means we've hit the right order with fewer swaps!
2173 // ABCDEF.. - after four only swaps we've finished
2174 while left_edge < len && right_edge != cap {
2175 let mut right_offset = 0;
2176 for i in left_edge..right_edge {
2177 right_offset = (i - left_edge) % (cap - right_edge);
2178 let src: isize = (right_edge + right_offset) as isize;
2179 ptr::swap(buf.add(i), buf.offset(src));
2181 let n_ops = right_edge - left_edge;
2183 right_edge += right_offset + 1;
2191 let tail = self.tail;
2192 let head = self.head;
2193 unsafe { &mut self.buffer_as_mut_slice()[tail..head] }
2196 /// Rotates the double-ended queue `mid` places to the left.
2199 /// - Rotates item `mid` into the first position.
2200 /// - Pops the first `mid` items and pushes them to the end.
2201 /// - Rotates `len() - mid` places to the right.
2205 /// If `mid` is greater than `len()`. Note that `mid == len()`
2206 /// does _not_ panic and is a no-op rotation.
2210 /// Takes `O(min(mid, len() - mid))` time and no extra space.
2215 /// use std::collections::VecDeque;
2217 /// let mut buf: VecDeque<_> = (0..10).collect();
2219 /// buf.rotate_left(3);
2220 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2222 /// for i in 1..10 {
2223 /// assert_eq!(i * 3 % 10, buf[0]);
2224 /// buf.rotate_left(3);
2226 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2228 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2229 pub fn rotate_left(&mut self, mid: usize) {
2230 assert!(mid <= self.len());
2231 let k = self.len() - mid;
2233 unsafe { self.rotate_left_inner(mid) }
2235 unsafe { self.rotate_right_inner(k) }
2239 /// Rotates the double-ended queue `k` places to the right.
2242 /// - Rotates the first item into position `k`.
2243 /// - Pops the last `k` items and pushes them to the front.
2244 /// - Rotates `len() - k` places to the left.
2248 /// If `k` is greater than `len()`. Note that `k == len()`
2249 /// does _not_ panic and is a no-op rotation.
2253 /// Takes `O(min(k, len() - k))` time and no extra space.
2258 /// use std::collections::VecDeque;
2260 /// let mut buf: VecDeque<_> = (0..10).collect();
2262 /// buf.rotate_right(3);
2263 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2265 /// for i in 1..10 {
2266 /// assert_eq!(0, buf[i * 3 % 10]);
2267 /// buf.rotate_right(3);
2269 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2271 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2272 pub fn rotate_right(&mut self, k: usize) {
2273 assert!(k <= self.len());
2274 let mid = self.len() - k;
2276 unsafe { self.rotate_right_inner(k) }
2278 unsafe { self.rotate_left_inner(mid) }
2282 // Safety: the following two methods require that the rotation amount
2283 // be less than half the length of the deque.
2285 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2286 // but than `min` is never more than half the capacity, regardless of x,
2287 // so it's sound to call here because we're calling with something
2288 // less than half the length, which is never above half the capacity.
2290 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2291 debug_assert!(mid * 2 <= self.len());
2292 self.wrap_copy(self.head, self.tail, mid);
2293 self.head = self.wrap_add(self.head, mid);
2294 self.tail = self.wrap_add(self.tail, mid);
2297 unsafe fn rotate_right_inner(&mut self, k: usize) {
2298 debug_assert!(k * 2 <= self.len());
2299 self.head = self.wrap_sub(self.head, k);
2300 self.tail = self.wrap_sub(self.tail, k);
2301 self.wrap_copy(self.tail, self.head, k);
2305 impl<T: Clone> VecDeque<T> {
2306 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2307 /// either by removing excess elements from the back or by appending clones of `value`
2313 /// use std::collections::VecDeque;
2315 /// let mut buf = VecDeque::new();
2316 /// buf.push_back(5);
2317 /// buf.push_back(10);
2318 /// buf.push_back(15);
2319 /// assert_eq!(buf, [5, 10, 15]);
2321 /// buf.resize(2, 0);
2322 /// assert_eq!(buf, [5, 10]);
2324 /// buf.resize(5, 20);
2325 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2327 #[stable(feature = "deque_extras", since = "1.16.0")]
2328 pub fn resize(&mut self, new_len: usize, value: T) {
2329 self.resize_with(new_len, || value.clone());
2333 /// Returns the index in the underlying buffer for a given logical element index.
2335 fn wrap_index(index: usize, size: usize) -> usize {
2336 // size is always a power of 2
2337 debug_assert!(size.is_power_of_two());
2341 /// Returns the two slices that cover the `VecDeque`'s valid range
2342 trait RingSlices: Sized {
2343 fn slice(self, from: usize, to: usize) -> Self;
2344 fn split_at(self, i: usize) -> (Self, Self);
2346 fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
2347 let contiguous = tail <= head;
2349 let (empty, buf) = buf.split_at(0);
2350 (buf.slice(tail, head), empty)
2352 let (mid, right) = buf.split_at(tail);
2353 let (left, _) = mid.split_at(head);
2359 impl<T> RingSlices for &[T] {
2360 fn slice(self, from: usize, to: usize) -> Self {
2363 fn split_at(self, i: usize) -> (Self, Self) {
2368 impl<T> RingSlices for &mut [T] {
2369 fn slice(self, from: usize, to: usize) -> Self {
2372 fn split_at(self, i: usize) -> (Self, Self) {
2373 (*self).split_at_mut(i)
2377 /// Calculate the number of elements left to be read in the buffer
2379 fn count(tail: usize, head: usize, size: usize) -> usize {
2380 // size is always a power of 2
2381 (head.wrapping_sub(tail)) & (size - 1)
2384 /// An iterator over the elements of a `VecDeque`.
2386 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
2387 /// documentation for more.
2389 /// [`iter`]: struct.VecDeque.html#method.iter
2390 /// [`VecDeque`]: struct.VecDeque.html
2391 #[stable(feature = "rust1", since = "1.0.0")]
2392 pub struct Iter<'a, T: 'a> {
2398 #[stable(feature = "collection_debug", since = "1.17.0")]
2399 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
2400 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2401 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2402 f.debug_tuple("Iter").field(&front).field(&back).finish()
2406 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 impl<T> Clone for Iter<'_, T> {
2409 fn clone(&self) -> Self {
2410 Iter { ring: self.ring, tail: self.tail, head: self.head }
2414 #[stable(feature = "rust1", since = "1.0.0")]
2415 impl<'a, T> Iterator for Iter<'a, T> {
2419 fn next(&mut self) -> Option<&'a T> {
2420 if self.tail == self.head {
2423 let tail = self.tail;
2424 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2425 unsafe { Some(self.ring.get_unchecked(tail)) }
2429 fn size_hint(&self) -> (usize, Option<usize>) {
2430 let len = count(self.tail, self.head, self.ring.len());
2434 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2436 F: FnMut(Acc, Self::Item) -> Acc,
2438 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2439 accum = front.iter().fold(accum, &mut f);
2440 back.iter().fold(accum, &mut f)
2443 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2446 F: FnMut(B, Self::Item) -> R,
2449 let (mut iter, final_res);
2450 if self.tail <= self.head {
2451 // single slice self.ring[self.tail..self.head]
2452 iter = self.ring[self.tail..self.head].iter();
2453 final_res = iter.try_fold(init, &mut f);
2455 // two slices: self.ring[self.tail..], self.ring[..self.head]
2456 let (front, back) = self.ring.split_at(self.tail);
2457 let mut back_iter = back.iter();
2458 let res = back_iter.try_fold(init, &mut f);
2459 let len = self.ring.len();
2460 self.tail = (self.ring.len() - back_iter.len()) & (len - 1);
2461 iter = front[..self.head].iter();
2462 final_res = iter.try_fold(res?, &mut f);
2464 self.tail = self.head - iter.len();
2468 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2469 if n >= count(self.tail, self.head, self.ring.len()) {
2470 self.tail = self.head;
2473 self.tail = wrap_index(self.tail.wrapping_add(n), self.ring.len());
2479 fn last(mut self) -> Option<&'a T> {
2484 #[stable(feature = "rust1", since = "1.0.0")]
2485 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2487 fn next_back(&mut self) -> Option<&'a T> {
2488 if self.tail == self.head {
2491 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2492 unsafe { Some(self.ring.get_unchecked(self.head)) }
2495 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2497 F: FnMut(Acc, Self::Item) -> Acc,
2499 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2500 accum = back.iter().rfold(accum, &mut f);
2501 front.iter().rfold(accum, &mut f)
2504 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
2507 F: FnMut(B, Self::Item) -> R,
2510 let (mut iter, final_res);
2511 if self.tail <= self.head {
2512 // single slice self.ring[self.tail..self.head]
2513 iter = self.ring[self.tail..self.head].iter();
2514 final_res = iter.try_rfold(init, &mut f);
2516 // two slices: self.ring[self.tail..], self.ring[..self.head]
2517 let (front, back) = self.ring.split_at(self.tail);
2518 let mut front_iter = front[..self.head].iter();
2519 let res = front_iter.try_rfold(init, &mut f);
2520 self.head = front_iter.len();
2522 final_res = iter.try_rfold(res?, &mut f);
2524 self.head = self.tail + iter.len();
2529 #[stable(feature = "rust1", since = "1.0.0")]
2530 impl<T> ExactSizeIterator for Iter<'_, T> {
2531 fn is_empty(&self) -> bool {
2532 self.head == self.tail
2536 #[stable(feature = "fused", since = "1.26.0")]
2537 impl<T> FusedIterator for Iter<'_, T> {}
2539 /// A mutable iterator over the elements of a `VecDeque`.
2541 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2542 /// documentation for more.
2544 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2545 /// [`VecDeque`]: struct.VecDeque.html
2546 #[stable(feature = "rust1", since = "1.0.0")]
2547 pub struct IterMut<'a, T: 'a> {
2553 #[stable(feature = "collection_debug", since = "1.17.0")]
2554 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
2555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2556 let (front, back) = RingSlices::ring_slices(&*self.ring, self.head, self.tail);
2557 f.debug_tuple("IterMut").field(&front).field(&back).finish()
2561 #[stable(feature = "rust1", since = "1.0.0")]
2562 impl<'a, T> Iterator for IterMut<'a, T> {
2563 type Item = &'a mut T;
2566 fn next(&mut self) -> Option<&'a mut T> {
2567 if self.tail == self.head {
2570 let tail = self.tail;
2571 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2574 let elem = self.ring.get_unchecked_mut(tail);
2575 Some(&mut *(elem as *mut _))
2580 fn size_hint(&self) -> (usize, Option<usize>) {
2581 let len = count(self.tail, self.head, self.ring.len());
2585 fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2587 F: FnMut(Acc, Self::Item) -> Acc,
2589 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2590 accum = front.iter_mut().fold(accum, &mut f);
2591 back.iter_mut().fold(accum, &mut f)
2594 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2595 if n >= count(self.tail, self.head, self.ring.len()) {
2596 self.tail = self.head;
2599 self.tail = wrap_index(self.tail.wrapping_add(n), self.ring.len());
2605 fn last(mut self) -> Option<&'a mut T> {
2610 #[stable(feature = "rust1", since = "1.0.0")]
2611 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2613 fn next_back(&mut self) -> Option<&'a mut T> {
2614 if self.tail == self.head {
2617 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2620 let elem = self.ring.get_unchecked_mut(self.head);
2621 Some(&mut *(elem as *mut _))
2625 fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2627 F: FnMut(Acc, Self::Item) -> Acc,
2629 let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2630 accum = back.iter_mut().rfold(accum, &mut f);
2631 front.iter_mut().rfold(accum, &mut f)
2635 #[stable(feature = "rust1", since = "1.0.0")]
2636 impl<T> ExactSizeIterator for IterMut<'_, T> {
2637 fn is_empty(&self) -> bool {
2638 self.head == self.tail
2642 #[stable(feature = "fused", since = "1.26.0")]
2643 impl<T> FusedIterator for IterMut<'_, T> {}
2645 /// An owning iterator over the elements of a `VecDeque`.
2647 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`]
2648 /// (provided by the `IntoIterator` trait). See its documentation for more.
2650 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2651 /// [`VecDeque`]: struct.VecDeque.html
2653 #[stable(feature = "rust1", since = "1.0.0")]
2654 pub struct IntoIter<T> {
2658 #[stable(feature = "collection_debug", since = "1.17.0")]
2659 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2661 f.debug_tuple("IntoIter").field(&self.inner).finish()
2665 #[stable(feature = "rust1", since = "1.0.0")]
2666 impl<T> Iterator for IntoIter<T> {
2670 fn next(&mut self) -> Option<T> {
2671 self.inner.pop_front()
2675 fn size_hint(&self) -> (usize, Option<usize>) {
2676 let len = self.inner.len();
2681 #[stable(feature = "rust1", since = "1.0.0")]
2682 impl<T> DoubleEndedIterator for IntoIter<T> {
2684 fn next_back(&mut self) -> Option<T> {
2685 self.inner.pop_back()
2689 #[stable(feature = "rust1", since = "1.0.0")]
2690 impl<T> ExactSizeIterator for IntoIter<T> {
2691 fn is_empty(&self) -> bool {
2692 self.inner.is_empty()
2696 #[stable(feature = "fused", since = "1.26.0")]
2697 impl<T> FusedIterator for IntoIter<T> {}
2699 #[stable(feature = "rust1", since = "1.0.0")]
2700 impl<A: PartialEq> PartialEq for VecDeque<A> {
2701 fn eq(&self, other: &VecDeque<A>) -> bool {
2702 if self.len() != other.len() {
2705 let (sa, sb) = self.as_slices();
2706 let (oa, ob) = other.as_slices();
2707 if sa.len() == oa.len() {
2708 sa == oa && sb == ob
2709 } else if sa.len() < oa.len() {
2710 // Always divisible in three sections, for example:
2711 // self: [a b c|d e f]
2712 // other: [0 1 2 3|4 5]
2713 // front = 3, mid = 1,
2714 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2715 let front = sa.len();
2716 let mid = oa.len() - front;
2718 let (oa_front, oa_mid) = oa.split_at(front);
2719 let (sb_mid, sb_back) = sb.split_at(mid);
2720 debug_assert_eq!(sa.len(), oa_front.len());
2721 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2722 debug_assert_eq!(sb_back.len(), ob.len());
2723 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2725 let front = oa.len();
2726 let mid = sa.len() - front;
2728 let (sa_front, sa_mid) = sa.split_at(front);
2729 let (ob_mid, ob_back) = ob.split_at(mid);
2730 debug_assert_eq!(sa_front.len(), oa.len());
2731 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2732 debug_assert_eq!(sb.len(), ob_back.len());
2733 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2738 #[stable(feature = "rust1", since = "1.0.0")]
2739 impl<A: Eq> Eq for VecDeque<A> {}
2741 macro_rules! __impl_slice_eq1 {
2742 ([$($vars:tt)*] $lhs:ty, $rhs:ty, $($constraints:tt)*) => {
2743 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2744 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2749 fn eq(&self, other: &$rhs) -> bool {
2750 if self.len() != other.len() {
2753 let (sa, sb) = self.as_slices();
2754 let (oa, ob) = other[..].split_at(sa.len());
2755 sa == oa && sb == ob
2761 __impl_slice_eq1! { [] VecDeque<A>, Vec<B>, }
2762 __impl_slice_eq1! { [] VecDeque<A>, &[B], }
2763 __impl_slice_eq1! { [] VecDeque<A>, &mut [B], }
2764 __impl_slice_eq1! { [const N: usize] VecDeque<A>, [B; N], [B; N]: LengthAtMost32 }
2765 __impl_slice_eq1! { [const N: usize] VecDeque<A>, &[B; N], [B; N]: LengthAtMost32 }
2766 __impl_slice_eq1! { [const N: usize] VecDeque<A>, &mut [B; N], [B; N]: LengthAtMost32 }
2768 #[stable(feature = "rust1", since = "1.0.0")]
2769 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2770 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2771 self.iter().partial_cmp(other.iter())
2775 #[stable(feature = "rust1", since = "1.0.0")]
2776 impl<A: Ord> Ord for VecDeque<A> {
2778 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2779 self.iter().cmp(other.iter())
2783 #[stable(feature = "rust1", since = "1.0.0")]
2784 impl<A: Hash> Hash for VecDeque<A> {
2785 fn hash<H: Hasher>(&self, state: &mut H) {
2786 self.len().hash(state);
2787 let (a, b) = self.as_slices();
2788 Hash::hash_slice(a, state);
2789 Hash::hash_slice(b, state);
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<A> Index<usize> for VecDeque<A> {
2798 fn index(&self, index: usize) -> &A {
2799 self.get(index).expect("Out of bounds access")
2803 #[stable(feature = "rust1", since = "1.0.0")]
2804 impl<A> IndexMut<usize> for VecDeque<A> {
2806 fn index_mut(&mut self, index: usize) -> &mut A {
2807 self.get_mut(index).expect("Out of bounds access")
2811 #[stable(feature = "rust1", since = "1.0.0")]
2812 impl<A> FromIterator<A> for VecDeque<A> {
2813 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2814 let iterator = iter.into_iter();
2815 let (lower, _) = iterator.size_hint();
2816 let mut deq = VecDeque::with_capacity(lower);
2817 deq.extend(iterator);
2822 #[stable(feature = "rust1", since = "1.0.0")]
2823 impl<T> IntoIterator for VecDeque<T> {
2825 type IntoIter = IntoIter<T>;
2827 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2829 fn into_iter(self) -> IntoIter<T> {
2830 IntoIter { inner: self }
2834 #[stable(feature = "rust1", since = "1.0.0")]
2835 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2837 type IntoIter = Iter<'a, T>;
2839 fn into_iter(self) -> Iter<'a, T> {
2844 #[stable(feature = "rust1", since = "1.0.0")]
2845 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2846 type Item = &'a mut T;
2847 type IntoIter = IterMut<'a, T>;
2849 fn into_iter(self) -> IterMut<'a, T> {
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 impl<A> Extend<A> for VecDeque<A> {
2856 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2857 // This function should be the moral equivalent of:
2859 // for item in iter.into_iter() {
2860 // self.push_back(item);
2862 let mut iter = iter.into_iter();
2863 while let Some(element) = iter.next() {
2864 if self.len() == self.capacity() {
2865 let (lower, _) = iter.size_hint();
2866 self.reserve(lower.saturating_add(1));
2869 let head = self.head;
2870 self.head = self.wrap_add(self.head, 1);
2872 self.buffer_write(head, element);
2878 #[stable(feature = "extend_ref", since = "1.2.0")]
2879 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2880 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2881 self.extend(iter.into_iter().cloned());
2885 #[stable(feature = "rust1", since = "1.0.0")]
2886 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2887 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2888 f.debug_list().entries(self).finish()
2892 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2893 impl<T> From<Vec<T>> for VecDeque<T> {
2894 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2896 /// [`Vec<T>`]: crate::vec::Vec
2897 /// [`VecDeque<T>`]: crate::collections::VecDeque
2899 /// This avoids reallocating where possible, but the conditions for that are
2900 /// strict, and subject to change, and so shouldn't be relied upon unless the
2901 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
2902 fn from(other: Vec<T>) -> Self {
2904 let mut other = ManuallyDrop::new(other);
2905 let other_buf = other.as_mut_ptr();
2906 let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2907 let len = other.len();
2909 // We need to extend the buf if it's not a power of two, too small
2910 // or doesn't have at least one free space
2911 if !buf.capacity().is_power_of_two()
2912 || (buf.capacity() < (MINIMUM_CAPACITY + 1))
2913 || (buf.capacity() == len)
2915 let cap = cmp::max(buf.capacity() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2916 buf.reserve_exact(len, cap - len);
2919 VecDeque { tail: 0, head: len, buf }
2924 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2925 impl<T> From<VecDeque<T>> for Vec<T> {
2926 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2928 /// [`Vec<T>`]: crate::vec::Vec
2929 /// [`VecDeque<T>`]: crate::collections::VecDeque
2931 /// This never needs to re-allocate, but does need to do `O(n)` data movement if
2932 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2937 /// use std::collections::VecDeque;
2939 /// // This one is O(1).
2940 /// let deque: VecDeque<_> = (1..5).collect();
2941 /// let ptr = deque.as_slices().0.as_ptr();
2942 /// let vec = Vec::from(deque);
2943 /// assert_eq!(vec, [1, 2, 3, 4]);
2944 /// assert_eq!(vec.as_ptr(), ptr);
2946 /// // This one needs data rearranging.
2947 /// let mut deque: VecDeque<_> = (1..5).collect();
2948 /// deque.push_front(9);
2949 /// deque.push_front(8);
2950 /// let ptr = deque.as_slices().1.as_ptr();
2951 /// let vec = Vec::from(deque);
2952 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2953 /// assert_eq!(vec.as_ptr(), ptr);
2955 fn from(mut other: VecDeque<T>) -> Self {
2956 other.make_contiguous();
2959 let other = ManuallyDrop::new(other);
2960 let buf = other.buf.ptr();
2961 let len = other.len();
2962 let cap = other.cap();
2964 if other.head != 0 {
2965 ptr::copy(buf.add(other.tail), buf, len);
2967 Vec::from_raw_parts(buf, len, cap)