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 #[stable(feature = "rust1", since = "1.0.0")]
54 pub struct VecDeque
<T
> {
55 // tail and head are pointers into the buffer. Tail always points
56 // to the first element that could be read, Head always points
57 // to where data should be written.
58 // If tail == head the buffer is empty. The length of the ringbuffer
59 // is defined as the distance between the two.
65 /// PairSlices pairs up equal length slice parts of two deques
67 /// For example, given deques "A" and "B" with the following division into slices:
69 /// A: [0 1 2] [3 4 5]
72 /// It produces the following sequence of matching slices:
78 /// and the uneven remainder of either A or B is skipped.
79 struct PairSlices
<'a
, 'b
, T
> {
86 impl<'a
, 'b
, T
> PairSlices
<'a
, 'b
, T
> {
87 fn from(to
: &'a
mut VecDeque
<T
>, from
: &'b VecDeque
<T
>) -> Self {
88 let (a0
, a1
) = to
.as_mut_slices();
89 let (b0
, b1
) = from
.as_slices();
90 PairSlices { a0, a1, b0, b1 }
93 fn has_remainder(&self) -> bool
{
97 fn remainder(self) -> impl Iterator
<Item
= &'b
[T
]> {
98 once(self.b0
).chain(once(self.b1
))
102 impl<'a
, 'b
, T
> Iterator
for PairSlices
<'a
, 'b
, T
> {
103 type Item
= (&'a
mut [T
], &'b
[T
]);
104 fn next(&mut self) -> Option
<Self::Item
> {
105 // Get next part length
106 let part
= cmp
::min(self.a0
.len(), self.b0
.len());
110 let (p0
, p1
) = replace(&mut self.a0
, &mut []).split_at_mut(part
);
111 let (q0
, q1
) = self.b0
.split_at(part
);
113 // Move a1 into a0, if it's empty (and b1, b0 the same way).
116 if self.a0
.is_empty() {
117 self.a0
= replace(&mut self.a1
, &mut []);
119 if self.b0
.is_empty() {
120 self.b0
= replace(&mut self.b1
, &[]);
126 #[stable(feature = "rust1", since = "1.0.0")]
127 impl<T
: Clone
> Clone
for VecDeque
<T
> {
128 fn clone(&self) -> VecDeque
<T
> {
129 self.iter().cloned().collect()
132 fn clone_from(&mut self, other
: &Self) {
133 self.truncate(other
.len());
135 let mut iter
= PairSlices
::from(self, other
);
136 while let Some((dst
, src
)) = iter
.next() {
137 dst
.clone_from_slice(&src
);
140 if iter
.has_remainder() {
141 for remainder
in iter
.remainder() {
142 self.extend(remainder
.iter().cloned());
148 #[stable(feature = "rust1", since = "1.0.0")]
149 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
151 /// Runs the destructor for all items in the slice when it gets dropped (normally or
152 /// during unwinding).
153 struct Dropper
<'a
, T
>(&'a
mut [T
]);
155 impl<'a
, T
> Drop
for Dropper
<'a
, T
> {
158 ptr
::drop_in_place(self.0);
163 let (front
, back
) = self.as_mut_slices();
165 let _back_dropper
= Dropper(back
);
167 ptr
::drop_in_place(front
);
169 // RawVec handles deallocation
173 #[stable(feature = "rust1", since = "1.0.0")]
174 impl<T
> Default
for VecDeque
<T
> {
175 /// Creates an empty `VecDeque<T>`.
177 fn default() -> VecDeque
<T
> {
182 impl<T
> VecDeque
<T
> {
183 /// Marginally more convenient
185 fn ptr(&self) -> *mut T
{
189 /// Marginally more convenient
191 fn cap(&self) -> usize {
192 if mem
::size_of
::<T
>() == 0 {
193 // For zero sized types, we are always at maximum capacity
200 /// Turn ptr into a slice
202 unsafe fn buffer_as_slice(&self) -> &[T
] {
203 slice
::from_raw_parts(self.ptr(), self.cap())
206 /// Turn ptr into a mut slice
208 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T
] {
209 slice
::from_raw_parts_mut(self.ptr(), self.cap())
212 /// Moves an element out of the buffer
214 unsafe fn buffer_read(&mut self, off
: usize) -> T
{
215 ptr
::read(self.ptr().add(off
))
218 /// Writes an element into the buffer, moving it.
220 unsafe fn buffer_write(&mut self, off
: usize, value
: T
) {
221 ptr
::write(self.ptr().add(off
), value
);
224 /// Returns `true` if the buffer is at full capacity.
226 fn is_full(&self) -> bool
{
227 self.cap() - self.len() == 1
230 /// Returns the index in the underlying buffer for a given logical element
233 fn wrap_index(&self, idx
: usize) -> usize {
234 wrap_index(idx
, self.cap())
237 /// Returns the index in the underlying buffer for a given logical element
240 fn wrap_add(&self, idx
: usize, addend
: usize) -> usize {
241 wrap_index(idx
.wrapping_add(addend
), self.cap())
244 /// Returns the index in the underlying buffer for a given logical element
245 /// index - subtrahend.
247 fn wrap_sub(&self, idx
: usize, subtrahend
: usize) -> usize {
248 wrap_index(idx
.wrapping_sub(subtrahend
), self.cap())
251 /// Copies a contiguous block of memory len long from src to dst
253 unsafe fn copy(&self, dst
: usize, src
: usize, len
: usize) {
255 dst
+ len
<= self.cap(),
256 "cpy dst={} src={} len={} cap={}",
263 src
+ len
<= self.cap(),
264 "cpy dst={} src={} len={} cap={}",
270 ptr
::copy(self.ptr().add(src
), self.ptr().add(dst
), len
);
273 /// Copies a contiguous block of memory len long from src to dst
275 unsafe fn copy_nonoverlapping(&self, dst
: usize, src
: usize, len
: usize) {
277 dst
+ len
<= self.cap(),
278 "cno dst={} src={} len={} cap={}",
285 src
+ len
<= self.cap(),
286 "cno dst={} src={} len={} cap={}",
292 ptr
::copy_nonoverlapping(self.ptr().add(src
), self.ptr().add(dst
), len
);
295 /// Copies a potentially wrapping block of memory len long from src to dest.
296 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
297 /// most one continuous overlapping region between src and dest).
298 unsafe fn wrap_copy(&self, dst
: usize, src
: usize, len
: usize) {
300 fn diff(a
: usize, b
: usize) -> usize {
301 if a
<= b { b - a }
else { a - b }
304 cmp
::min(diff(dst
, src
), self.cap() - diff(dst
, src
)) + len
<= self.cap(),
305 "wrc dst={} src={} len={} cap={}",
312 if src
== dst
|| len
== 0 {
316 let dst_after_src
= self.wrap_sub(dst
, src
) < len
;
318 let src_pre_wrap_len
= self.cap() - src
;
319 let dst_pre_wrap_len
= self.cap() - dst
;
320 let src_wraps
= src_pre_wrap_len
< len
;
321 let dst_wraps
= dst_pre_wrap_len
< len
;
323 match (dst_after_src
, src_wraps
, dst_wraps
) {
324 (_
, false, false) => {
325 // src doesn't wrap, dst doesn't wrap
328 // 1 [_ _ A A B B C C _]
329 // 2 [_ _ A A A A B B _]
332 self.copy(dst
, src
, len
);
334 (false, false, true) => {
335 // dst before src, src doesn't wrap, dst wraps
338 // 1 [A A B B _ _ _ C C]
339 // 2 [A A B B _ _ _ A A]
340 // 3 [B B B B _ _ _ A A]
343 self.copy(dst
, src
, dst_pre_wrap_len
);
344 self.copy(0, src
+ dst_pre_wrap_len
, len
- dst_pre_wrap_len
);
346 (true, false, true) => {
347 // src before dst, src doesn't wrap, dst wraps
350 // 1 [C C _ _ _ A A B B]
351 // 2 [B B _ _ _ A A B B]
352 // 3 [B B _ _ _ A A A A]
355 self.copy(0, src
+ dst_pre_wrap_len
, len
- dst_pre_wrap_len
);
356 self.copy(dst
, src
, dst_pre_wrap_len
);
358 (false, true, false) => {
359 // dst before src, src wraps, dst doesn't wrap
362 // 1 [C C _ _ _ A A B B]
363 // 2 [C C _ _ _ B B B B]
364 // 3 [C C _ _ _ B B C C]
367 self.copy(dst
, src
, src_pre_wrap_len
);
368 self.copy(dst
+ src_pre_wrap_len
, 0, len
- src_pre_wrap_len
);
370 (true, true, false) => {
371 // src before dst, src wraps, dst doesn't wrap
374 // 1 [A A B B _ _ _ C C]
375 // 2 [A A A A _ _ _ C C]
376 // 3 [C C A A _ _ _ C C]
379 self.copy(dst
+ src_pre_wrap_len
, 0, len
- src_pre_wrap_len
);
380 self.copy(dst
, src
, src_pre_wrap_len
);
382 (false, true, true) => {
383 // dst before src, src wraps, dst wraps
386 // 1 [A B C D _ E F G H]
387 // 2 [A B C D _ E G H H]
388 // 3 [A B C D _ E G H A]
389 // 4 [B C C D _ E G H A]
392 debug_assert
!(dst_pre_wrap_len
> src_pre_wrap_len
);
393 let delta
= dst_pre_wrap_len
- src_pre_wrap_len
;
394 self.copy(dst
, src
, src_pre_wrap_len
);
395 self.copy(dst
+ src_pre_wrap_len
, 0, delta
);
396 self.copy(0, delta
, len
- dst_pre_wrap_len
);
398 (true, true, true) => {
399 // src before dst, src wraps, dst wraps
402 // 1 [A B C D _ E F G H]
403 // 2 [A A B D _ E F G H]
404 // 3 [H A B D _ E F G H]
405 // 4 [H A B D _ E F F G]
408 debug_assert
!(src_pre_wrap_len
> dst_pre_wrap_len
);
409 let delta
= src_pre_wrap_len
- dst_pre_wrap_len
;
410 self.copy(delta
, 0, len
- src_pre_wrap_len
);
411 self.copy(0, self.cap() - delta
, delta
);
412 self.copy(dst
, src
, dst_pre_wrap_len
);
417 /// Frobs the head and tail sections around to handle the fact that we
418 /// just reallocated. Unsafe because it trusts old_capacity.
420 unsafe fn handle_capacity_increase(&mut self, old_capacity
: usize) {
421 let new_capacity
= self.cap();
423 // Move the shortest contiguous section of the ring buffer
425 // [o o o o o o o . ]
427 // A [o o o o o o o . . . . . . . . . ]
429 // [o o . o o o o o ]
431 // B [. . . o o o o o o o . . . . . . ]
433 // [o o o o o . o o ]
435 // C [o o o o o . . . . . . . . . o o ]
437 if self.tail
<= self.head
{
440 } else if self.head
< old_capacity
- self.tail
{
442 self.copy_nonoverlapping(old_capacity
, 0, self.head
);
443 self.head
+= old_capacity
;
444 debug_assert
!(self.head
> self.tail
);
447 let new_tail
= new_capacity
- (old_capacity
- self.tail
);
448 self.copy_nonoverlapping(new_tail
, self.tail
, old_capacity
- self.tail
);
449 self.tail
= new_tail
;
450 debug_assert
!(self.head
< self.tail
);
452 debug_assert
!(self.head
< self.cap());
453 debug_assert
!(self.tail
< self.cap());
454 debug_assert
!(self.cap().count_ones() == 1);
458 impl<T
> VecDeque
<T
> {
459 /// Creates an empty `VecDeque`.
464 /// use std::collections::VecDeque;
466 /// let vector: VecDeque<u32> = VecDeque::new();
468 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn new() -> VecDeque
<T
> {
470 VecDeque
::with_capacity(INITIAL_CAPACITY
)
473 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
478 /// use std::collections::VecDeque;
480 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn with_capacity(capacity
: usize) -> VecDeque
<T
> {
484 // +1 since the ringbuffer always leaves one space empty
485 let cap
= cmp
::max(capacity
+ 1, MINIMUM_CAPACITY
+ 1).next_power_of_two();
486 assert
!(cap
> capacity
, "capacity overflow");
488 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity(cap) }
491 /// Provides a reference to the element at the given index.
493 /// Element at index 0 is the front of the queue.
498 /// use std::collections::VecDeque;
500 /// let mut buf = VecDeque::new();
501 /// buf.push_back(3);
502 /// buf.push_back(4);
503 /// buf.push_back(5);
504 /// assert_eq!(buf.get(1), Some(&4));
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub fn get(&self, index
: usize) -> Option
<&T
> {
508 if index
< self.len() {
509 let idx
= self.wrap_add(self.tail
, index
);
510 unsafe { Some(&*self.ptr().add(idx)) }
516 /// Provides a mutable reference to the element at the given index.
518 /// Element at index 0 is the front of the queue.
523 /// use std::collections::VecDeque;
525 /// let mut buf = VecDeque::new();
526 /// buf.push_back(3);
527 /// buf.push_back(4);
528 /// buf.push_back(5);
529 /// if let Some(elem) = buf.get_mut(1) {
533 /// assert_eq!(buf[1], 7);
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn get_mut(&mut self, index
: usize) -> Option
<&mut T
> {
537 if index
< self.len() {
538 let idx
= self.wrap_add(self.tail
, index
);
539 unsafe { Some(&mut *self.ptr().add(idx)) }
545 /// Swaps elements at indices `i` and `j`.
547 /// `i` and `j` may be equal.
549 /// Element at index 0 is the front of the queue.
553 /// Panics if either index is out of bounds.
558 /// use std::collections::VecDeque;
560 /// let mut buf = VecDeque::new();
561 /// buf.push_back(3);
562 /// buf.push_back(4);
563 /// buf.push_back(5);
564 /// assert_eq!(buf, [3, 4, 5]);
566 /// assert_eq!(buf, [5, 4, 3]);
568 #[stable(feature = "rust1", since = "1.0.0")]
569 pub fn swap(&mut self, i
: usize, j
: usize) {
570 assert
!(i
< self.len());
571 assert
!(j
< self.len());
572 let ri
= self.wrap_add(self.tail
, i
);
573 let rj
= self.wrap_add(self.tail
, j
);
574 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
577 /// Returns the number of elements the `VecDeque` can hold without
583 /// use std::collections::VecDeque;
585 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
586 /// assert!(buf.capacity() >= 10);
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn capacity(&self) -> usize {
594 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
595 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
597 /// Note that the allocator may give the collection more space than it requests. Therefore
598 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
599 /// insertions are expected.
603 /// Panics if the new capacity overflows `usize`.
608 /// use std::collections::VecDeque;
610 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
611 /// buf.reserve_exact(10);
612 /// assert!(buf.capacity() >= 11);
615 /// [`reserve`]: #method.reserve
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn reserve_exact(&mut self, additional
: usize) {
618 self.reserve(additional
);
621 /// Reserves capacity for at least `additional` more elements to be inserted in the given
622 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
626 /// Panics if the new capacity overflows `usize`.
631 /// use std::collections::VecDeque;
633 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
635 /// assert!(buf.capacity() >= 11);
637 #[stable(feature = "rust1", since = "1.0.0")]
638 pub fn reserve(&mut self, additional
: usize) {
639 let old_cap
= self.cap();
640 let used_cap
= self.len() + 1;
641 let new_cap
= used_cap
642 .checked_add(additional
)
643 .and_then(|needed_cap
| needed_cap
.checked_next_power_of_two())
644 .expect("capacity overflow");
646 if new_cap
> old_cap
{
647 self.buf
.reserve_exact(used_cap
, new_cap
- used_cap
);
649 self.handle_capacity_increase(old_cap
);
654 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
655 /// be inserted in the given `VecDeque<T>`. After calling `reserve_exact`,
656 /// capacity will be greater than or equal to `self.len() + additional`.
657 /// Does nothing if the capacity is already sufficient.
659 /// Note that the allocator may give the collection more space than it
660 /// requests. Therefore, capacity can not be relied upon to be precisely
661 /// minimal. Prefer `reserve` if future insertions are expected.
665 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
671 /// #![feature(try_reserve)]
672 /// use std::collections::TryReserveError;
673 /// use std::collections::VecDeque;
675 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
676 /// let mut output = VecDeque::new();
678 /// // Pre-reserve the memory, exiting if we can't
679 /// output.try_reserve_exact(data.len())?;
681 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
682 /// output.extend(data.iter().map(|&val| {
683 /// val * 2 + 5 // very complicated
688 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
690 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
691 pub fn try_reserve_exact(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
692 self.try_reserve(additional
)
695 /// Tries to reserve capacity for at least `additional` more elements to be inserted
696 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
697 /// frequent reallocations. After calling `reserve`, capacity will be
698 /// greater than or equal to `self.len() + additional`. Does nothing if
699 /// capacity is already sufficient.
703 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
709 /// #![feature(try_reserve)]
710 /// use std::collections::TryReserveError;
711 /// use std::collections::VecDeque;
713 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
714 /// let mut output = VecDeque::new();
716 /// // Pre-reserve the memory, exiting if we can't
717 /// output.try_reserve(data.len())?;
719 /// // Now we know this can't OOM in the middle of our complex work
720 /// output.extend(data.iter().map(|&val| {
721 /// val * 2 + 5 // very complicated
726 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
728 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
729 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
730 let old_cap
= self.cap();
731 let used_cap
= self.len() + 1;
732 let new_cap
= used_cap
733 .checked_add(additional
)
734 .and_then(|needed_cap
| needed_cap
.checked_next_power_of_two())
735 .ok_or(TryReserveError
::CapacityOverflow
)?
;
737 if new_cap
> old_cap
{
738 self.buf
.try_reserve_exact(used_cap
, new_cap
- used_cap
)?
;
740 self.handle_capacity_increase(old_cap
);
746 /// Shrinks the capacity of the `VecDeque` as much as possible.
748 /// It will drop down as close as possible to the length but the allocator may still inform the
749 /// `VecDeque` that there is space for a few more elements.
754 /// use std::collections::VecDeque;
756 /// let mut buf = VecDeque::with_capacity(15);
757 /// buf.extend(0..4);
758 /// assert_eq!(buf.capacity(), 15);
759 /// buf.shrink_to_fit();
760 /// assert!(buf.capacity() >= 4);
762 #[stable(feature = "deque_extras_15", since = "1.5.0")]
763 pub fn shrink_to_fit(&mut self) {
767 /// Shrinks the capacity of the `VecDeque` with a lower bound.
769 /// The capacity will remain at least as large as both the length
770 /// and the supplied value.
772 /// Panics if the current capacity is smaller than the supplied
773 /// minimum capacity.
778 /// #![feature(shrink_to)]
779 /// use std::collections::VecDeque;
781 /// let mut buf = VecDeque::with_capacity(15);
782 /// buf.extend(0..4);
783 /// assert_eq!(buf.capacity(), 15);
784 /// buf.shrink_to(6);
785 /// assert!(buf.capacity() >= 6);
786 /// buf.shrink_to(0);
787 /// assert!(buf.capacity() >= 4);
789 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
790 pub fn shrink_to(&mut self, min_capacity
: usize) {
791 assert
!(self.capacity() >= min_capacity
, "Tried to shrink to a larger capacity");
793 // +1 since the ringbuffer always leaves one space empty
794 // len + 1 can't overflow for an existing, well-formed ringbuffer.
795 let target_cap
= cmp
::max(cmp
::max(min_capacity
, self.len()) + 1, MINIMUM_CAPACITY
+ 1)
796 .next_power_of_two();
798 if target_cap
< self.cap() {
799 // There are three cases of interest:
800 // All elements are out of desired bounds
801 // Elements are contiguous, and head is out of desired bounds
802 // Elements are discontiguous, and tail is out of desired bounds
804 // At all other times, element positions are unaffected.
806 // Indicates that elements at the head should be moved.
807 let head_outside
= self.head
== 0 || self.head
>= target_cap
;
808 // Move elements from out of desired bounds (positions after target_cap)
809 if self.tail
>= target_cap
&& head_outside
{
811 // [. . . . . . . . o o o o o o o . ]
813 // [o o o o o o o . ]
815 self.copy_nonoverlapping(0, self.tail
, self.len());
817 self.head
= self.len();
819 } else if self.tail
!= 0 && self.tail
< target_cap
&& head_outside
{
821 // [. . . o o o o o o o . . . . . . ]
823 // [o o . o o o o o ]
824 let len
= self.wrap_sub(self.head
, target_cap
);
826 self.copy_nonoverlapping(0, target_cap
, len
);
829 debug_assert
!(self.head
< self.tail
);
830 } else if self.tail
>= target_cap
{
832 // [o o o o o . . . . . . . . . o o ]
834 // [o o o o o . o o ]
835 debug_assert
!(self.wrap_sub(self.head
, 1) < target_cap
);
836 let len
= self.cap() - self.tail
;
837 let new_tail
= target_cap
- len
;
839 self.copy_nonoverlapping(new_tail
, self.tail
, len
);
841 self.tail
= new_tail
;
842 debug_assert
!(self.head
< self.tail
);
845 self.buf
.shrink_to_fit(target_cap
);
847 debug_assert
!(self.head
< self.cap());
848 debug_assert
!(self.tail
< self.cap());
849 debug_assert
!(self.cap().count_ones() == 1);
853 /// Shortens the `VecDeque`, keeping the first `len` elements and dropping
856 /// If `len` is greater than the `VecDeque`'s current length, this has no
862 /// use std::collections::VecDeque;
864 /// let mut buf = VecDeque::new();
865 /// buf.push_back(5);
866 /// buf.push_back(10);
867 /// buf.push_back(15);
868 /// assert_eq!(buf, [5, 10, 15]);
870 /// assert_eq!(buf, [5]);
872 #[stable(feature = "deque_extras", since = "1.16.0")]
873 pub fn truncate(&mut self, len
: usize) {
874 /// Runs the destructor for all items in the slice when it gets dropped (normally or
875 /// during unwinding).
876 struct Dropper
<'a
, T
>(&'a
mut [T
]);
878 impl<'a
, T
> Drop
for Dropper
<'a
, T
> {
881 ptr
::drop_in_place(self.0);
888 // * Any slice passed to `drop_in_place` is valid; the second case has
889 // `len <= front.len()` and returning on `len > self.len()` ensures
890 // `begin <= back.len()` in the first case
891 // * The head of the VecDeque is moved before calling `drop_in_place`,
892 // so no value is dropped twice if `drop_in_place` panics
894 if len
> self.len() {
897 let num_dropped
= self.len() - len
;
898 let (front
, back
) = self.as_mut_slices();
899 if len
> front
.len() {
900 let begin
= len
- front
.len();
901 let drop_back
= back
.get_unchecked_mut(begin
..) as *mut _
;
902 self.head
= self.wrap_sub(self.head
, num_dropped
);
903 ptr
::drop_in_place(drop_back
);
905 let drop_back
= back
as *mut _
;
906 let drop_front
= front
.get_unchecked_mut(len
..) as *mut _
;
907 self.head
= self.wrap_sub(self.head
, num_dropped
);
909 // Make sure the second half is dropped even when a destructor
910 // in the first one panics.
911 let _back_dropper
= Dropper(&mut *drop_back
);
912 ptr
::drop_in_place(drop_front
);
917 /// Returns a front-to-back iterator.
922 /// use std::collections::VecDeque;
924 /// let mut buf = VecDeque::new();
925 /// buf.push_back(5);
926 /// buf.push_back(3);
927 /// buf.push_back(4);
928 /// let b: &[_] = &[&5, &3, &4];
929 /// let c: Vec<&i32> = buf.iter().collect();
930 /// assert_eq!(&c[..], b);
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn iter(&self) -> Iter
<'_
, T
> {
934 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() }
}
937 /// Returns a front-to-back iterator that returns mutable references.
942 /// use std::collections::VecDeque;
944 /// let mut buf = VecDeque::new();
945 /// buf.push_back(5);
946 /// buf.push_back(3);
947 /// buf.push_back(4);
948 /// for num in buf.iter_mut() {
951 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
952 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
954 #[stable(feature = "rust1", since = "1.0.0")]
955 pub fn iter_mut(&mut self) -> IterMut
<'_
, T
> {
956 IterMut { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_mut_slice() }
}
959 /// Returns a pair of slices which contain, in order, the contents of the
962 /// If [`make_contiguous`](#method.make_contiguous) was previously called, all elements
963 /// of the `VecDeque` will be in the first slice and the second slice will be empty.
968 /// use std::collections::VecDeque;
970 /// let mut vector = VecDeque::new();
972 /// vector.push_back(0);
973 /// vector.push_back(1);
974 /// vector.push_back(2);
976 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
978 /// vector.push_front(10);
979 /// vector.push_front(9);
981 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
984 #[stable(feature = "deque_extras_15", since = "1.5.0")]
985 pub fn as_slices(&self) -> (&[T
], &[T
]) {
987 let buf
= self.buffer_as_slice();
988 RingSlices
::ring_slices(buf
, self.head
, self.tail
)
992 /// Returns a pair of slices which contain, in order, the contents of the
995 /// If [`make_contiguous`](#method.make_contiguous) was previously called, all elements
996 /// of the `VecDeque` will be in the first slice and the second slice will be empty.
1001 /// use std::collections::VecDeque;
1003 /// let mut vector = VecDeque::new();
1005 /// vector.push_back(0);
1006 /// vector.push_back(1);
1008 /// vector.push_front(10);
1009 /// vector.push_front(9);
1011 /// vector.as_mut_slices().0[0] = 42;
1012 /// vector.as_mut_slices().1[0] = 24;
1013 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
1016 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1017 pub fn as_mut_slices(&mut self) -> (&mut [T
], &mut [T
]) {
1019 let head
= self.head
;
1020 let tail
= self.tail
;
1021 let buf
= self.buffer_as_mut_slice();
1022 RingSlices
::ring_slices(buf
, head
, tail
)
1026 /// Returns the number of elements in the `VecDeque`.
1031 /// use std::collections::VecDeque;
1033 /// let mut v = VecDeque::new();
1034 /// assert_eq!(v.len(), 0);
1036 /// assert_eq!(v.len(), 1);
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 pub fn len(&self) -> usize {
1040 count(self.tail
, self.head
, self.cap())
1043 /// Returns `true` if the `VecDeque` is empty.
1048 /// use std::collections::VecDeque;
1050 /// let mut v = VecDeque::new();
1051 /// assert!(v.is_empty());
1052 /// v.push_front(1);
1053 /// assert!(!v.is_empty());
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn is_empty(&self) -> bool
{
1057 self.tail
== self.head
1060 /// Creates a draining iterator that removes the specified range in the
1061 /// `VecDeque` and yields the removed items.
1063 /// Note 1: The element range is removed even if the iterator is not
1064 /// consumed until the end.
1066 /// Note 2: It is unspecified how many elements are removed from the deque,
1067 /// if the `Drain` value is not dropped, but the borrow it holds expires
1068 /// (e.g., due to `mem::forget`).
1072 /// Panics if the starting point is greater than the end point or if
1073 /// the end point is greater than the length of the vector.
1078 /// use std::collections::VecDeque;
1080 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1081 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
1082 /// assert_eq!(drained, [3]);
1083 /// assert_eq!(v, [1, 2]);
1085 /// // A full range clears all contents
1087 /// assert!(v.is_empty());
1090 #[stable(feature = "drain", since = "1.6.0")]
1091 pub fn drain
<R
>(&mut self, range
: R
) -> Drain
<'_
, T
>
1093 R
: RangeBounds
<usize>,
1097 // When the Drain is first created, the source deque is shortened to
1098 // make sure no uninitialized or moved-from elements are accessible at
1099 // all if the Drain's destructor never gets to run.
1101 // Drain will ptr::read out the values to remove.
1102 // When finished, the remaining data will be copied back to cover the hole,
1103 // and the head/tail values will be restored correctly.
1105 let len
= self.len();
1106 let start
= match range
.start_bound() {
1108 Excluded(&n
) => n
+ 1,
1111 let end
= match range
.end_bound() {
1112 Included(&n
) => n
+ 1,
1116 assert
!(start
<= end
, "drain lower bound was too large");
1117 assert
!(end
<= len
, "drain upper bound was too large");
1119 // The deque's elements are parted into three segments:
1120 // * self.tail -> drain_tail
1121 // * drain_tail -> drain_head
1122 // * drain_head -> self.head
1124 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1126 // We store drain_tail as self.head, and drain_head and self.head as
1127 // after_tail and after_head respectively on the Drain. This also
1128 // truncates the effective array such that if the Drain is leaked, we
1129 // have forgotten about the potentially moved values after the start of
1133 // [. . . o o x x o o . . .]
1135 let drain_tail
= self.wrap_add(self.tail
, start
);
1136 let drain_head
= self.wrap_add(self.tail
, end
);
1137 let head
= self.head
;
1139 // "forget" about the values after the start of the drain until after
1140 // the drain is complete and the Drain destructor is run.
1141 self.head
= drain_tail
;
1144 deque
: NonNull
::from(&mut *self),
1145 after_tail
: drain_head
,
1150 // Crucially, we only create shared references from `self` here and read from
1151 // it. We do not write to `self` nor reborrow to a mutable reference.
1152 // Hence the raw pointer we created above, for `deque`, remains valid.
1153 ring
: unsafe { self.buffer_as_slice() }
,
1158 /// Clears the `VecDeque`, removing all values.
1163 /// use std::collections::VecDeque;
1165 /// let mut v = VecDeque::new();
1168 /// assert!(v.is_empty());
1170 #[stable(feature = "rust1", since = "1.0.0")]
1172 pub fn clear(&mut self) {
1176 /// Returns `true` if the `VecDeque` contains an element equal to the
1182 /// use std::collections::VecDeque;
1184 /// let mut vector: VecDeque<u32> = VecDeque::new();
1186 /// vector.push_back(0);
1187 /// vector.push_back(1);
1189 /// assert_eq!(vector.contains(&1), true);
1190 /// assert_eq!(vector.contains(&10), false);
1192 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1193 pub fn contains(&self, x
: &T
) -> bool
1197 let (a
, b
) = self.as_slices();
1198 a
.contains(x
) || b
.contains(x
)
1201 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1207 /// use std::collections::VecDeque;
1209 /// let mut d = VecDeque::new();
1210 /// assert_eq!(d.front(), None);
1214 /// assert_eq!(d.front(), Some(&1));
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 pub fn front(&self) -> Option
<&T
> {
1218 if !self.is_empty() { Some(&self[0]) }
else { None }
1221 /// Provides a mutable reference to the front element, or `None` if the
1222 /// `VecDeque` is empty.
1227 /// use std::collections::VecDeque;
1229 /// let mut d = VecDeque::new();
1230 /// assert_eq!(d.front_mut(), None);
1234 /// match d.front_mut() {
1235 /// Some(x) => *x = 9,
1238 /// assert_eq!(d.front(), Some(&9));
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 pub fn front_mut(&mut self) -> Option
<&mut T
> {
1242 if !self.is_empty() { Some(&mut self[0]) }
else { None }
1245 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1251 /// use std::collections::VecDeque;
1253 /// let mut d = VecDeque::new();
1254 /// assert_eq!(d.back(), None);
1258 /// assert_eq!(d.back(), Some(&2));
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 pub fn back(&self) -> Option
<&T
> {
1262 if !self.is_empty() { Some(&self[self.len() - 1]) }
else { None }
1265 /// Provides a mutable reference to the back element, or `None` if the
1266 /// `VecDeque` is empty.
1271 /// use std::collections::VecDeque;
1273 /// let mut d = VecDeque::new();
1274 /// assert_eq!(d.back(), None);
1278 /// match d.back_mut() {
1279 /// Some(x) => *x = 9,
1282 /// assert_eq!(d.back(), Some(&9));
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 pub fn back_mut(&mut self) -> Option
<&mut T
> {
1286 let len
= self.len();
1287 if !self.is_empty() { Some(&mut self[len - 1]) }
else { None }
1290 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1296 /// use std::collections::VecDeque;
1298 /// let mut d = VecDeque::new();
1302 /// assert_eq!(d.pop_front(), Some(1));
1303 /// assert_eq!(d.pop_front(), Some(2));
1304 /// assert_eq!(d.pop_front(), None);
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 pub fn pop_front(&mut self) -> Option
<T
> {
1308 if self.is_empty() {
1311 let tail
= self.tail
;
1312 self.tail
= self.wrap_add(self.tail
, 1);
1313 unsafe { Some(self.buffer_read(tail)) }
1317 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1323 /// use std::collections::VecDeque;
1325 /// let mut buf = VecDeque::new();
1326 /// assert_eq!(buf.pop_back(), None);
1327 /// buf.push_back(1);
1328 /// buf.push_back(3);
1329 /// assert_eq!(buf.pop_back(), Some(3));
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 pub fn pop_back(&mut self) -> Option
<T
> {
1333 if self.is_empty() {
1336 self.head
= self.wrap_sub(self.head
, 1);
1337 let head
= self.head
;
1338 unsafe { Some(self.buffer_read(head)) }
1342 /// Prepends an element to the `VecDeque`.
1347 /// use std::collections::VecDeque;
1349 /// let mut d = VecDeque::new();
1350 /// d.push_front(1);
1351 /// d.push_front(2);
1352 /// assert_eq!(d.front(), Some(&2));
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 pub fn push_front(&mut self, value
: T
) {
1356 self.grow_if_necessary();
1358 self.tail
= self.wrap_sub(self.tail
, 1);
1359 let tail
= self.tail
;
1361 self.buffer_write(tail
, value
);
1365 /// Appends an element to the back of the `VecDeque`.
1370 /// use std::collections::VecDeque;
1372 /// let mut buf = VecDeque::new();
1373 /// buf.push_back(1);
1374 /// buf.push_back(3);
1375 /// assert_eq!(3, *buf.back().unwrap());
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 pub fn push_back(&mut self, value
: T
) {
1379 self.grow_if_necessary();
1381 let head
= self.head
;
1382 self.head
= self.wrap_add(self.head
, 1);
1383 unsafe { self.buffer_write(head, value) }
1387 fn is_contiguous(&self) -> bool
{
1388 self.tail
<= self.head
1391 /// Removes an element from anywhere in the `VecDeque` and returns it,
1392 /// replacing it with the first element.
1394 /// This does not preserve ordering, but is `O(1)`.
1396 /// Returns `None` if `index` is out of bounds.
1398 /// Element at index 0 is the front of the queue.
1403 /// use std::collections::VecDeque;
1405 /// let mut buf = VecDeque::new();
1406 /// assert_eq!(buf.swap_remove_front(0), None);
1407 /// buf.push_back(1);
1408 /// buf.push_back(2);
1409 /// buf.push_back(3);
1410 /// assert_eq!(buf, [1, 2, 3]);
1412 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1413 /// assert_eq!(buf, [2, 1]);
1415 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1416 pub fn swap_remove_front(&mut self, index
: usize) -> Option
<T
> {
1417 let length
= self.len();
1418 if length
> 0 && index
< length
&& index
!= 0 {
1419 self.swap(index
, 0);
1420 } else if index
>= length
{
1426 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1429 /// This does not preserve ordering, but is `O(1)`.
1431 /// Returns `None` if `index` is out of bounds.
1433 /// Element at index 0 is the front of the queue.
1438 /// use std::collections::VecDeque;
1440 /// let mut buf = VecDeque::new();
1441 /// assert_eq!(buf.swap_remove_back(0), None);
1442 /// buf.push_back(1);
1443 /// buf.push_back(2);
1444 /// buf.push_back(3);
1445 /// assert_eq!(buf, [1, 2, 3]);
1447 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1448 /// assert_eq!(buf, [3, 2]);
1450 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1451 pub fn swap_remove_back(&mut self, index
: usize) -> Option
<T
> {
1452 let length
= self.len();
1453 if length
> 0 && index
< length
- 1 {
1454 self.swap(index
, length
- 1);
1455 } else if index
>= length
{
1461 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1462 /// greater than or equal to `index` towards the back.
1464 /// Element at index 0 is the front of the queue.
1468 /// Panics if `index` is greater than `VecDeque`'s length
1473 /// use std::collections::VecDeque;
1475 /// let mut vec_deque = VecDeque::new();
1476 /// vec_deque.push_back('a');
1477 /// vec_deque.push_back('b');
1478 /// vec_deque.push_back('c');
1479 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1481 /// vec_deque.insert(1, 'd');
1482 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1484 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1485 pub fn insert(&mut self, index
: usize, value
: T
) {
1486 assert
!(index
<= self.len(), "index out of bounds");
1487 self.grow_if_necessary();
1489 // Move the least number of elements in the ring buffer and insert
1492 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1494 // There are three main cases:
1495 // Elements are contiguous
1496 // - special case when tail is 0
1497 // Elements are discontiguous and the insert is in the tail section
1498 // Elements are discontiguous and the insert is in the head section
1500 // For each of those there are two more cases:
1501 // Insert is closer to tail
1502 // Insert is closer to head
1504 // Key: H - self.head
1506 // o - Valid element
1507 // I - Insertion element
1508 // A - The element that should be after the insertion point
1509 // M - Indicates element was moved
1511 let idx
= self.wrap_add(self.tail
, index
);
1513 let distance_to_tail
= index
;
1514 let distance_to_head
= self.len() - index
;
1516 let contiguous
= self.is_contiguous();
1518 match (contiguous
, distance_to_tail
<= distance_to_head
, idx
>= self.tail
) {
1519 (true, true, _
) if index
== 0 => {
1524 // [A o o o o o o . . . . . . . . .]
1527 // [A o o o o o o o . . . . . I]
1530 self.tail
= self.wrap_sub(self.tail
, 1);
1532 (true, true, _
) => {
1534 // contiguous, insert closer to tail:
1537 // [. . . o o A o o o o . . . . . .]
1540 // [. . o o I A o o o o . . . . . .]
1543 // contiguous, insert closer to tail and tail is 0:
1547 // [o o A o o o o . . . . . . . . .]
1550 // [o I A o o o o o . . . . . . . o]
1553 let new_tail
= self.wrap_sub(self.tail
, 1);
1555 self.copy(new_tail
, self.tail
, 1);
1556 // Already moved the tail, so we only copy `index - 1` elements.
1557 self.copy(self.tail
, self.tail
+ 1, index
- 1);
1559 self.tail
= new_tail
;
1562 (true, false, _
) => {
1564 // contiguous, insert closer to head:
1567 // [. . . o o o o A o o . . . . . .]
1570 // [. . . o o o o I A o o . . . . .]
1573 self.copy(idx
+ 1, idx
, self.head
- idx
);
1574 self.head
= self.wrap_add(self.head
, 1);
1577 (false, true, true) => {
1579 // discontiguous, insert closer to tail, tail section:
1582 // [o o o o o o . . . . . o o A o o]
1585 // [o o o o o o . . . . o o I A o o]
1588 self.copy(self.tail
- 1, self.tail
, index
);
1592 (false, false, true) => {
1594 // discontiguous, insert closer to head, tail section:
1597 // [o o . . . . . . . o o o o o A o]
1600 // [o o o . . . . . . o o o o o I A]
1603 // copy elements up to new head
1604 self.copy(1, 0, self.head
);
1606 // copy last element into empty spot at bottom of buffer
1607 self.copy(0, self.cap() - 1, 1);
1609 // move elements from idx to end forward not including ^ element
1610 self.copy(idx
+ 1, idx
, self.cap() - 1 - idx
);
1615 (false, true, false) if idx
== 0 => {
1617 // discontiguous, insert is closer to tail, head section,
1618 // and is at index zero in the internal buffer:
1621 // [A o o o o o o o o o . . . o o o]
1624 // [A o o o o o o o o o . . o o o I]
1627 // copy elements up to new tail
1628 self.copy(self.tail
- 1, self.tail
, self.cap() - self.tail
);
1630 // copy last element into empty spot at bottom of buffer
1631 self.copy(self.cap() - 1, 0, 1);
1636 (false, true, false) => {
1638 // discontiguous, insert closer to tail, head section:
1641 // [o o o A o o o o o o . . . o o o]
1644 // [o o I A o o o o o o . . o o o o]
1647 // copy elements up to new tail
1648 self.copy(self.tail
- 1, self.tail
, self.cap() - self.tail
);
1650 // copy last element into empty spot at bottom of buffer
1651 self.copy(self.cap() - 1, 0, 1);
1653 // move elements from idx-1 to end forward not including ^ element
1654 self.copy(0, 1, idx
- 1);
1659 (false, false, false) => {
1661 // discontiguous, insert closer to head, head section:
1664 // [o o o o A o o . . . . . . o o o]
1667 // [o o o o I A o o . . . . . o o o]
1670 self.copy(idx
+ 1, idx
, self.head
- idx
);
1676 // tail might've been changed so we need to recalculate
1677 let new_idx
= self.wrap_add(self.tail
, index
);
1679 self.buffer_write(new_idx
, value
);
1683 /// Removes and returns the element at `index` from the `VecDeque`.
1684 /// Whichever end is closer to the removal point will be moved to make
1685 /// room, and all the affected elements will be moved to new positions.
1686 /// Returns `None` if `index` is out of bounds.
1688 /// Element at index 0 is the front of the queue.
1693 /// use std::collections::VecDeque;
1695 /// let mut buf = VecDeque::new();
1696 /// buf.push_back(1);
1697 /// buf.push_back(2);
1698 /// buf.push_back(3);
1699 /// assert_eq!(buf, [1, 2, 3]);
1701 /// assert_eq!(buf.remove(1), Some(2));
1702 /// assert_eq!(buf, [1, 3]);
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 pub fn remove(&mut self, index
: usize) -> Option
<T
> {
1706 if self.is_empty() || self.len() <= index
{
1710 // There are three main cases:
1711 // Elements are contiguous
1712 // Elements are discontiguous and the removal is in the tail section
1713 // Elements are discontiguous and the removal is in the head section
1714 // - special case when elements are technically contiguous,
1715 // but self.head = 0
1717 // For each of those there are two more cases:
1718 // Insert is closer to tail
1719 // Insert is closer to head
1721 // Key: H - self.head
1723 // o - Valid element
1724 // x - Element marked for removal
1725 // R - Indicates element that is being removed
1726 // M - Indicates element was moved
1728 let idx
= self.wrap_add(self.tail
, index
);
1730 let elem
= unsafe { Some(self.buffer_read(idx)) }
;
1732 let distance_to_tail
= index
;
1733 let distance_to_head
= self.len() - index
;
1735 let contiguous
= self.is_contiguous();
1737 match (contiguous
, distance_to_tail
<= distance_to_head
, idx
>= self.tail
) {
1738 (true, true, _
) => {
1740 // contiguous, remove closer to tail:
1743 // [. . . o o x o o o o . . . . . .]
1746 // [. . . . o o o o o o . . . . . .]
1749 self.copy(self.tail
+ 1, self.tail
, index
);
1753 (true, false, _
) => {
1755 // contiguous, remove closer to head:
1758 // [. . . o o o o x o o . . . . . .]
1761 // [. . . o o o o o o . . . . . . .]
1764 self.copy(idx
, idx
+ 1, self.head
- idx
- 1);
1768 (false, true, true) => {
1770 // discontiguous, remove closer to tail, tail section:
1773 // [o o o o o o . . . . . o o x o o]
1776 // [o o o o o o . . . . . . o o o o]
1779 self.copy(self.tail
+ 1, self.tail
, index
);
1780 self.tail
= self.wrap_add(self.tail
, 1);
1783 (false, false, false) => {
1785 // discontiguous, remove closer to head, head section:
1788 // [o o o o x o o . . . . . . o o o]
1791 // [o o o o o o . . . . . . . o o o]
1794 self.copy(idx
, idx
+ 1, self.head
- idx
- 1);
1798 (false, false, true) => {
1800 // discontiguous, remove closer to head, tail section:
1803 // [o o o . . . . . . o o o o o x o]
1806 // [o o . . . . . . . o o o o o o o]
1809 // or quasi-discontiguous, remove next to head, tail section:
1812 // [. . . . . . . . . o o o o o x o]
1815 // [. . . . . . . . . o o o o o o .]
1818 // draw in elements in the tail section
1819 self.copy(idx
, idx
+ 1, self.cap() - idx
- 1);
1821 // Prevents underflow.
1823 // copy first element into empty spot
1824 self.copy(self.cap() - 1, 0, 1);
1826 // move elements in the head section backwards
1827 self.copy(0, 1, self.head
- 1);
1830 self.head
= self.wrap_sub(self.head
, 1);
1833 (false, true, false) => {
1835 // discontiguous, remove closer to tail, head section:
1838 // [o o x o o o o o o o . . . o o o]
1841 // [o o o o o o o o o o . . . . o o]
1844 // draw in elements up to idx
1845 self.copy(1, 0, idx
);
1847 // copy last element into empty spot
1848 self.copy(0, self.cap() - 1, 1);
1850 // move elements from tail to end forward, excluding the last one
1851 self.copy(self.tail
+ 1, self.tail
, self.cap() - self.tail
- 1);
1853 self.tail
= self.wrap_add(self.tail
, 1);
1861 /// Splits the `VecDeque` into two at the given index.
1863 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1864 /// and the returned `VecDeque` contains elements `[at, len)`.
1866 /// Note that the capacity of `self` does not change.
1868 /// Element at index 0 is the front of the queue.
1872 /// Panics if `at > len`.
1877 /// use std::collections::VecDeque;
1879 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1880 /// let buf2 = buf.split_off(1);
1881 /// assert_eq!(buf, [1]);
1882 /// assert_eq!(buf2, [2, 3]);
1885 #[must_use = "use `.truncate()` if you don't need the other half"]
1886 #[stable(feature = "split_off", since = "1.4.0")]
1887 pub fn split_off(&mut self, at
: usize) -> Self {
1888 let len
= self.len();
1889 assert
!(at
<= len
, "`at` out of bounds");
1891 let other_len
= len
- at
;
1892 let mut other
= VecDeque
::with_capacity(other_len
);
1895 let (first_half
, second_half
) = self.as_slices();
1897 let first_len
= first_half
.len();
1898 let second_len
= second_half
.len();
1900 // `at` lies in the first half.
1901 let amount_in_first
= first_len
- at
;
1903 ptr
::copy_nonoverlapping(first_half
.as_ptr().add(at
), other
.ptr(), amount_in_first
);
1905 // just take all of the second half.
1906 ptr
::copy_nonoverlapping(
1907 second_half
.as_ptr(),
1908 other
.ptr().add(amount_in_first
),
1912 // `at` lies in the second half, need to factor in the elements we skipped
1913 // in the first half.
1914 let offset
= at
- first_len
;
1915 let amount_in_second
= second_len
- offset
;
1916 ptr
::copy_nonoverlapping(
1917 second_half
.as_ptr().add(offset
),
1924 // Cleanup where the ends of the buffers are
1925 self.head
= self.wrap_sub(self.head
, other_len
);
1926 other
.head
= other
.wrap_index(other_len
);
1931 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1935 /// Panics if the new number of elements in self overflows a `usize`.
1940 /// use std::collections::VecDeque;
1942 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1943 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1944 /// buf.append(&mut buf2);
1945 /// assert_eq!(buf, [1, 2, 3, 4]);
1946 /// assert_eq!(buf2, []);
1949 #[stable(feature = "append", since = "1.4.0")]
1950 pub fn append(&mut self, other
: &mut Self) {
1952 self.extend(other
.drain(..));
1955 /// Retains only the elements specified by the predicate.
1957 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1958 /// This method operates in place, visiting each element exactly once in the
1959 /// original order, and preserves the order of the retained elements.
1964 /// use std::collections::VecDeque;
1966 /// let mut buf = VecDeque::new();
1967 /// buf.extend(1..5);
1968 /// buf.retain(|&x| x % 2 == 0);
1969 /// assert_eq!(buf, [2, 4]);
1972 /// The exact order may be useful for tracking external state, like an index.
1975 /// use std::collections::VecDeque;
1977 /// let mut buf = VecDeque::new();
1978 /// buf.extend(1..6);
1980 /// let keep = [false, true, true, false, true];
1982 /// buf.retain(|_| (keep[i], i += 1).0);
1983 /// assert_eq!(buf, [2, 3, 5]);
1985 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1986 pub fn retain
<F
>(&mut self, mut f
: F
)
1988 F
: FnMut(&T
) -> bool
,
1990 let len
= self.len();
1996 self.swap(i
- del
, i
);
2000 self.truncate(len
- del
);
2004 // This may panic or abort
2006 fn grow_if_necessary(&mut self) {
2008 let old_cap
= self.cap();
2011 self.handle_capacity_increase(old_cap
);
2013 debug_assert
!(!self.is_full());
2017 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
2018 /// either by removing excess elements from the back or by appending
2019 /// elements generated by calling `generator` to the back.
2024 /// use std::collections::VecDeque;
2026 /// let mut buf = VecDeque::new();
2027 /// buf.push_back(5);
2028 /// buf.push_back(10);
2029 /// buf.push_back(15);
2030 /// assert_eq!(buf, [5, 10, 15]);
2032 /// buf.resize_with(5, Default::default);
2033 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2035 /// buf.resize_with(2, || unreachable!());
2036 /// assert_eq!(buf, [5, 10]);
2038 /// let mut state = 100;
2039 /// buf.resize_with(5, || { state += 1; state });
2040 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2042 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2043 pub fn resize_with(&mut self, new_len
: usize, generator
: impl FnMut() -> T
) {
2044 let len
= self.len();
2047 self.extend(repeat_with(generator
).take(new_len
- len
))
2049 self.truncate(new_len
);
2053 /// Rearranges the internal storage of this deque so it is one contiguous slice, which is then returned.
2055 /// This method does not allocate and does not change the order of the inserted elements.
2056 /// As it returns a mutable slice, this can be used to sort or binary search a deque.
2058 /// Once the internal storage is contiguous, the [`as_slices`](#method.as_slices) and
2059 /// [`as_mut_slices`](#method.as_mut_slices) methods will return the entire contents of the
2060 /// `VecDeque` in a single slice.
2064 /// Sorting the content of a deque.
2067 /// #![feature(deque_make_contiguous)]
2069 /// use std::collections::VecDeque;
2071 /// let mut buf = VecDeque::with_capacity(15);
2073 /// buf.push_back(2);
2074 /// buf.push_back(1);
2075 /// buf.push_front(3);
2077 /// // sorting the deque
2078 /// buf.make_contiguous().sort();
2079 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2081 /// // sorting it in reverse order
2082 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2083 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2086 /// Getting immutable access to the contiguous slice.
2089 /// #![feature(deque_make_contiguous)]
2091 /// use std::collections::VecDeque;
2093 /// let mut buf = VecDeque::new();
2095 /// buf.push_back(2);
2096 /// buf.push_back(1);
2097 /// buf.push_front(3);
2099 /// buf.make_contiguous();
2100 /// if let (slice, &[]) = buf.as_slices() {
2101 /// // we can now be sure that `slice` contains all elements of the deque,
2102 /// // while still having immutable access to `buf`.
2103 /// assert_eq!(buf.len(), slice.len());
2104 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2107 #[unstable(feature = "deque_make_contiguous", issue = "70929")]
2108 pub fn make_contiguous(&mut self) -> &mut [T
] {
2109 if self.is_contiguous() {
2110 let tail
= self.tail
;
2111 let head
= self.head
;
2112 return unsafe { &mut self.buffer_as_mut_slice()[tail..head] }
;
2115 let buf
= self.buf
.ptr();
2116 let cap
= self.cap();
2117 let len
= self.len();
2119 let free
= self.tail
- self.head
;
2120 let tail_len
= cap
- self.tail
;
2122 if free
>= tail_len
{
2123 // there is enough free space to copy the tail in one go,
2124 // this means that we first shift the head backwards, and then
2125 // copy the tail to the correct position.
2127 // from: DEFGH....ABC
2130 ptr
::copy(buf
, buf
.add(tail_len
), self.head
);
2132 ptr
::copy_nonoverlapping(buf
.add(self.tail
), buf
, tail_len
);
2138 } else if free
>= self.head
{
2139 // there is enough free space to copy the head in one go,
2140 // this means that we first shift the tail forwards, and then
2141 // copy the head to the correct position.
2143 // from: FGH....ABCDE
2146 ptr
::copy(buf
.add(self.tail
), buf
.add(self.head
), tail_len
);
2148 ptr
::copy_nonoverlapping(buf
, buf
.add(self.head
+ tail_len
), self.head
);
2151 self.tail
= self.head
;
2152 self.head
= self.tail
+ len
;
2155 // free is smaller than both head and tail,
2156 // this means we have to slowly "swap" the tail and the head.
2158 // from: EFGHI...ABCD or HIJK.ABCDEFG
2159 // to: ABCDEFGHI... or ABCDEFGHIJK.
2160 let mut left_edge
: usize = 0;
2161 let mut right_edge
: usize = self.tail
;
2163 // The general problem looks like this
2164 // GHIJKLM...ABCDEF - before any swaps
2165 // ABCDEFM...GHIJKL - after 1 pass of swaps
2166 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2167 // - then restart the algorithm with a new (smaller) store
2168 // Sometimes the temp store is reached when the right edge is at the end
2169 // of the buffer - this means we've hit the right order with fewer swaps!
2172 // ABCDEF.. - after four only swaps we've finished
2173 while left_edge
< len
&& right_edge
!= cap
{
2174 let mut right_offset
= 0;
2175 for i
in left_edge
..right_edge
{
2176 right_offset
= (i
- left_edge
) % (cap
- right_edge
);
2177 let src
: isize = (right_edge
+ right_offset
) as isize;
2178 ptr
::swap(buf
.add(i
), buf
.offset(src
));
2180 let n_ops
= right_edge
- left_edge
;
2182 right_edge
+= right_offset
+ 1;
2190 let tail
= self.tail
;
2191 let head
= self.head
;
2192 unsafe { &mut self.buffer_as_mut_slice()[tail..head] }
2195 /// Rotates the double-ended queue `mid` places to the left.
2198 /// - Rotates item `mid` into the first position.
2199 /// - Pops the first `mid` items and pushes them to the end.
2200 /// - Rotates `len() - mid` places to the right.
2204 /// If `mid` is greater than `len()`. Note that `mid == len()`
2205 /// does _not_ panic and is a no-op rotation.
2209 /// Takes `O(min(mid, len() - mid))` time and no extra space.
2214 /// use std::collections::VecDeque;
2216 /// let mut buf: VecDeque<_> = (0..10).collect();
2218 /// buf.rotate_left(3);
2219 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2221 /// for i in 1..10 {
2222 /// assert_eq!(i * 3 % 10, buf[0]);
2223 /// buf.rotate_left(3);
2225 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2227 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2228 pub fn rotate_left(&mut self, mid
: usize) {
2229 assert
!(mid
<= self.len());
2230 let k
= self.len() - mid
;
2232 unsafe { self.rotate_left_inner(mid) }
2234 unsafe { self.rotate_right_inner(k) }
2238 /// Rotates the double-ended queue `k` places to the right.
2241 /// - Rotates the first item into position `k`.
2242 /// - Pops the last `k` items and pushes them to the front.
2243 /// - Rotates `len() - k` places to the left.
2247 /// If `k` is greater than `len()`. Note that `k == len()`
2248 /// does _not_ panic and is a no-op rotation.
2252 /// Takes `O(min(k, len() - k))` time and no extra space.
2257 /// use std::collections::VecDeque;
2259 /// let mut buf: VecDeque<_> = (0..10).collect();
2261 /// buf.rotate_right(3);
2262 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2264 /// for i in 1..10 {
2265 /// assert_eq!(0, buf[i * 3 % 10]);
2266 /// buf.rotate_right(3);
2268 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2270 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2271 pub fn rotate_right(&mut self, k
: usize) {
2272 assert
!(k
<= self.len());
2273 let mid
= self.len() - k
;
2275 unsafe { self.rotate_right_inner(k) }
2277 unsafe { self.rotate_left_inner(mid) }
2281 // Safety: the following two methods require that the rotation amount
2282 // be less than half the length of the deque.
2284 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2285 // but than `min` is never more than half the capacity, regardless of x,
2286 // so it's sound to call here because we're calling with something
2287 // less than half the length, which is never above half the capacity.
2289 unsafe fn rotate_left_inner(&mut self, mid
: usize) {
2290 debug_assert
!(mid
* 2 <= self.len());
2291 self.wrap_copy(self.head
, self.tail
, mid
);
2292 self.head
= self.wrap_add(self.head
, mid
);
2293 self.tail
= self.wrap_add(self.tail
, mid
);
2296 unsafe fn rotate_right_inner(&mut self, k
: usize) {
2297 debug_assert
!(k
* 2 <= self.len());
2298 self.head
= self.wrap_sub(self.head
, k
);
2299 self.tail
= self.wrap_sub(self.tail
, k
);
2300 self.wrap_copy(self.tail
, self.head
, k
);
2304 impl<T
: Clone
> VecDeque
<T
> {
2305 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2306 /// either by removing excess elements from the back or by appending clones of `value`
2312 /// use std::collections::VecDeque;
2314 /// let mut buf = VecDeque::new();
2315 /// buf.push_back(5);
2316 /// buf.push_back(10);
2317 /// buf.push_back(15);
2318 /// assert_eq!(buf, [5, 10, 15]);
2320 /// buf.resize(2, 0);
2321 /// assert_eq!(buf, [5, 10]);
2323 /// buf.resize(5, 20);
2324 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2326 #[stable(feature = "deque_extras", since = "1.16.0")]
2327 pub fn resize(&mut self, new_len
: usize, value
: T
) {
2328 self.resize_with(new_len
, || value
.clone());
2332 /// Returns the index in the underlying buffer for a given logical element index.
2334 fn wrap_index(index
: usize, size
: usize) -> usize {
2335 // size is always a power of 2
2336 debug_assert
!(size
.is_power_of_two());
2340 /// Returns the two slices that cover the `VecDeque`'s valid range
2341 trait RingSlices
: Sized
{
2342 fn slice(self, from
: usize, to
: usize) -> Self;
2343 fn split_at(self, i
: usize) -> (Self, Self);
2345 fn ring_slices(buf
: Self, head
: usize, tail
: usize) -> (Self, Self) {
2346 let contiguous
= tail
<= head
;
2348 let (empty
, buf
) = buf
.split_at(0);
2349 (buf
.slice(tail
, head
), empty
)
2351 let (mid
, right
) = buf
.split_at(tail
);
2352 let (left
, _
) = mid
.split_at(head
);
2358 impl<T
> RingSlices
for &[T
] {
2359 fn slice(self, from
: usize, to
: usize) -> Self {
2362 fn split_at(self, i
: usize) -> (Self, Self) {
2367 impl<T
> RingSlices
for &mut [T
] {
2368 fn slice(self, from
: usize, to
: usize) -> Self {
2371 fn split_at(self, i
: usize) -> (Self, Self) {
2372 (*self).split_at_mut(i
)
2376 /// Calculate the number of elements left to be read in the buffer
2378 fn count(tail
: usize, head
: usize, size
: usize) -> usize {
2379 // size is always a power of 2
2380 (head
.wrapping_sub(tail
)) & (size
- 1)
2383 /// An iterator over the elements of a `VecDeque`.
2385 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
2386 /// documentation for more.
2388 /// [`iter`]: struct.VecDeque.html#method.iter
2389 /// [`VecDeque`]: struct.VecDeque.html
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 pub struct Iter
<'a
, T
: 'a
> {
2397 #[stable(feature = "collection_debug", since = "1.17.0")]
2398 impl<T
: fmt
::Debug
> fmt
::Debug
for Iter
<'_
, T
> {
2399 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2400 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2401 f
.debug_tuple("Iter").field(&front
).field(&back
).finish()
2405 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2406 #[stable(feature = "rust1", since = "1.0.0")]
2407 impl<T
> Clone
for Iter
<'_
, T
> {
2408 fn clone(&self) -> Self {
2409 Iter { ring: self.ring, tail: self.tail, head: self.head }
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 impl<'a
, T
> Iterator
for Iter
<'a
, T
> {
2418 fn next(&mut self) -> Option
<&'a T
> {
2419 if self.tail
== self.head
{
2422 let tail
= self.tail
;
2423 self.tail
= wrap_index(self.tail
.wrapping_add(1), self.ring
.len());
2424 unsafe { Some(self.ring.get_unchecked(tail)) }
2428 fn size_hint(&self) -> (usize, Option
<usize>) {
2429 let len
= count(self.tail
, self.head
, self.ring
.len());
2433 fn fold
<Acc
, F
>(self, mut accum
: Acc
, mut f
: F
) -> Acc
2435 F
: FnMut(Acc
, Self::Item
) -> Acc
,
2437 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2438 accum
= front
.iter().fold(accum
, &mut f
);
2439 back
.iter().fold(accum
, &mut f
)
2442 fn try_fold
<B
, F
, R
>(&mut self, init
: B
, mut f
: F
) -> R
2445 F
: FnMut(B
, Self::Item
) -> R
,
2448 let (mut iter
, final_res
);
2449 if self.tail
<= self.head
{
2450 // single slice self.ring[self.tail..self.head]
2451 iter
= self.ring
[self.tail
..self.head
].iter();
2452 final_res
= iter
.try_fold(init
, &mut f
);
2454 // two slices: self.ring[self.tail..], self.ring[..self.head]
2455 let (front
, back
) = self.ring
.split_at(self.tail
);
2456 let mut back_iter
= back
.iter();
2457 let res
= back_iter
.try_fold(init
, &mut f
);
2458 let len
= self.ring
.len();
2459 self.tail
= (self.ring
.len() - back_iter
.len()) & (len
- 1);
2460 iter
= front
[..self.head
].iter();
2461 final_res
= iter
.try_fold(res?
, &mut f
);
2463 self.tail
= self.head
- iter
.len();
2467 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2468 if n
>= count(self.tail
, self.head
, self.ring
.len()) {
2469 self.tail
= self.head
;
2472 self.tail
= wrap_index(self.tail
.wrapping_add(n
), self.ring
.len());
2478 fn last(mut self) -> Option
<&'a T
> {
2483 #[stable(feature = "rust1", since = "1.0.0")]
2484 impl<'a
, T
> DoubleEndedIterator
for Iter
<'a
, T
> {
2486 fn next_back(&mut self) -> Option
<&'a T
> {
2487 if self.tail
== self.head
{
2490 self.head
= wrap_index(self.head
.wrapping_sub(1), self.ring
.len());
2491 unsafe { Some(self.ring.get_unchecked(self.head)) }
2494 fn rfold
<Acc
, F
>(self, mut accum
: Acc
, mut f
: F
) -> Acc
2496 F
: FnMut(Acc
, Self::Item
) -> Acc
,
2498 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2499 accum
= back
.iter().rfold(accum
, &mut f
);
2500 front
.iter().rfold(accum
, &mut f
)
2503 fn try_rfold
<B
, F
, R
>(&mut self, init
: B
, mut f
: F
) -> R
2506 F
: FnMut(B
, Self::Item
) -> R
,
2509 let (mut iter
, final_res
);
2510 if self.tail
<= self.head
{
2511 // single slice self.ring[self.tail..self.head]
2512 iter
= self.ring
[self.tail
..self.head
].iter();
2513 final_res
= iter
.try_rfold(init
, &mut f
);
2515 // two slices: self.ring[self.tail..], self.ring[..self.head]
2516 let (front
, back
) = self.ring
.split_at(self.tail
);
2517 let mut front_iter
= front
[..self.head
].iter();
2518 let res
= front_iter
.try_rfold(init
, &mut f
);
2519 self.head
= front_iter
.len();
2521 final_res
= iter
.try_rfold(res?
, &mut f
);
2523 self.head
= self.tail
+ iter
.len();
2528 #[stable(feature = "rust1", since = "1.0.0")]
2529 impl<T
> ExactSizeIterator
for Iter
<'_
, T
> {
2530 fn is_empty(&self) -> bool
{
2531 self.head
== self.tail
2535 #[stable(feature = "fused", since = "1.26.0")]
2536 impl<T
> FusedIterator
for Iter
<'_
, T
> {}
2538 /// A mutable iterator over the elements of a `VecDeque`.
2540 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2541 /// documentation for more.
2543 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2544 /// [`VecDeque`]: struct.VecDeque.html
2545 #[stable(feature = "rust1", since = "1.0.0")]
2546 pub struct IterMut
<'a
, T
: 'a
> {
2552 #[stable(feature = "collection_debug", since = "1.17.0")]
2553 impl<T
: fmt
::Debug
> fmt
::Debug
for IterMut
<'_
, T
> {
2554 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2555 let (front
, back
) = RingSlices
::ring_slices(&*self.ring
, self.head
, self.tail
);
2556 f
.debug_tuple("IterMut").field(&front
).field(&back
).finish()
2560 #[stable(feature = "rust1", since = "1.0.0")]
2561 impl<'a
, T
> Iterator
for IterMut
<'a
, T
> {
2562 type Item
= &'a
mut T
;
2565 fn next(&mut self) -> Option
<&'a
mut T
> {
2566 if self.tail
== self.head
{
2569 let tail
= self.tail
;
2570 self.tail
= wrap_index(self.tail
.wrapping_add(1), self.ring
.len());
2573 let elem
= self.ring
.get_unchecked_mut(tail
);
2574 Some(&mut *(elem
as *mut _
))
2579 fn size_hint(&self) -> (usize, Option
<usize>) {
2580 let len
= count(self.tail
, self.head
, self.ring
.len());
2584 fn fold
<Acc
, F
>(self, mut accum
: Acc
, mut f
: F
) -> Acc
2586 F
: FnMut(Acc
, Self::Item
) -> Acc
,
2588 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2589 accum
= front
.iter_mut().fold(accum
, &mut f
);
2590 back
.iter_mut().fold(accum
, &mut f
)
2593 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2594 if n
>= count(self.tail
, self.head
, self.ring
.len()) {
2595 self.tail
= self.head
;
2598 self.tail
= wrap_index(self.tail
.wrapping_add(n
), self.ring
.len());
2604 fn last(mut self) -> Option
<&'a
mut T
> {
2609 #[stable(feature = "rust1", since = "1.0.0")]
2610 impl<'a
, T
> DoubleEndedIterator
for IterMut
<'a
, T
> {
2612 fn next_back(&mut self) -> Option
<&'a
mut T
> {
2613 if self.tail
== self.head
{
2616 self.head
= wrap_index(self.head
.wrapping_sub(1), self.ring
.len());
2619 let elem
= self.ring
.get_unchecked_mut(self.head
);
2620 Some(&mut *(elem
as *mut _
))
2624 fn rfold
<Acc
, F
>(self, mut accum
: Acc
, mut f
: F
) -> Acc
2626 F
: FnMut(Acc
, Self::Item
) -> Acc
,
2628 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2629 accum
= back
.iter_mut().rfold(accum
, &mut f
);
2630 front
.iter_mut().rfold(accum
, &mut f
)
2634 #[stable(feature = "rust1", since = "1.0.0")]
2635 impl<T
> ExactSizeIterator
for IterMut
<'_
, T
> {
2636 fn is_empty(&self) -> bool
{
2637 self.head
== self.tail
2641 #[stable(feature = "fused", since = "1.26.0")]
2642 impl<T
> FusedIterator
for IterMut
<'_
, T
> {}
2644 /// An owning iterator over the elements of a `VecDeque`.
2646 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`]
2647 /// (provided by the `IntoIterator` trait). See its documentation for more.
2649 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2650 /// [`VecDeque`]: struct.VecDeque.html
2652 #[stable(feature = "rust1", since = "1.0.0")]
2653 pub struct IntoIter
<T
> {
2657 #[stable(feature = "collection_debug", since = "1.17.0")]
2658 impl<T
: fmt
::Debug
> fmt
::Debug
for IntoIter
<T
> {
2659 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2660 f
.debug_tuple("IntoIter").field(&self.inner
).finish()
2664 #[stable(feature = "rust1", since = "1.0.0")]
2665 impl<T
> Iterator
for IntoIter
<T
> {
2669 fn next(&mut self) -> Option
<T
> {
2670 self.inner
.pop_front()
2674 fn size_hint(&self) -> (usize, Option
<usize>) {
2675 let len
= self.inner
.len();
2680 #[stable(feature = "rust1", since = "1.0.0")]
2681 impl<T
> DoubleEndedIterator
for IntoIter
<T
> {
2683 fn next_back(&mut self) -> Option
<T
> {
2684 self.inner
.pop_back()
2688 #[stable(feature = "rust1", since = "1.0.0")]
2689 impl<T
> ExactSizeIterator
for IntoIter
<T
> {
2690 fn is_empty(&self) -> bool
{
2691 self.inner
.is_empty()
2695 #[stable(feature = "fused", since = "1.26.0")]
2696 impl<T
> FusedIterator
for IntoIter
<T
> {}
2698 #[stable(feature = "rust1", since = "1.0.0")]
2699 impl<A
: PartialEq
> PartialEq
for VecDeque
<A
> {
2700 fn eq(&self, other
: &VecDeque
<A
>) -> bool
{
2701 if self.len() != other
.len() {
2704 let (sa
, sb
) = self.as_slices();
2705 let (oa
, ob
) = other
.as_slices();
2706 if sa
.len() == oa
.len() {
2707 sa
== oa
&& sb
== ob
2708 } else if sa
.len() < oa
.len() {
2709 // Always divisible in three sections, for example:
2710 // self: [a b c|d e f]
2711 // other: [0 1 2 3|4 5]
2712 // front = 3, mid = 1,
2713 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2714 let front
= sa
.len();
2715 let mid
= oa
.len() - front
;
2717 let (oa_front
, oa_mid
) = oa
.split_at(front
);
2718 let (sb_mid
, sb_back
) = sb
.split_at(mid
);
2719 debug_assert_eq
!(sa
.len(), oa_front
.len());
2720 debug_assert_eq
!(sb_mid
.len(), oa_mid
.len());
2721 debug_assert_eq
!(sb_back
.len(), ob
.len());
2722 sa
== oa_front
&& sb_mid
== oa_mid
&& sb_back
== ob
2724 let front
= oa
.len();
2725 let mid
= sa
.len() - front
;
2727 let (sa_front
, sa_mid
) = sa
.split_at(front
);
2728 let (ob_mid
, ob_back
) = ob
.split_at(mid
);
2729 debug_assert_eq
!(sa_front
.len(), oa
.len());
2730 debug_assert_eq
!(sa_mid
.len(), ob_mid
.len());
2731 debug_assert_eq
!(sb
.len(), ob_back
.len());
2732 sa_front
== oa
&& sa_mid
== ob_mid
&& sb
== ob_back
2737 #[stable(feature = "rust1", since = "1.0.0")]
2738 impl<A
: Eq
> Eq
for VecDeque
<A
> {}
2740 macro_rules
! __impl_slice_eq1
{
2741 ([$
($vars
:tt
)*] $lhs
:ty
, $rhs
:ty
, $
($constraints
:tt
)*) => {
2742 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2743 impl<A
, B
, $
($vars
)*> PartialEq
<$rhs
> for $lhs
2748 fn eq(&self, other
: &$rhs
) -> bool
{
2749 if self.len() != other
.len() {
2752 let (sa
, sb
) = self.as_slices();
2753 let (oa
, ob
) = other
[..].split_at(sa
.len());
2754 sa
== oa
&& sb
== ob
2760 __impl_slice_eq1
! { [] VecDeque<A>, Vec<B>, }
2761 __impl_slice_eq1
! { [] VecDeque<A>, &[B], }
2762 __impl_slice_eq1
! { [] VecDeque<A>, &mut [B], }
2763 __impl_slice_eq1
! { [const N: usize] VecDeque<A>, [B; N], [B; N]: LengthAtMost32 }
2764 __impl_slice_eq1
! { [const N: usize] VecDeque<A>, &[B; N], [B; N]: LengthAtMost32 }
2765 __impl_slice_eq1
! { [const N: usize] VecDeque<A>, &mut [B; N], [B; N]: LengthAtMost32 }
2767 #[stable(feature = "rust1", since = "1.0.0")]
2768 impl<A
: PartialOrd
> PartialOrd
for VecDeque
<A
> {
2769 fn partial_cmp(&self, other
: &VecDeque
<A
>) -> Option
<Ordering
> {
2770 self.iter().partial_cmp(other
.iter())
2774 #[stable(feature = "rust1", since = "1.0.0")]
2775 impl<A
: Ord
> Ord
for VecDeque
<A
> {
2777 fn cmp(&self, other
: &VecDeque
<A
>) -> Ordering
{
2778 self.iter().cmp(other
.iter())
2782 #[stable(feature = "rust1", since = "1.0.0")]
2783 impl<A
: Hash
> Hash
for VecDeque
<A
> {
2784 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
2785 self.len().hash(state
);
2786 let (a
, b
) = self.as_slices();
2787 Hash
::hash_slice(a
, state
);
2788 Hash
::hash_slice(b
, state
);
2792 #[stable(feature = "rust1", since = "1.0.0")]
2793 impl<A
> Index
<usize> for VecDeque
<A
> {
2797 fn index(&self, index
: usize) -> &A
{
2798 self.get(index
).expect("Out of bounds access")
2802 #[stable(feature = "rust1", since = "1.0.0")]
2803 impl<A
> IndexMut
<usize> for VecDeque
<A
> {
2805 fn index_mut(&mut self, index
: usize) -> &mut A
{
2806 self.get_mut(index
).expect("Out of bounds access")
2810 #[stable(feature = "rust1", since = "1.0.0")]
2811 impl<A
> FromIterator
<A
> for VecDeque
<A
> {
2812 fn from_iter
<T
: IntoIterator
<Item
= A
>>(iter
: T
) -> VecDeque
<A
> {
2813 let iterator
= iter
.into_iter();
2814 let (lower
, _
) = iterator
.size_hint();
2815 let mut deq
= VecDeque
::with_capacity(lower
);
2816 deq
.extend(iterator
);
2821 #[stable(feature = "rust1", since = "1.0.0")]
2822 impl<T
> IntoIterator
for VecDeque
<T
> {
2824 type IntoIter
= IntoIter
<T
>;
2826 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2828 fn into_iter(self) -> IntoIter
<T
> {
2829 IntoIter { inner: self }
2833 #[stable(feature = "rust1", since = "1.0.0")]
2834 impl<'a
, T
> IntoIterator
for &'a VecDeque
<T
> {
2836 type IntoIter
= Iter
<'a
, T
>;
2838 fn into_iter(self) -> Iter
<'a
, T
> {
2843 #[stable(feature = "rust1", since = "1.0.0")]
2844 impl<'a
, T
> IntoIterator
for &'a
mut VecDeque
<T
> {
2845 type Item
= &'a
mut T
;
2846 type IntoIter
= IterMut
<'a
, T
>;
2848 fn into_iter(self) -> IterMut
<'a
, T
> {
2853 #[stable(feature = "rust1", since = "1.0.0")]
2854 impl<A
> Extend
<A
> for VecDeque
<A
> {
2855 fn extend
<T
: IntoIterator
<Item
= A
>>(&mut self, iter
: T
) {
2856 // This function should be the moral equivalent of:
2858 // for item in iter.into_iter() {
2859 // self.push_back(item);
2861 let mut iter
= iter
.into_iter();
2862 while let Some(element
) = iter
.next() {
2863 if self.len() == self.capacity() {
2864 let (lower
, _
) = iter
.size_hint();
2865 self.reserve(lower
.saturating_add(1));
2868 let head
= self.head
;
2869 self.head
= self.wrap_add(self.head
, 1);
2871 self.buffer_write(head
, element
);
2877 #[stable(feature = "extend_ref", since = "1.2.0")]
2878 impl<'a
, T
: 'a
+ Copy
> Extend
<&'a T
> for VecDeque
<T
> {
2879 fn extend
<I
: IntoIterator
<Item
= &'a T
>>(&mut self, iter
: I
) {
2880 self.extend(iter
.into_iter().cloned());
2884 #[stable(feature = "rust1", since = "1.0.0")]
2885 impl<T
: fmt
::Debug
> fmt
::Debug
for VecDeque
<T
> {
2886 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2887 f
.debug_list().entries(self).finish()
2891 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2892 impl<T
> From
<Vec
<T
>> for VecDeque
<T
> {
2893 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2895 /// [`Vec<T>`]: crate::vec::Vec
2896 /// [`VecDeque<T>`]: crate::collections::VecDeque
2898 /// This avoids reallocating where possible, but the conditions for that are
2899 /// strict, and subject to change, and so shouldn't be relied upon unless the
2900 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
2901 fn from(other
: Vec
<T
>) -> Self {
2903 let mut other
= ManuallyDrop
::new(other
);
2904 let other_buf
= other
.as_mut_ptr();
2905 let mut buf
= RawVec
::from_raw_parts(other_buf
, other
.capacity());
2906 let len
= other
.len();
2908 // We need to extend the buf if it's not a power of two, too small
2909 // or doesn't have at least one free space
2910 if !buf
.capacity().is_power_of_two()
2911 || (buf
.capacity() < (MINIMUM_CAPACITY
+ 1))
2912 || (buf
.capacity() == len
)
2914 let cap
= cmp
::max(buf
.capacity() + 1, MINIMUM_CAPACITY
+ 1).next_power_of_two();
2915 buf
.reserve_exact(len
, cap
- len
);
2918 VecDeque { tail: 0, head: len, buf }
2923 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2924 impl<T
> From
<VecDeque
<T
>> for Vec
<T
> {
2925 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2927 /// [`Vec<T>`]: crate::vec::Vec
2928 /// [`VecDeque<T>`]: crate::collections::VecDeque
2930 /// This never needs to re-allocate, but does need to do `O(n)` data movement if
2931 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2936 /// use std::collections::VecDeque;
2938 /// // This one is O(1).
2939 /// let deque: VecDeque<_> = (1..5).collect();
2940 /// let ptr = deque.as_slices().0.as_ptr();
2941 /// let vec = Vec::from(deque);
2942 /// assert_eq!(vec, [1, 2, 3, 4]);
2943 /// assert_eq!(vec.as_ptr(), ptr);
2945 /// // This one needs data rearranging.
2946 /// let mut deque: VecDeque<_> = (1..5).collect();
2947 /// deque.push_front(9);
2948 /// deque.push_front(8);
2949 /// let ptr = deque.as_slices().1.as_ptr();
2950 /// let vec = Vec::from(deque);
2951 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2952 /// assert_eq!(vec.as_ptr(), ptr);
2954 fn from(mut other
: VecDeque
<T
>) -> Self {
2955 other
.make_contiguous();
2958 let other
= ManuallyDrop
::new(other
);
2959 let buf
= other
.buf
.ptr();
2960 let len
= other
.len();
2961 let cap
= other
.cap();
2963 if other
.head
!= 0 {
2964 ptr
::copy(buf
.add(other
.tail
), buf
, len
);
2966 Vec
::from_raw_parts(buf
, len
, cap
)