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}
;
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
;
28 const INITIAL_CAPACITY
: usize = 7; // 2^3 - 1
29 const MINIMUM_CAPACITY
: usize = 1; // 2 - 1
30 #[cfg(target_pointer_width = "16")]
31 const MAXIMUM_ZST_CAPACITY
: usize = 1 << (16 - 1); // Largest possible power of two
32 #[cfg(target_pointer_width = "32")]
33 const MAXIMUM_ZST_CAPACITY
: usize = 1 << (32 - 1); // Largest possible power of two
34 #[cfg(target_pointer_width = "64")]
35 const MAXIMUM_ZST_CAPACITY
: usize = 1 << (64 - 1); // Largest possible power of two
37 /// A double-ended queue implemented with a growable ring buffer.
39 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
40 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
41 /// push onto the back in this manner, and iterating over `VecDeque` goes front
44 /// [`push_back`]: #method.push_back
45 /// [`pop_front`]: #method.pop_front
46 /// [`extend`]: #method.extend
47 /// [`append`]: #method.append
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub struct VecDeque
<T
> {
50 // tail and head are pointers into the buffer. Tail always points
51 // to the first element that could be read, Head always points
52 // to where data should be written.
53 // If tail == head the buffer is empty. The length of the ringbuffer
54 // is defined as the distance between the two.
60 /// PairSlices pairs up equal length slice parts of two deques
62 /// For example, given deques "A" and "B" with the following division into slices:
64 /// A: [0 1 2] [3 4 5]
67 /// It produces the following sequence of matching slices:
73 /// and the uneven remainder of either A or B is skipped.
74 struct PairSlices
<'a
, 'b
, T
> {
81 impl<'a
, 'b
, T
> PairSlices
<'a
, 'b
, T
> {
82 fn from(to
: &'a
mut VecDeque
<T
>, from
: &'b VecDeque
<T
>) -> Self {
83 let (a0
, a1
) = to
.as_mut_slices();
84 let (b0
, b1
) = from
.as_slices();
85 PairSlices { a0, a1, b0, b1 }
88 fn has_remainder(&self) -> bool
{
92 fn remainder(self) -> impl Iterator
<Item
= &'b
[T
]> {
93 once(self.b0
).chain(once(self.b1
))
97 impl<'a
, 'b
, T
> Iterator
for PairSlices
<'a
, 'b
, T
> {
98 type Item
= (&'a
mut [T
], &'b
[T
]);
99 fn next(&mut self) -> Option
<Self::Item
> {
100 // Get next part length
101 let part
= cmp
::min(self.a0
.len(), self.b0
.len());
105 let (p0
, p1
) = replace(&mut self.a0
, &mut []).split_at_mut(part
);
106 let (q0
, q1
) = self.b0
.split_at(part
);
108 // Move a1 into a0, if it's empty (and b1, b0 the same way).
111 if self.a0
.is_empty() {
112 self.a0
= replace(&mut self.a1
, &mut []);
114 if self.b0
.is_empty() {
115 self.b0
= replace(&mut self.b1
, &[]);
121 #[stable(feature = "rust1", since = "1.0.0")]
122 impl<T
: Clone
> Clone
for VecDeque
<T
> {
123 fn clone(&self) -> VecDeque
<T
> {
124 self.iter().cloned().collect()
127 fn clone_from(&mut self, other
: &Self) {
128 self.truncate(other
.len());
130 let mut iter
= PairSlices
::from(self, other
);
131 while let Some((dst
, src
)) = iter
.next() {
132 dst
.clone_from_slice(&src
);
135 if iter
.has_remainder() {
136 for remainder
in iter
.remainder() {
137 self.extend(remainder
.iter().cloned());
143 #[stable(feature = "rust1", since = "1.0.0")]
144 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
146 /// Runs the destructor for all items in the slice when it gets dropped (normally or
147 /// during unwinding).
148 struct Dropper
<'a
, T
>(&'a
mut [T
]);
150 impl<'a
, T
> Drop
for Dropper
<'a
, T
> {
153 ptr
::drop_in_place(self.0);
158 let (front
, back
) = self.as_mut_slices();
160 let _back_dropper
= Dropper(back
);
162 ptr
::drop_in_place(front
);
164 // RawVec handles deallocation
168 #[stable(feature = "rust1", since = "1.0.0")]
169 impl<T
> Default
for VecDeque
<T
> {
170 /// Creates an empty `VecDeque<T>`.
172 fn default() -> VecDeque
<T
> {
177 impl<T
> VecDeque
<T
> {
178 /// Marginally more convenient
180 fn ptr(&self) -> *mut T
{
184 /// Marginally more convenient
186 fn cap(&self) -> usize {
187 if mem
::size_of
::<T
>() == 0 {
188 // For zero sized types, we are always at maximum capacity
195 /// Turn ptr into a slice
197 unsafe fn buffer_as_slice(&self) -> &[T
] {
198 slice
::from_raw_parts(self.ptr(), self.cap())
201 /// Turn ptr into a mut slice
203 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T
] {
204 slice
::from_raw_parts_mut(self.ptr(), self.cap())
207 /// Moves an element out of the buffer
209 unsafe fn buffer_read(&mut self, off
: usize) -> T
{
210 ptr
::read(self.ptr().add(off
))
213 /// Writes an element into the buffer, moving it.
215 unsafe fn buffer_write(&mut self, off
: usize, value
: T
) {
216 ptr
::write(self.ptr().add(off
), value
);
219 /// Returns `true` if the buffer is at full capacity.
221 fn is_full(&self) -> bool
{
222 self.cap() - self.len() == 1
225 /// Returns the index in the underlying buffer for a given logical element
228 fn wrap_index(&self, idx
: usize) -> usize {
229 wrap_index(idx
, self.cap())
232 /// Returns the index in the underlying buffer for a given logical element
235 fn wrap_add(&self, idx
: usize, addend
: usize) -> usize {
236 wrap_index(idx
.wrapping_add(addend
), self.cap())
239 /// Returns the index in the underlying buffer for a given logical element
240 /// index - subtrahend.
242 fn wrap_sub(&self, idx
: usize, subtrahend
: usize) -> usize {
243 wrap_index(idx
.wrapping_sub(subtrahend
), self.cap())
246 /// Copies a contiguous block of memory len long from src to dst
248 unsafe fn copy(&self, dst
: usize, src
: usize, len
: usize) {
250 dst
+ len
<= self.cap(),
251 "cpy dst={} src={} len={} cap={}",
258 src
+ len
<= self.cap(),
259 "cpy dst={} src={} len={} cap={}",
265 ptr
::copy(self.ptr().add(src
), self.ptr().add(dst
), len
);
268 /// Copies a contiguous block of memory len long from src to dst
270 unsafe fn copy_nonoverlapping(&self, dst
: usize, src
: usize, len
: usize) {
272 dst
+ len
<= self.cap(),
273 "cno dst={} src={} len={} cap={}",
280 src
+ len
<= self.cap(),
281 "cno dst={} src={} len={} cap={}",
287 ptr
::copy_nonoverlapping(self.ptr().add(src
), self.ptr().add(dst
), len
);
290 /// Copies a potentially wrapping block of memory len long from src to dest.
291 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
292 /// most one continuous overlapping region between src and dest).
293 unsafe fn wrap_copy(&self, dst
: usize, src
: usize, len
: usize) {
295 fn diff(a
: usize, b
: usize) -> usize {
296 if a
<= b { b - a }
else { a - b }
299 cmp
::min(diff(dst
, src
), self.cap() - diff(dst
, src
)) + len
<= self.cap(),
300 "wrc dst={} src={} len={} cap={}",
307 if src
== dst
|| len
== 0 {
311 let dst_after_src
= self.wrap_sub(dst
, src
) < len
;
313 let src_pre_wrap_len
= self.cap() - src
;
314 let dst_pre_wrap_len
= self.cap() - dst
;
315 let src_wraps
= src_pre_wrap_len
< len
;
316 let dst_wraps
= dst_pre_wrap_len
< len
;
318 match (dst_after_src
, src_wraps
, dst_wraps
) {
319 (_
, false, false) => {
320 // src doesn't wrap, dst doesn't wrap
323 // 1 [_ _ A A B B C C _]
324 // 2 [_ _ A A A A B B _]
327 self.copy(dst
, src
, len
);
329 (false, false, true) => {
330 // dst before src, src doesn't wrap, dst wraps
333 // 1 [A A B B _ _ _ C C]
334 // 2 [A A B B _ _ _ A A]
335 // 3 [B B B B _ _ _ A A]
338 self.copy(dst
, src
, dst_pre_wrap_len
);
339 self.copy(0, src
+ dst_pre_wrap_len
, len
- dst_pre_wrap_len
);
341 (true, false, true) => {
342 // src before dst, src doesn't wrap, dst wraps
345 // 1 [C C _ _ _ A A B B]
346 // 2 [B B _ _ _ A A B B]
347 // 3 [B B _ _ _ A A A A]
350 self.copy(0, src
+ dst_pre_wrap_len
, len
- dst_pre_wrap_len
);
351 self.copy(dst
, src
, dst_pre_wrap_len
);
353 (false, true, false) => {
354 // dst before src, src wraps, dst doesn't wrap
357 // 1 [C C _ _ _ A A B B]
358 // 2 [C C _ _ _ B B B B]
359 // 3 [C C _ _ _ B B C C]
362 self.copy(dst
, src
, src_pre_wrap_len
);
363 self.copy(dst
+ src_pre_wrap_len
, 0, len
- src_pre_wrap_len
);
365 (true, true, false) => {
366 // src before dst, src wraps, dst doesn't wrap
369 // 1 [A A B B _ _ _ C C]
370 // 2 [A A A A _ _ _ C C]
371 // 3 [C C A A _ _ _ C C]
374 self.copy(dst
+ src_pre_wrap_len
, 0, len
- src_pre_wrap_len
);
375 self.copy(dst
, src
, src_pre_wrap_len
);
377 (false, true, true) => {
378 // dst before src, src wraps, dst wraps
381 // 1 [A B C D _ E F G H]
382 // 2 [A B C D _ E G H H]
383 // 3 [A B C D _ E G H A]
384 // 4 [B C C D _ E G H A]
387 debug_assert
!(dst_pre_wrap_len
> src_pre_wrap_len
);
388 let delta
= dst_pre_wrap_len
- src_pre_wrap_len
;
389 self.copy(dst
, src
, src_pre_wrap_len
);
390 self.copy(dst
+ src_pre_wrap_len
, 0, delta
);
391 self.copy(0, delta
, len
- dst_pre_wrap_len
);
393 (true, true, true) => {
394 // src before dst, src wraps, dst wraps
397 // 1 [A B C D _ E F G H]
398 // 2 [A A B D _ E F G H]
399 // 3 [H A B D _ E F G H]
400 // 4 [H A B D _ E F F G]
403 debug_assert
!(src_pre_wrap_len
> dst_pre_wrap_len
);
404 let delta
= src_pre_wrap_len
- dst_pre_wrap_len
;
405 self.copy(delta
, 0, len
- src_pre_wrap_len
);
406 self.copy(0, self.cap() - delta
, delta
);
407 self.copy(dst
, src
, dst_pre_wrap_len
);
412 /// Frobs the head and tail sections around to handle the fact that we
413 /// just reallocated. Unsafe because it trusts old_capacity.
415 unsafe fn handle_capacity_increase(&mut self, old_capacity
: usize) {
416 let new_capacity
= self.cap();
418 // Move the shortest contiguous section of the ring buffer
420 // [o o o o o o o . ]
422 // A [o o o o o o o . . . . . . . . . ]
424 // [o o . o o o o o ]
426 // B [. . . o o o o o o o . . . . . . ]
428 // [o o o o o . o o ]
430 // C [o o o o o . . . . . . . . . o o ]
432 if self.tail
<= self.head
{
435 } else if self.head
< old_capacity
- self.tail
{
437 self.copy_nonoverlapping(old_capacity
, 0, self.head
);
438 self.head
+= old_capacity
;
439 debug_assert
!(self.head
> self.tail
);
442 let new_tail
= new_capacity
- (old_capacity
- self.tail
);
443 self.copy_nonoverlapping(new_tail
, self.tail
, old_capacity
- self.tail
);
444 self.tail
= new_tail
;
445 debug_assert
!(self.head
< self.tail
);
447 debug_assert
!(self.head
< self.cap());
448 debug_assert
!(self.tail
< self.cap());
449 debug_assert
!(self.cap().count_ones() == 1);
453 impl<T
> VecDeque
<T
> {
454 /// Creates an empty `VecDeque`.
459 /// use std::collections::VecDeque;
461 /// let vector: VecDeque<u32> = VecDeque::new();
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub fn new() -> VecDeque
<T
> {
465 VecDeque
::with_capacity(INITIAL_CAPACITY
)
468 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
473 /// use std::collections::VecDeque;
475 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn with_capacity(capacity
: usize) -> VecDeque
<T
> {
479 // +1 since the ringbuffer always leaves one space empty
480 let cap
= cmp
::max(capacity
+ 1, MINIMUM_CAPACITY
+ 1).next_power_of_two();
481 assert
!(cap
> capacity
, "capacity overflow");
483 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity(cap) }
486 /// Retrieves an element in the `VecDeque` by index.
488 /// Element at index 0 is the front of the queue.
493 /// use std::collections::VecDeque;
495 /// let mut buf = VecDeque::new();
496 /// buf.push_back(3);
497 /// buf.push_back(4);
498 /// buf.push_back(5);
499 /// assert_eq!(buf.get(1), Some(&4));
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn get(&self, index
: usize) -> Option
<&T
> {
503 if index
< self.len() {
504 let idx
= self.wrap_add(self.tail
, index
);
505 unsafe { Some(&*self.ptr().add(idx)) }
511 /// Retrieves an element in the `VecDeque` mutably by index.
513 /// Element at index 0 is the front of the queue.
518 /// use std::collections::VecDeque;
520 /// let mut buf = VecDeque::new();
521 /// buf.push_back(3);
522 /// buf.push_back(4);
523 /// buf.push_back(5);
524 /// if let Some(elem) = buf.get_mut(1) {
528 /// assert_eq!(buf[1], 7);
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn get_mut(&mut self, index
: usize) -> Option
<&mut T
> {
532 if index
< self.len() {
533 let idx
= self.wrap_add(self.tail
, index
);
534 unsafe { Some(&mut *self.ptr().add(idx)) }
540 /// Swaps elements at indices `i` and `j`.
542 /// `i` and `j` may be equal.
544 /// Element at index 0 is the front of the queue.
548 /// Panics if either index is out of bounds.
553 /// use std::collections::VecDeque;
555 /// let mut buf = VecDeque::new();
556 /// buf.push_back(3);
557 /// buf.push_back(4);
558 /// buf.push_back(5);
559 /// assert_eq!(buf, [3, 4, 5]);
561 /// assert_eq!(buf, [5, 4, 3]);
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub fn swap(&mut self, i
: usize, j
: usize) {
565 assert
!(i
< self.len());
566 assert
!(j
< self.len());
567 let ri
= self.wrap_add(self.tail
, i
);
568 let rj
= self.wrap_add(self.tail
, j
);
569 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
572 /// Returns the number of elements the `VecDeque` can hold without
578 /// use std::collections::VecDeque;
580 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
581 /// assert!(buf.capacity() >= 10);
584 #[stable(feature = "rust1", since = "1.0.0")]
585 pub fn capacity(&self) -> usize {
589 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
590 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
592 /// Note that the allocator may give the collection more space than it requests. Therefore
593 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
594 /// insertions are expected.
598 /// Panics if the new capacity overflows `usize`.
603 /// use std::collections::VecDeque;
605 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
606 /// buf.reserve_exact(10);
607 /// assert!(buf.capacity() >= 11);
610 /// [`reserve`]: #method.reserve
611 #[stable(feature = "rust1", since = "1.0.0")]
612 pub fn reserve_exact(&mut self, additional
: usize) {
613 self.reserve(additional
);
616 /// Reserves capacity for at least `additional` more elements to be inserted in the given
617 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
621 /// Panics if the new capacity overflows `usize`.
626 /// use std::collections::VecDeque;
628 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
630 /// assert!(buf.capacity() >= 11);
632 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn reserve(&mut self, additional
: usize) {
634 let old_cap
= self.cap();
635 let used_cap
= self.len() + 1;
636 let new_cap
= used_cap
637 .checked_add(additional
)
638 .and_then(|needed_cap
| needed_cap
.checked_next_power_of_two())
639 .expect("capacity overflow");
641 if new_cap
> old_cap
{
642 self.buf
.reserve_exact(used_cap
, new_cap
- used_cap
);
644 self.handle_capacity_increase(old_cap
);
649 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
650 /// be inserted in the given `VecDeque<T>`. After calling `reserve_exact`,
651 /// capacity will be greater than or equal to `self.len() + additional`.
652 /// Does nothing if the capacity is already sufficient.
654 /// Note that the allocator may give the collection more space than it
655 /// requests. Therefore, capacity can not be relied upon to be precisely
656 /// minimal. Prefer `reserve` if future insertions are expected.
660 /// If the capacity overflows, or the allocator reports a failure, then an error
666 /// #![feature(try_reserve)]
667 /// use std::collections::TryReserveError;
668 /// use std::collections::VecDeque;
670 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
671 /// let mut output = VecDeque::new();
673 /// // Pre-reserve the memory, exiting if we can't
674 /// output.try_reserve_exact(data.len())?;
676 /// // Now we know this can't OOM in the middle of our complex work
677 /// output.extend(data.iter().map(|&val| {
678 /// val * 2 + 5 // very complicated
683 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
685 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
686 pub fn try_reserve_exact(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
687 self.try_reserve(additional
)
690 /// Tries to reserve capacity for at least `additional` more elements to be inserted
691 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
692 /// frequent reallocations. After calling `reserve`, capacity will be
693 /// greater than or equal to `self.len() + additional`. Does nothing if
694 /// capacity is already sufficient.
698 /// If the capacity overflows, or the allocator reports a failure, then an error
704 /// #![feature(try_reserve)]
705 /// use std::collections::TryReserveError;
706 /// use std::collections::VecDeque;
708 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
709 /// let mut output = VecDeque::new();
711 /// // Pre-reserve the memory, exiting if we can't
712 /// output.try_reserve(data.len())?;
714 /// // Now we know this can't OOM in the middle of our complex work
715 /// output.extend(data.iter().map(|&val| {
716 /// val * 2 + 5 // very complicated
721 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
723 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
724 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
725 let old_cap
= self.cap();
726 let used_cap
= self.len() + 1;
727 let new_cap
= used_cap
728 .checked_add(additional
)
729 .and_then(|needed_cap
| needed_cap
.checked_next_power_of_two())
730 .ok_or(TryReserveError
::CapacityOverflow
)?
;
732 if new_cap
> old_cap
{
733 self.buf
.try_reserve_exact(used_cap
, new_cap
- used_cap
)?
;
735 self.handle_capacity_increase(old_cap
);
741 /// Shrinks the capacity of the `VecDeque` as much as possible.
743 /// It will drop down as close as possible to the length but the allocator may still inform the
744 /// `VecDeque` that there is space for a few more elements.
749 /// use std::collections::VecDeque;
751 /// let mut buf = VecDeque::with_capacity(15);
752 /// buf.extend(0..4);
753 /// assert_eq!(buf.capacity(), 15);
754 /// buf.shrink_to_fit();
755 /// assert!(buf.capacity() >= 4);
757 #[stable(feature = "deque_extras_15", since = "1.5.0")]
758 pub fn shrink_to_fit(&mut self) {
762 /// Shrinks the capacity of the `VecDeque` with a lower bound.
764 /// The capacity will remain at least as large as both the length
765 /// and the supplied value.
767 /// Panics if the current capacity is smaller than the supplied
768 /// minimum capacity.
773 /// #![feature(shrink_to)]
774 /// use std::collections::VecDeque;
776 /// let mut buf = VecDeque::with_capacity(15);
777 /// buf.extend(0..4);
778 /// assert_eq!(buf.capacity(), 15);
779 /// buf.shrink_to(6);
780 /// assert!(buf.capacity() >= 6);
781 /// buf.shrink_to(0);
782 /// assert!(buf.capacity() >= 4);
784 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
785 pub fn shrink_to(&mut self, min_capacity
: usize) {
786 assert
!(self.capacity() >= min_capacity
, "Tried to shrink to a larger capacity");
788 // +1 since the ringbuffer always leaves one space empty
789 // len + 1 can't overflow for an existing, well-formed ringbuffer.
790 let target_cap
= cmp
::max(cmp
::max(min_capacity
, self.len()) + 1, MINIMUM_CAPACITY
+ 1)
791 .next_power_of_two();
793 if target_cap
< self.cap() {
794 // There are three cases of interest:
795 // All elements are out of desired bounds
796 // Elements are contiguous, and head is out of desired bounds
797 // Elements are discontiguous, and tail is out of desired bounds
799 // At all other times, element positions are unaffected.
801 // Indicates that elements at the head should be moved.
802 let head_outside
= self.head
== 0 || self.head
>= target_cap
;
803 // Move elements from out of desired bounds (positions after target_cap)
804 if self.tail
>= target_cap
&& head_outside
{
806 // [. . . . . . . . o o o o o o o . ]
808 // [o o o o o o o . ]
810 self.copy_nonoverlapping(0, self.tail
, self.len());
812 self.head
= self.len();
814 } else if self.tail
!= 0 && self.tail
< target_cap
&& head_outside
{
816 // [. . . o o o o o o o . . . . . . ]
818 // [o o . o o o o o ]
819 let len
= self.wrap_sub(self.head
, target_cap
);
821 self.copy_nonoverlapping(0, target_cap
, len
);
824 debug_assert
!(self.head
< self.tail
);
825 } else if self.tail
>= target_cap
{
827 // [o o o o o . . . . . . . . . o o ]
829 // [o o o o o . o o ]
830 debug_assert
!(self.wrap_sub(self.head
, 1) < target_cap
);
831 let len
= self.cap() - self.tail
;
832 let new_tail
= target_cap
- len
;
834 self.copy_nonoverlapping(new_tail
, self.tail
, len
);
836 self.tail
= new_tail
;
837 debug_assert
!(self.head
< self.tail
);
840 self.buf
.shrink_to_fit(target_cap
);
842 debug_assert
!(self.head
< self.cap());
843 debug_assert
!(self.tail
< self.cap());
844 debug_assert
!(self.cap().count_ones() == 1);
848 /// Shortens the `VecDeque`, keeping the first `len` elements and dropping
851 /// If `len` is greater than the `VecDeque`'s current length, this has no
857 /// use std::collections::VecDeque;
859 /// let mut buf = VecDeque::new();
860 /// buf.push_back(5);
861 /// buf.push_back(10);
862 /// buf.push_back(15);
863 /// assert_eq!(buf, [5, 10, 15]);
865 /// assert_eq!(buf, [5]);
867 #[stable(feature = "deque_extras", since = "1.16.0")]
868 pub fn truncate(&mut self, len
: usize) {
871 // * Any slice passed to `drop_in_place` is valid; the second case has
872 // `len <= front.len()` and returning on `len > self.len()` ensures
873 // `begin <= back.len()` in the first case
874 // * The head of the VecDeque is moved before calling `drop_in_place`,
875 // so no value is dropped twice if `drop_in_place` panics
877 if len
> self.len() {
880 let num_dropped
= self.len() - len
;
881 let (front
, back
) = self.as_mut_slices();
882 if len
> front
.len() {
883 let begin
= len
- front
.len();
884 let drop_back
= back
.get_unchecked_mut(begin
..) as *mut _
;
885 self.head
= self.wrap_sub(self.head
, num_dropped
);
886 ptr
::drop_in_place(drop_back
);
888 let drop_back
= back
as *mut _
;
889 let drop_front
= front
.get_unchecked_mut(len
..) as *mut _
;
890 self.head
= self.wrap_sub(self.head
, num_dropped
);
891 ptr
::drop_in_place(drop_front
);
892 ptr
::drop_in_place(drop_back
);
897 /// Returns a front-to-back iterator.
902 /// use std::collections::VecDeque;
904 /// let mut buf = VecDeque::new();
905 /// buf.push_back(5);
906 /// buf.push_back(3);
907 /// buf.push_back(4);
908 /// let b: &[_] = &[&5, &3, &4];
909 /// let c: Vec<&i32> = buf.iter().collect();
910 /// assert_eq!(&c[..], b);
912 #[stable(feature = "rust1", since = "1.0.0")]
913 pub fn iter(&self) -> Iter
<'_
, T
> {
914 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() }
}
917 /// Returns a front-to-back iterator that returns mutable references.
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 /// for num in buf.iter_mut() {
931 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
932 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
934 #[stable(feature = "rust1", since = "1.0.0")]
935 pub fn iter_mut(&mut self) -> IterMut
<'_
, T
> {
936 IterMut { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_mut_slice() }
}
939 /// Returns a pair of slices which contain, in order, the contents of the
945 /// use std::collections::VecDeque;
947 /// let mut vector = VecDeque::new();
949 /// vector.push_back(0);
950 /// vector.push_back(1);
951 /// vector.push_back(2);
953 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
955 /// vector.push_front(10);
956 /// vector.push_front(9);
958 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
961 #[stable(feature = "deque_extras_15", since = "1.5.0")]
962 pub fn as_slices(&self) -> (&[T
], &[T
]) {
964 let buf
= self.buffer_as_slice();
965 RingSlices
::ring_slices(buf
, self.head
, self.tail
)
969 /// Returns a pair of slices which contain, in order, the contents of the
975 /// use std::collections::VecDeque;
977 /// let mut vector = VecDeque::new();
979 /// vector.push_back(0);
980 /// vector.push_back(1);
982 /// vector.push_front(10);
983 /// vector.push_front(9);
985 /// vector.as_mut_slices().0[0] = 42;
986 /// vector.as_mut_slices().1[0] = 24;
987 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
990 #[stable(feature = "deque_extras_15", since = "1.5.0")]
991 pub fn as_mut_slices(&mut self) -> (&mut [T
], &mut [T
]) {
993 let head
= self.head
;
994 let tail
= self.tail
;
995 let buf
= self.buffer_as_mut_slice();
996 RingSlices
::ring_slices(buf
, head
, tail
)
1000 /// Returns the number of elements in the `VecDeque`.
1005 /// use std::collections::VecDeque;
1007 /// let mut v = VecDeque::new();
1008 /// assert_eq!(v.len(), 0);
1010 /// assert_eq!(v.len(), 1);
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub fn len(&self) -> usize {
1014 count(self.tail
, self.head
, self.cap())
1017 /// Returns `true` if the `VecDeque` is empty.
1022 /// use std::collections::VecDeque;
1024 /// let mut v = VecDeque::new();
1025 /// assert!(v.is_empty());
1026 /// v.push_front(1);
1027 /// assert!(!v.is_empty());
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 pub fn is_empty(&self) -> bool
{
1031 self.tail
== self.head
1034 /// Creates a draining iterator that removes the specified range in the
1035 /// `VecDeque` and yields the removed items.
1037 /// Note 1: The element range is removed even if the iterator is not
1038 /// consumed until the end.
1040 /// Note 2: It is unspecified how many elements are removed from the deque,
1041 /// if the `Drain` value is not dropped, but the borrow it holds expires
1042 /// (e.g., due to `mem::forget`).
1046 /// Panics if the starting point is greater than the end point or if
1047 /// the end point is greater than the length of the vector.
1052 /// use std::collections::VecDeque;
1054 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1055 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
1056 /// assert_eq!(drained, [3]);
1057 /// assert_eq!(v, [1, 2]);
1059 /// // A full range clears all contents
1061 /// assert!(v.is_empty());
1064 #[stable(feature = "drain", since = "1.6.0")]
1065 pub fn drain
<R
>(&mut self, range
: R
) -> Drain
<'_
, T
>
1067 R
: RangeBounds
<usize>,
1071 // When the Drain is first created, the source deque is shortened to
1072 // make sure no uninitialized or moved-from elements are accessible at
1073 // all if the Drain's destructor never gets to run.
1075 // Drain will ptr::read out the values to remove.
1076 // When finished, the remaining data will be copied back to cover the hole,
1077 // and the head/tail values will be restored correctly.
1079 let len
= self.len();
1080 let start
= match range
.start_bound() {
1082 Excluded(&n
) => n
+ 1,
1085 let end
= match range
.end_bound() {
1086 Included(&n
) => n
+ 1,
1090 assert
!(start
<= end
, "drain lower bound was too large");
1091 assert
!(end
<= len
, "drain upper bound was too large");
1093 // The deque's elements are parted into three segments:
1094 // * self.tail -> drain_tail
1095 // * drain_tail -> drain_head
1096 // * drain_head -> self.head
1098 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1100 // We store drain_tail as self.head, and drain_head and self.head as
1101 // after_tail and after_head respectively on the Drain. This also
1102 // truncates the effective array such that if the Drain is leaked, we
1103 // have forgotten about the potentially moved values after the start of
1107 // [. . . o o x x o o . . .]
1109 let drain_tail
= self.wrap_add(self.tail
, start
);
1110 let drain_head
= self.wrap_add(self.tail
, end
);
1111 let head
= self.head
;
1113 // "forget" about the values after the start of the drain until after
1114 // the drain is complete and the Drain destructor is run.
1115 self.head
= drain_tail
;
1118 deque
: NonNull
::from(&mut *self),
1119 after_tail
: drain_head
,
1124 // Crucially, we only create shared references from `self` here and read from
1125 // it. We do not write to `self` nor reborrow to a mutable reference.
1126 // Hence the raw pointer we created above, for `deque`, remains valid.
1127 ring
: unsafe { self.buffer_as_slice() }
,
1132 /// Clears the `VecDeque`, removing all values.
1137 /// use std::collections::VecDeque;
1139 /// let mut v = VecDeque::new();
1142 /// assert!(v.is_empty());
1144 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn clear(&mut self) {
1150 /// Returns `true` if the `VecDeque` contains an element equal to the
1156 /// use std::collections::VecDeque;
1158 /// let mut vector: VecDeque<u32> = VecDeque::new();
1160 /// vector.push_back(0);
1161 /// vector.push_back(1);
1163 /// assert_eq!(vector.contains(&1), true);
1164 /// assert_eq!(vector.contains(&10), false);
1166 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1167 pub fn contains(&self, x
: &T
) -> bool
1171 let (a
, b
) = self.as_slices();
1172 a
.contains(x
) || b
.contains(x
)
1175 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1181 /// use std::collections::VecDeque;
1183 /// let mut d = VecDeque::new();
1184 /// assert_eq!(d.front(), None);
1188 /// assert_eq!(d.front(), Some(&1));
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 pub fn front(&self) -> Option
<&T
> {
1192 if !self.is_empty() { Some(&self[0]) }
else { None }
1195 /// Provides a mutable reference to the front element, or `None` if the
1196 /// `VecDeque` is empty.
1201 /// use std::collections::VecDeque;
1203 /// let mut d = VecDeque::new();
1204 /// assert_eq!(d.front_mut(), None);
1208 /// match d.front_mut() {
1209 /// Some(x) => *x = 9,
1212 /// assert_eq!(d.front(), Some(&9));
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 pub fn front_mut(&mut self) -> Option
<&mut T
> {
1216 if !self.is_empty() { Some(&mut self[0]) }
else { None }
1219 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1225 /// use std::collections::VecDeque;
1227 /// let mut d = VecDeque::new();
1228 /// assert_eq!(d.back(), None);
1232 /// assert_eq!(d.back(), Some(&2));
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 pub fn back(&self) -> Option
<&T
> {
1236 if !self.is_empty() { Some(&self[self.len() - 1]) }
else { None }
1239 /// Provides a mutable reference to the back element, or `None` if the
1240 /// `VecDeque` is empty.
1245 /// use std::collections::VecDeque;
1247 /// let mut d = VecDeque::new();
1248 /// assert_eq!(d.back(), None);
1252 /// match d.back_mut() {
1253 /// Some(x) => *x = 9,
1256 /// assert_eq!(d.back(), Some(&9));
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 pub fn back_mut(&mut self) -> Option
<&mut T
> {
1260 let len
= self.len();
1261 if !self.is_empty() { Some(&mut self[len - 1]) }
else { None }
1264 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1270 /// use std::collections::VecDeque;
1272 /// let mut d = VecDeque::new();
1276 /// assert_eq!(d.pop_front(), Some(1));
1277 /// assert_eq!(d.pop_front(), Some(2));
1278 /// assert_eq!(d.pop_front(), None);
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 pub fn pop_front(&mut self) -> Option
<T
> {
1282 if self.is_empty() {
1285 let tail
= self.tail
;
1286 self.tail
= self.wrap_add(self.tail
, 1);
1287 unsafe { Some(self.buffer_read(tail)) }
1291 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1297 /// use std::collections::VecDeque;
1299 /// let mut buf = VecDeque::new();
1300 /// assert_eq!(buf.pop_back(), None);
1301 /// buf.push_back(1);
1302 /// buf.push_back(3);
1303 /// assert_eq!(buf.pop_back(), Some(3));
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub fn pop_back(&mut self) -> Option
<T
> {
1307 if self.is_empty() {
1310 self.head
= self.wrap_sub(self.head
, 1);
1311 let head
= self.head
;
1312 unsafe { Some(self.buffer_read(head)) }
1316 /// Prepends an element to the `VecDeque`.
1321 /// use std::collections::VecDeque;
1323 /// let mut d = VecDeque::new();
1324 /// d.push_front(1);
1325 /// d.push_front(2);
1326 /// assert_eq!(d.front(), Some(&2));
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 pub fn push_front(&mut self, value
: T
) {
1330 self.grow_if_necessary();
1332 self.tail
= self.wrap_sub(self.tail
, 1);
1333 let tail
= self.tail
;
1335 self.buffer_write(tail
, value
);
1339 /// Appends an element to the back of the `VecDeque`.
1344 /// use std::collections::VecDeque;
1346 /// let mut buf = VecDeque::new();
1347 /// buf.push_back(1);
1348 /// buf.push_back(3);
1349 /// assert_eq!(3, *buf.back().unwrap());
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 pub fn push_back(&mut self, value
: T
) {
1353 self.grow_if_necessary();
1355 let head
= self.head
;
1356 self.head
= self.wrap_add(self.head
, 1);
1357 unsafe { self.buffer_write(head, value) }
1361 fn is_contiguous(&self) -> bool
{
1362 self.tail
<= self.head
1365 /// Removes an element from anywhere in the `VecDeque` and returns it,
1366 /// replacing it with the first element.
1368 /// This does not preserve ordering, but is O(1).
1370 /// Returns `None` if `index` is out of bounds.
1372 /// Element at index 0 is the front of the queue.
1377 /// use std::collections::VecDeque;
1379 /// let mut buf = VecDeque::new();
1380 /// assert_eq!(buf.swap_remove_front(0), None);
1381 /// buf.push_back(1);
1382 /// buf.push_back(2);
1383 /// buf.push_back(3);
1384 /// assert_eq!(buf, [1, 2, 3]);
1386 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1387 /// assert_eq!(buf, [2, 1]);
1389 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1390 pub fn swap_remove_front(&mut self, index
: usize) -> Option
<T
> {
1391 let length
= self.len();
1392 if length
> 0 && index
< length
&& index
!= 0 {
1393 self.swap(index
, 0);
1394 } else if index
>= length
{
1400 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1403 /// This does not preserve ordering, but is O(1).
1405 /// Returns `None` if `index` is out of bounds.
1407 /// Element at index 0 is the front of the queue.
1412 /// use std::collections::VecDeque;
1414 /// let mut buf = VecDeque::new();
1415 /// assert_eq!(buf.swap_remove_back(0), None);
1416 /// buf.push_back(1);
1417 /// buf.push_back(2);
1418 /// buf.push_back(3);
1419 /// assert_eq!(buf, [1, 2, 3]);
1421 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1422 /// assert_eq!(buf, [3, 2]);
1424 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1425 pub fn swap_remove_back(&mut self, index
: usize) -> Option
<T
> {
1426 let length
= self.len();
1427 if length
> 0 && index
< length
- 1 {
1428 self.swap(index
, length
- 1);
1429 } else if index
>= length
{
1435 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1436 /// greater than or equal to `index` towards the back.
1438 /// Element at index 0 is the front of the queue.
1442 /// Panics if `index` is greater than `VecDeque`'s length
1447 /// use std::collections::VecDeque;
1449 /// let mut vec_deque = VecDeque::new();
1450 /// vec_deque.push_back('a');
1451 /// vec_deque.push_back('b');
1452 /// vec_deque.push_back('c');
1453 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1455 /// vec_deque.insert(1, 'd');
1456 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1458 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1459 pub fn insert(&mut self, index
: usize, value
: T
) {
1460 assert
!(index
<= self.len(), "index out of bounds");
1461 self.grow_if_necessary();
1463 // Move the least number of elements in the ring buffer and insert
1466 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1468 // There are three main cases:
1469 // Elements are contiguous
1470 // - special case when tail is 0
1471 // Elements are discontiguous and the insert is in the tail section
1472 // Elements are discontiguous and the insert is in the head section
1474 // For each of those there are two more cases:
1475 // Insert is closer to tail
1476 // Insert is closer to head
1478 // Key: H - self.head
1480 // o - Valid element
1481 // I - Insertion element
1482 // A - The element that should be after the insertion point
1483 // M - Indicates element was moved
1485 let idx
= self.wrap_add(self.tail
, index
);
1487 let distance_to_tail
= index
;
1488 let distance_to_head
= self.len() - index
;
1490 let contiguous
= self.is_contiguous();
1492 match (contiguous
, distance_to_tail
<= distance_to_head
, idx
>= self.tail
) {
1493 (true, true, _
) if index
== 0 => {
1498 // [A o o o o o o . . . . . . . . .]
1501 // [A o o o o o o o . . . . . I]
1504 self.tail
= self.wrap_sub(self.tail
, 1);
1506 (true, true, _
) => {
1508 // contiguous, insert closer to tail:
1511 // [. . . o o A o o o o . . . . . .]
1514 // [. . o o I A o o o o . . . . . .]
1517 // contiguous, insert closer to tail and tail is 0:
1521 // [o o A o o o o . . . . . . . . .]
1524 // [o I A o o o o o . . . . . . . o]
1527 let new_tail
= self.wrap_sub(self.tail
, 1);
1529 self.copy(new_tail
, self.tail
, 1);
1530 // Already moved the tail, so we only copy `index - 1` elements.
1531 self.copy(self.tail
, self.tail
+ 1, index
- 1);
1533 self.tail
= new_tail
;
1536 (true, false, _
) => {
1538 // contiguous, insert closer to head:
1541 // [. . . o o o o A o o . . . . . .]
1544 // [. . . o o o o I A o o . . . . .]
1547 self.copy(idx
+ 1, idx
, self.head
- idx
);
1548 self.head
= self.wrap_add(self.head
, 1);
1551 (false, true, true) => {
1553 // discontiguous, insert closer to tail, tail section:
1556 // [o o o o o o . . . . . o o A o o]
1559 // [o o o o o o . . . . o o I A o o]
1562 self.copy(self.tail
- 1, self.tail
, index
);
1566 (false, false, true) => {
1568 // discontiguous, insert closer to head, tail section:
1571 // [o o . . . . . . . o o o o o A o]
1574 // [o o o . . . . . . o o o o o I A]
1577 // copy elements up to new head
1578 self.copy(1, 0, self.head
);
1580 // copy last element into empty spot at bottom of buffer
1581 self.copy(0, self.cap() - 1, 1);
1583 // move elements from idx to end forward not including ^ element
1584 self.copy(idx
+ 1, idx
, self.cap() - 1 - idx
);
1589 (false, true, false) if idx
== 0 => {
1591 // discontiguous, insert is closer to tail, head section,
1592 // and is at index zero in the internal buffer:
1595 // [A o o o o o o o o o . . . o o o]
1598 // [A o o o o o o o o o . . o o o I]
1601 // copy elements up to new tail
1602 self.copy(self.tail
- 1, self.tail
, self.cap() - self.tail
);
1604 // copy last element into empty spot at bottom of buffer
1605 self.copy(self.cap() - 1, 0, 1);
1610 (false, true, false) => {
1612 // discontiguous, insert closer to tail, head section:
1615 // [o o o A o o o o o o . . . o o o]
1618 // [o o I A o o o o o o . . o o o o]
1621 // copy elements up to new tail
1622 self.copy(self.tail
- 1, self.tail
, self.cap() - self.tail
);
1624 // copy last element into empty spot at bottom of buffer
1625 self.copy(self.cap() - 1, 0, 1);
1627 // move elements from idx-1 to end forward not including ^ element
1628 self.copy(0, 1, idx
- 1);
1633 (false, false, false) => {
1635 // discontiguous, insert closer to head, head section:
1638 // [o o o o A o o . . . . . . o o o]
1641 // [o o o o I A o o . . . . . o o o]
1644 self.copy(idx
+ 1, idx
, self.head
- idx
);
1650 // tail might've been changed so we need to recalculate
1651 let new_idx
= self.wrap_add(self.tail
, index
);
1653 self.buffer_write(new_idx
, value
);
1657 /// Removes and returns the element at `index` from the `VecDeque`.
1658 /// Whichever end is closer to the removal point will be moved to make
1659 /// room, and all the affected elements will be moved to new positions.
1660 /// Returns `None` if `index` is out of bounds.
1662 /// Element at index 0 is the front of the queue.
1667 /// use std::collections::VecDeque;
1669 /// let mut buf = VecDeque::new();
1670 /// buf.push_back(1);
1671 /// buf.push_back(2);
1672 /// buf.push_back(3);
1673 /// assert_eq!(buf, [1, 2, 3]);
1675 /// assert_eq!(buf.remove(1), Some(2));
1676 /// assert_eq!(buf, [1, 3]);
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 pub fn remove(&mut self, index
: usize) -> Option
<T
> {
1680 if self.is_empty() || self.len() <= index
{
1684 // There are three main cases:
1685 // Elements are contiguous
1686 // Elements are discontiguous and the removal is in the tail section
1687 // Elements are discontiguous and the removal is in the head section
1688 // - special case when elements are technically contiguous,
1689 // but self.head = 0
1691 // For each of those there are two more cases:
1692 // Insert is closer to tail
1693 // Insert is closer to head
1695 // Key: H - self.head
1697 // o - Valid element
1698 // x - Element marked for removal
1699 // R - Indicates element that is being removed
1700 // M - Indicates element was moved
1702 let idx
= self.wrap_add(self.tail
, index
);
1704 let elem
= unsafe { Some(self.buffer_read(idx)) }
;
1706 let distance_to_tail
= index
;
1707 let distance_to_head
= self.len() - index
;
1709 let contiguous
= self.is_contiguous();
1711 match (contiguous
, distance_to_tail
<= distance_to_head
, idx
>= self.tail
) {
1712 (true, true, _
) => {
1714 // contiguous, remove closer to tail:
1717 // [. . . o o x o o o o . . . . . .]
1720 // [. . . . o o o o o o . . . . . .]
1723 self.copy(self.tail
+ 1, self.tail
, index
);
1727 (true, false, _
) => {
1729 // contiguous, remove closer to head:
1732 // [. . . o o o o x o o . . . . . .]
1735 // [. . . o o o o o o . . . . . . .]
1738 self.copy(idx
, idx
+ 1, self.head
- idx
- 1);
1742 (false, true, true) => {
1744 // discontiguous, remove closer to tail, tail section:
1747 // [o o o o o o . . . . . o o x o o]
1750 // [o o o o o o . . . . . . o o o o]
1753 self.copy(self.tail
+ 1, self.tail
, index
);
1754 self.tail
= self.wrap_add(self.tail
, 1);
1757 (false, false, false) => {
1759 // discontiguous, remove closer to head, head section:
1762 // [o o o o x o o . . . . . . o o o]
1765 // [o o o o o o . . . . . . . o o o]
1768 self.copy(idx
, idx
+ 1, self.head
- idx
- 1);
1772 (false, false, true) => {
1774 // discontiguous, remove closer to head, tail section:
1777 // [o o o . . . . . . o o o o o x o]
1780 // [o o . . . . . . . o o o o o o o]
1783 // or quasi-discontiguous, remove next to head, tail section:
1786 // [. . . . . . . . . o o o o o x o]
1789 // [. . . . . . . . . o o o o o o .]
1792 // draw in elements in the tail section
1793 self.copy(idx
, idx
+ 1, self.cap() - idx
- 1);
1795 // Prevents underflow.
1797 // copy first element into empty spot
1798 self.copy(self.cap() - 1, 0, 1);
1800 // move elements in the head section backwards
1801 self.copy(0, 1, self.head
- 1);
1804 self.head
= self.wrap_sub(self.head
, 1);
1807 (false, true, false) => {
1809 // discontiguous, remove closer to tail, head section:
1812 // [o o x o o o o o o o . . . o o o]
1815 // [o o o o o o o o o o . . . . o o]
1818 // draw in elements up to idx
1819 self.copy(1, 0, idx
);
1821 // copy last element into empty spot
1822 self.copy(0, self.cap() - 1, 1);
1824 // move elements from tail to end forward, excluding the last one
1825 self.copy(self.tail
+ 1, self.tail
, self.cap() - self.tail
- 1);
1827 self.tail
= self.wrap_add(self.tail
, 1);
1835 /// Splits the `VecDeque` into two at the given index.
1837 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1838 /// and the returned `VecDeque` contains elements `[at, len)`.
1840 /// Note that the capacity of `self` does not change.
1842 /// Element at index 0 is the front of the queue.
1846 /// Panics if `at > len`.
1851 /// use std::collections::VecDeque;
1853 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1854 /// let buf2 = buf.split_off(1);
1855 /// assert_eq!(buf, [1]);
1856 /// assert_eq!(buf2, [2, 3]);
1859 #[stable(feature = "split_off", since = "1.4.0")]
1860 pub fn split_off(&mut self, at
: usize) -> Self {
1861 let len
= self.len();
1862 assert
!(at
<= len
, "`at` out of bounds");
1864 let other_len
= len
- at
;
1865 let mut other
= VecDeque
::with_capacity(other_len
);
1868 let (first_half
, second_half
) = self.as_slices();
1870 let first_len
= first_half
.len();
1871 let second_len
= second_half
.len();
1873 // `at` lies in the first half.
1874 let amount_in_first
= first_len
- at
;
1876 ptr
::copy_nonoverlapping(first_half
.as_ptr().add(at
), other
.ptr(), amount_in_first
);
1878 // just take all of the second half.
1879 ptr
::copy_nonoverlapping(
1880 second_half
.as_ptr(),
1881 other
.ptr().add(amount_in_first
),
1885 // `at` lies in the second half, need to factor in the elements we skipped
1886 // in the first half.
1887 let offset
= at
- first_len
;
1888 let amount_in_second
= second_len
- offset
;
1889 ptr
::copy_nonoverlapping(
1890 second_half
.as_ptr().add(offset
),
1897 // Cleanup where the ends of the buffers are
1898 self.head
= self.wrap_sub(self.head
, other_len
);
1899 other
.head
= other
.wrap_index(other_len
);
1904 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1908 /// Panics if the new number of elements in self overflows a `usize`.
1913 /// use std::collections::VecDeque;
1915 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
1916 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
1917 /// buf.append(&mut buf2);
1918 /// assert_eq!(buf, [1, 2, 3, 4]);
1919 /// assert_eq!(buf2, []);
1922 #[stable(feature = "append", since = "1.4.0")]
1923 pub fn append(&mut self, other
: &mut Self) {
1925 self.extend(other
.drain(..));
1928 /// Retains only the elements specified by the predicate.
1930 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1931 /// This method operates in place, visiting each element exactly once in the
1932 /// original order, and preserves the order of the retained elements.
1937 /// use std::collections::VecDeque;
1939 /// let mut buf = VecDeque::new();
1940 /// buf.extend(1..5);
1941 /// buf.retain(|&x| x % 2 == 0);
1942 /// assert_eq!(buf, [2, 4]);
1945 /// The exact order may be useful for tracking external state, like an index.
1948 /// use std::collections::VecDeque;
1950 /// let mut buf = VecDeque::new();
1951 /// buf.extend(1..6);
1953 /// let keep = [false, true, true, false, true];
1955 /// buf.retain(|_| (keep[i], i += 1).0);
1956 /// assert_eq!(buf, [2, 3, 5]);
1958 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1959 pub fn retain
<F
>(&mut self, mut f
: F
)
1961 F
: FnMut(&T
) -> bool
,
1963 let len
= self.len();
1969 self.swap(i
- del
, i
);
1973 self.truncate(len
- del
);
1977 // This may panic or abort
1979 fn grow_if_necessary(&mut self) {
1981 let old_cap
= self.cap();
1984 self.handle_capacity_increase(old_cap
);
1986 debug_assert
!(!self.is_full());
1990 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
1991 /// either by removing excess elements from the back or by appending
1992 /// elements generated by calling `generator` to the back.
1997 /// use std::collections::VecDeque;
1999 /// let mut buf = VecDeque::new();
2000 /// buf.push_back(5);
2001 /// buf.push_back(10);
2002 /// buf.push_back(15);
2003 /// assert_eq!(buf, [5, 10, 15]);
2005 /// buf.resize_with(5, Default::default);
2006 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2008 /// buf.resize_with(2, || unreachable!());
2009 /// assert_eq!(buf, [5, 10]);
2011 /// let mut state = 100;
2012 /// buf.resize_with(5, || { state += 1; state });
2013 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2015 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2016 pub fn resize_with(&mut self, new_len
: usize, generator
: impl FnMut() -> T
) {
2017 let len
= self.len();
2020 self.extend(repeat_with(generator
).take(new_len
- len
))
2022 self.truncate(new_len
);
2026 /// Rotates the double-ended queue `mid` places to the left.
2029 /// - Rotates item `mid` into the first position.
2030 /// - Pops the first `mid` items and pushes them to the end.
2031 /// - Rotates `len() - mid` places to the right.
2035 /// If `mid` is greater than `len()`. Note that `mid == len()`
2036 /// does _not_ panic and is a no-op rotation.
2040 /// Takes `O(min(mid, len() - mid))` time and no extra space.
2045 /// use std::collections::VecDeque;
2047 /// let mut buf: VecDeque<_> = (0..10).collect();
2049 /// buf.rotate_left(3);
2050 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2052 /// for i in 1..10 {
2053 /// assert_eq!(i * 3 % 10, buf[0]);
2054 /// buf.rotate_left(3);
2056 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2058 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2059 pub fn rotate_left(&mut self, mid
: usize) {
2060 assert
!(mid
<= self.len());
2061 let k
= self.len() - mid
;
2063 unsafe { self.rotate_left_inner(mid) }
2065 unsafe { self.rotate_right_inner(k) }
2069 /// Rotates the double-ended queue `k` places to the right.
2072 /// - Rotates the first item into position `k`.
2073 /// - Pops the last `k` items and pushes them to the front.
2074 /// - Rotates `len() - k` places to the left.
2078 /// If `k` is greater than `len()`. Note that `k == len()`
2079 /// does _not_ panic and is a no-op rotation.
2083 /// Takes `O(min(k, len() - k))` time and no extra space.
2088 /// use std::collections::VecDeque;
2090 /// let mut buf: VecDeque<_> = (0..10).collect();
2092 /// buf.rotate_right(3);
2093 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2095 /// for i in 1..10 {
2096 /// assert_eq!(0, buf[i * 3 % 10]);
2097 /// buf.rotate_right(3);
2099 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2101 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2102 pub fn rotate_right(&mut self, k
: usize) {
2103 assert
!(k
<= self.len());
2104 let mid
= self.len() - k
;
2106 unsafe { self.rotate_right_inner(k) }
2108 unsafe { self.rotate_left_inner(mid) }
2112 // Safety: the following two methods require that the rotation amount
2113 // be less than half the length of the deque.
2115 // `wrap_copy` requres that `min(x, cap() - x) + copy_len <= cap()`,
2116 // but than `min` is never more than half the capacity, regardless of x,
2117 // so it's sound to call here because we're calling with something
2118 // less than half the length, which is never above half the capacity.
2120 unsafe fn rotate_left_inner(&mut self, mid
: usize) {
2121 debug_assert
!(mid
* 2 <= self.len());
2122 self.wrap_copy(self.head
, self.tail
, mid
);
2123 self.head
= self.wrap_add(self.head
, mid
);
2124 self.tail
= self.wrap_add(self.tail
, mid
);
2127 unsafe fn rotate_right_inner(&mut self, k
: usize) {
2128 debug_assert
!(k
* 2 <= self.len());
2129 self.head
= self.wrap_sub(self.head
, k
);
2130 self.tail
= self.wrap_sub(self.tail
, k
);
2131 self.wrap_copy(self.tail
, self.head
, k
);
2135 impl<T
: Clone
> VecDeque
<T
> {
2136 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2137 /// either by removing excess elements from the back or by appending clones of `value`
2143 /// use std::collections::VecDeque;
2145 /// let mut buf = VecDeque::new();
2146 /// buf.push_back(5);
2147 /// buf.push_back(10);
2148 /// buf.push_back(15);
2149 /// assert_eq!(buf, [5, 10, 15]);
2151 /// buf.resize(2, 0);
2152 /// assert_eq!(buf, [5, 10]);
2154 /// buf.resize(5, 20);
2155 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2157 #[stable(feature = "deque_extras", since = "1.16.0")]
2158 pub fn resize(&mut self, new_len
: usize, value
: T
) {
2159 self.resize_with(new_len
, || value
.clone());
2163 /// Returns the index in the underlying buffer for a given logical element index.
2165 fn wrap_index(index
: usize, size
: usize) -> usize {
2166 // size is always a power of 2
2167 debug_assert
!(size
.is_power_of_two());
2171 /// Returns the two slices that cover the `VecDeque`'s valid range
2172 trait RingSlices
: Sized
{
2173 fn slice(self, from
: usize, to
: usize) -> Self;
2174 fn split_at(self, i
: usize) -> (Self, Self);
2176 fn ring_slices(buf
: Self, head
: usize, tail
: usize) -> (Self, Self) {
2177 let contiguous
= tail
<= head
;
2179 let (empty
, buf
) = buf
.split_at(0);
2180 (buf
.slice(tail
, head
), empty
)
2182 let (mid
, right
) = buf
.split_at(tail
);
2183 let (left
, _
) = mid
.split_at(head
);
2189 impl<T
> RingSlices
for &[T
] {
2190 fn slice(self, from
: usize, to
: usize) -> Self {
2193 fn split_at(self, i
: usize) -> (Self, Self) {
2198 impl<T
> RingSlices
for &mut [T
] {
2199 fn slice(self, from
: usize, to
: usize) -> Self {
2202 fn split_at(self, i
: usize) -> (Self, Self) {
2203 (*self).split_at_mut(i
)
2207 /// Calculate the number of elements left to be read in the buffer
2209 fn count(tail
: usize, head
: usize, size
: usize) -> usize {
2210 // size is always a power of 2
2211 (head
.wrapping_sub(tail
)) & (size
- 1)
2214 /// An iterator over the elements of a `VecDeque`.
2216 /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its
2217 /// documentation for more.
2219 /// [`iter`]: struct.VecDeque.html#method.iter
2220 /// [`VecDeque`]: struct.VecDeque.html
2221 #[stable(feature = "rust1", since = "1.0.0")]
2222 pub struct Iter
<'a
, T
: 'a
> {
2228 #[stable(feature = "collection_debug", since = "1.17.0")]
2229 impl<T
: fmt
::Debug
> fmt
::Debug
for Iter
<'_
, T
> {
2230 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2231 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2232 f
.debug_tuple("Iter").field(&front
).field(&back
).finish()
2236 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 impl<T
> Clone
for Iter
<'_
, T
> {
2239 fn clone(&self) -> Self {
2240 Iter { ring: self.ring, tail: self.tail, head: self.head }
2244 #[stable(feature = "rust1", since = "1.0.0")]
2245 impl<'a
, T
> Iterator
for Iter
<'a
, T
> {
2249 fn next(&mut self) -> Option
<&'a T
> {
2250 if self.tail
== self.head
{
2253 let tail
= self.tail
;
2254 self.tail
= wrap_index(self.tail
.wrapping_add(1), self.ring
.len());
2255 unsafe { Some(self.ring.get_unchecked(tail)) }
2259 fn size_hint(&self) -> (usize, Option
<usize>) {
2260 let len
= count(self.tail
, self.head
, self.ring
.len());
2264 fn fold
<Acc
, F
>(self, mut accum
: Acc
, mut f
: F
) -> Acc
2266 F
: FnMut(Acc
, Self::Item
) -> Acc
,
2268 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2269 accum
= front
.iter().fold(accum
, &mut f
);
2270 back
.iter().fold(accum
, &mut f
)
2273 fn try_fold
<B
, F
, R
>(&mut self, init
: B
, mut f
: F
) -> R
2276 F
: FnMut(B
, Self::Item
) -> R
,
2279 let (mut iter
, final_res
);
2280 if self.tail
<= self.head
{
2281 // single slice self.ring[self.tail..self.head]
2282 iter
= self.ring
[self.tail
..self.head
].iter();
2283 final_res
= iter
.try_fold(init
, &mut f
);
2285 // two slices: self.ring[self.tail..], self.ring[..self.head]
2286 let (front
, back
) = self.ring
.split_at(self.tail
);
2287 let mut back_iter
= back
.iter();
2288 let res
= back_iter
.try_fold(init
, &mut f
);
2289 let len
= self.ring
.len();
2290 self.tail
= (self.ring
.len() - back_iter
.len()) & (len
- 1);
2291 iter
= front
[..self.head
].iter();
2292 final_res
= iter
.try_fold(res?
, &mut f
);
2294 self.tail
= self.head
- iter
.len();
2298 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2299 if n
>= count(self.tail
, self.head
, self.ring
.len()) {
2300 self.tail
= self.head
;
2303 self.tail
= wrap_index(self.tail
.wrapping_add(n
), self.ring
.len());
2309 fn last(mut self) -> Option
<&'a T
> {
2314 #[stable(feature = "rust1", since = "1.0.0")]
2315 impl<'a
, T
> DoubleEndedIterator
for Iter
<'a
, T
> {
2317 fn next_back(&mut self) -> Option
<&'a T
> {
2318 if self.tail
== self.head
{
2321 self.head
= wrap_index(self.head
.wrapping_sub(1), self.ring
.len());
2322 unsafe { Some(self.ring.get_unchecked(self.head)) }
2325 fn rfold
<Acc
, F
>(self, mut accum
: Acc
, mut f
: F
) -> Acc
2327 F
: FnMut(Acc
, Self::Item
) -> Acc
,
2329 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2330 accum
= back
.iter().rfold(accum
, &mut f
);
2331 front
.iter().rfold(accum
, &mut f
)
2334 fn try_rfold
<B
, F
, R
>(&mut self, init
: B
, mut f
: F
) -> R
2337 F
: FnMut(B
, Self::Item
) -> R
,
2340 let (mut iter
, final_res
);
2341 if self.tail
<= self.head
{
2342 // single slice self.ring[self.tail..self.head]
2343 iter
= self.ring
[self.tail
..self.head
].iter();
2344 final_res
= iter
.try_rfold(init
, &mut f
);
2346 // two slices: self.ring[self.tail..], self.ring[..self.head]
2347 let (front
, back
) = self.ring
.split_at(self.tail
);
2348 let mut front_iter
= front
[..self.head
].iter();
2349 let res
= front_iter
.try_rfold(init
, &mut f
);
2350 self.head
= front_iter
.len();
2352 final_res
= iter
.try_rfold(res?
, &mut f
);
2354 self.head
= self.tail
+ iter
.len();
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 impl<T
> ExactSizeIterator
for Iter
<'_
, T
> {
2361 fn is_empty(&self) -> bool
{
2362 self.head
== self.tail
2366 #[stable(feature = "fused", since = "1.26.0")]
2367 impl<T
> FusedIterator
for Iter
<'_
, T
> {}
2369 /// A mutable iterator over the elements of a `VecDeque`.
2371 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2372 /// documentation for more.
2374 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2375 /// [`VecDeque`]: struct.VecDeque.html
2376 #[stable(feature = "rust1", since = "1.0.0")]
2377 pub struct IterMut
<'a
, T
: 'a
> {
2383 #[stable(feature = "collection_debug", since = "1.17.0")]
2384 impl<T
: fmt
::Debug
> fmt
::Debug
for IterMut
<'_
, T
> {
2385 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2386 let (front
, back
) = RingSlices
::ring_slices(&*self.ring
, self.head
, self.tail
);
2387 f
.debug_tuple("IterMut").field(&front
).field(&back
).finish()
2391 #[stable(feature = "rust1", since = "1.0.0")]
2392 impl<'a
, T
> Iterator
for IterMut
<'a
, T
> {
2393 type Item
= &'a
mut T
;
2396 fn next(&mut self) -> Option
<&'a
mut T
> {
2397 if self.tail
== self.head
{
2400 let tail
= self.tail
;
2401 self.tail
= wrap_index(self.tail
.wrapping_add(1), self.ring
.len());
2404 let elem
= self.ring
.get_unchecked_mut(tail
);
2405 Some(&mut *(elem
as *mut _
))
2410 fn size_hint(&self) -> (usize, Option
<usize>) {
2411 let len
= count(self.tail
, self.head
, self.ring
.len());
2415 fn fold
<Acc
, F
>(self, mut accum
: Acc
, mut f
: F
) -> Acc
2417 F
: FnMut(Acc
, Self::Item
) -> Acc
,
2419 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2420 accum
= front
.iter_mut().fold(accum
, &mut f
);
2421 back
.iter_mut().fold(accum
, &mut f
)
2424 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2425 if n
>= count(self.tail
, self.head
, self.ring
.len()) {
2426 self.tail
= self.head
;
2429 self.tail
= wrap_index(self.tail
.wrapping_add(n
), self.ring
.len());
2435 fn last(mut self) -> Option
<&'a
mut T
> {
2440 #[stable(feature = "rust1", since = "1.0.0")]
2441 impl<'a
, T
> DoubleEndedIterator
for IterMut
<'a
, T
> {
2443 fn next_back(&mut self) -> Option
<&'a
mut T
> {
2444 if self.tail
== self.head
{
2447 self.head
= wrap_index(self.head
.wrapping_sub(1), self.ring
.len());
2450 let elem
= self.ring
.get_unchecked_mut(self.head
);
2451 Some(&mut *(elem
as *mut _
))
2455 fn rfold
<Acc
, F
>(self, mut accum
: Acc
, mut f
: F
) -> Acc
2457 F
: FnMut(Acc
, Self::Item
) -> Acc
,
2459 let (front
, back
) = RingSlices
::ring_slices(self.ring
, self.head
, self.tail
);
2460 accum
= back
.iter_mut().rfold(accum
, &mut f
);
2461 front
.iter_mut().rfold(accum
, &mut f
)
2465 #[stable(feature = "rust1", since = "1.0.0")]
2466 impl<T
> ExactSizeIterator
for IterMut
<'_
, T
> {
2467 fn is_empty(&self) -> bool
{
2468 self.head
== self.tail
2472 #[stable(feature = "fused", since = "1.26.0")]
2473 impl<T
> FusedIterator
for IterMut
<'_
, T
> {}
2475 /// An owning iterator over the elements of a `VecDeque`.
2477 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`]
2478 /// (provided by the `IntoIterator` trait). See its documentation for more.
2480 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2481 /// [`VecDeque`]: struct.VecDeque.html
2483 #[stable(feature = "rust1", since = "1.0.0")]
2484 pub struct IntoIter
<T
> {
2488 #[stable(feature = "collection_debug", since = "1.17.0")]
2489 impl<T
: fmt
::Debug
> fmt
::Debug
for IntoIter
<T
> {
2490 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2491 f
.debug_tuple("IntoIter").field(&self.inner
).finish()
2495 #[stable(feature = "rust1", since = "1.0.0")]
2496 impl<T
> Iterator
for IntoIter
<T
> {
2500 fn next(&mut self) -> Option
<T
> {
2501 self.inner
.pop_front()
2505 fn size_hint(&self) -> (usize, Option
<usize>) {
2506 let len
= self.inner
.len();
2511 #[stable(feature = "rust1", since = "1.0.0")]
2512 impl<T
> DoubleEndedIterator
for IntoIter
<T
> {
2514 fn next_back(&mut self) -> Option
<T
> {
2515 self.inner
.pop_back()
2519 #[stable(feature = "rust1", since = "1.0.0")]
2520 impl<T
> ExactSizeIterator
for IntoIter
<T
> {
2521 fn is_empty(&self) -> bool
{
2522 self.inner
.is_empty()
2526 #[stable(feature = "fused", since = "1.26.0")]
2527 impl<T
> FusedIterator
for IntoIter
<T
> {}
2529 /// A draining iterator over the elements of a `VecDeque`.
2531 /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its
2532 /// documentation for more.
2534 /// [`drain`]: struct.VecDeque.html#method.drain
2535 /// [`VecDeque`]: struct.VecDeque.html
2536 #[stable(feature = "drain", since = "1.6.0")]
2537 pub struct Drain
<'a
, T
: 'a
> {
2541 deque
: NonNull
<VecDeque
<T
>>,
2544 #[stable(feature = "collection_debug", since = "1.17.0")]
2545 impl<T
: fmt
::Debug
> fmt
::Debug
for Drain
<'_
, T
> {
2546 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2547 f
.debug_tuple("Drain")
2548 .field(&self.after_tail
)
2549 .field(&self.after_head
)
2555 #[stable(feature = "drain", since = "1.6.0")]
2556 unsafe impl<T
: Sync
> Sync
for Drain
<'_
, T
> {}
2557 #[stable(feature = "drain", since = "1.6.0")]
2558 unsafe impl<T
: Send
> Send
for Drain
<'_
, T
> {}
2560 #[stable(feature = "drain", since = "1.6.0")]
2561 impl<T
> Drop
for Drain
<'_
, T
> {
2562 fn drop(&mut self) {
2563 self.for_each(drop
);
2565 let source_deque
= unsafe { self.deque.as_mut() }
;
2567 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2570 // [. . . o o x x o o . . .]
2572 let orig_tail
= source_deque
.tail
;
2573 let drain_tail
= source_deque
.head
;
2574 let drain_head
= self.after_tail
;
2575 let orig_head
= self.after_head
;
2577 let tail_len
= count(orig_tail
, drain_tail
, source_deque
.cap());
2578 let head_len
= count(drain_head
, orig_head
, source_deque
.cap());
2580 // Restore the original head value
2581 source_deque
.head
= orig_head
;
2583 match (tail_len
, head_len
) {
2585 source_deque
.head
= 0;
2586 source_deque
.tail
= 0;
2589 source_deque
.tail
= drain_head
;
2592 source_deque
.head
= drain_tail
;
2595 if tail_len
<= head_len
{
2596 source_deque
.tail
= source_deque
.wrap_sub(drain_head
, tail_len
);
2597 source_deque
.wrap_copy(source_deque
.tail
, orig_tail
, tail_len
);
2599 source_deque
.head
= source_deque
.wrap_add(drain_tail
, head_len
);
2600 source_deque
.wrap_copy(drain_tail
, drain_head
, head_len
);
2607 #[stable(feature = "drain", since = "1.6.0")]
2608 impl<T
> Iterator
for Drain
<'_
, T
> {
2612 fn next(&mut self) -> Option
<T
> {
2613 self.iter
.next().map(|elt
| unsafe { ptr::read(elt) }
)
2617 fn size_hint(&self) -> (usize, Option
<usize>) {
2618 self.iter
.size_hint()
2622 #[stable(feature = "drain", since = "1.6.0")]
2623 impl<T
> DoubleEndedIterator
for Drain
<'_
, T
> {
2625 fn next_back(&mut self) -> Option
<T
> {
2626 self.iter
.next_back().map(|elt
| unsafe { ptr::read(elt) }
)
2630 #[stable(feature = "drain", since = "1.6.0")]
2631 impl<T
> ExactSizeIterator
for Drain
<'_
, T
> {}
2633 #[stable(feature = "fused", since = "1.26.0")]
2634 impl<T
> FusedIterator
for Drain
<'_
, T
> {}
2636 #[stable(feature = "rust1", since = "1.0.0")]
2637 impl<A
: PartialEq
> PartialEq
for VecDeque
<A
> {
2638 fn eq(&self, other
: &VecDeque
<A
>) -> bool
{
2639 if self.len() != other
.len() {
2642 let (sa
, sb
) = self.as_slices();
2643 let (oa
, ob
) = other
.as_slices();
2644 if sa
.len() == oa
.len() {
2645 sa
== oa
&& sb
== ob
2646 } else if sa
.len() < oa
.len() {
2647 // Always divisible in three sections, for example:
2648 // self: [a b c|d e f]
2649 // other: [0 1 2 3|4 5]
2650 // front = 3, mid = 1,
2651 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2652 let front
= sa
.len();
2653 let mid
= oa
.len() - front
;
2655 let (oa_front
, oa_mid
) = oa
.split_at(front
);
2656 let (sb_mid
, sb_back
) = sb
.split_at(mid
);
2657 debug_assert_eq
!(sa
.len(), oa_front
.len());
2658 debug_assert_eq
!(sb_mid
.len(), oa_mid
.len());
2659 debug_assert_eq
!(sb_back
.len(), ob
.len());
2660 sa
== oa_front
&& sb_mid
== oa_mid
&& sb_back
== ob
2662 let front
= oa
.len();
2663 let mid
= sa
.len() - front
;
2665 let (sa_front
, sa_mid
) = sa
.split_at(front
);
2666 let (ob_mid
, ob_back
) = ob
.split_at(mid
);
2667 debug_assert_eq
!(sa_front
.len(), oa
.len());
2668 debug_assert_eq
!(sa_mid
.len(), ob_mid
.len());
2669 debug_assert_eq
!(sb
.len(), ob_back
.len());
2670 sa_front
== oa
&& sa_mid
== ob_mid
&& sb
== ob_back
2675 #[stable(feature = "rust1", since = "1.0.0")]
2676 impl<A
: Eq
> Eq
for VecDeque
<A
> {}
2678 macro_rules
! __impl_slice_eq1
{
2679 ([$
($vars
:tt
)*] $lhs
:ty
, $rhs
:ty
, $
($constraints
:tt
)*) => {
2680 #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2681 impl<A
, B
, $
($vars
)*> PartialEq
<$rhs
> for $lhs
2686 fn eq(&self, other
: &$rhs
) -> bool
{
2687 if self.len() != other
.len() {
2690 let (sa
, sb
) = self.as_slices();
2691 let (oa
, ob
) = other
[..].split_at(sa
.len());
2692 sa
== oa
&& sb
== ob
2698 __impl_slice_eq1
! { [] VecDeque<A>, Vec<B>, }
2699 __impl_slice_eq1
! { [] VecDeque<A>, &[B], }
2700 __impl_slice_eq1
! { [] VecDeque<A>, &mut [B], }
2701 __impl_slice_eq1
! { [const N: usize] VecDeque<A>, [B; N], [B; N]: LengthAtMost32 }
2702 __impl_slice_eq1
! { [const N: usize] VecDeque<A>, &[B; N], [B; N]: LengthAtMost32 }
2703 __impl_slice_eq1
! { [const N: usize] VecDeque<A>, &mut [B; N], [B; N]: LengthAtMost32 }
2705 #[stable(feature = "rust1", since = "1.0.0")]
2706 impl<A
: PartialOrd
> PartialOrd
for VecDeque
<A
> {
2707 fn partial_cmp(&self, other
: &VecDeque
<A
>) -> Option
<Ordering
> {
2708 self.iter().partial_cmp(other
.iter())
2712 #[stable(feature = "rust1", since = "1.0.0")]
2713 impl<A
: Ord
> Ord
for VecDeque
<A
> {
2715 fn cmp(&self, other
: &VecDeque
<A
>) -> Ordering
{
2716 self.iter().cmp(other
.iter())
2720 #[stable(feature = "rust1", since = "1.0.0")]
2721 impl<A
: Hash
> Hash
for VecDeque
<A
> {
2722 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
2723 self.len().hash(state
);
2724 let (a
, b
) = self.as_slices();
2725 Hash
::hash_slice(a
, state
);
2726 Hash
::hash_slice(b
, state
);
2730 #[stable(feature = "rust1", since = "1.0.0")]
2731 impl<A
> Index
<usize> for VecDeque
<A
> {
2735 fn index(&self, index
: usize) -> &A
{
2736 self.get(index
).expect("Out of bounds access")
2740 #[stable(feature = "rust1", since = "1.0.0")]
2741 impl<A
> IndexMut
<usize> for VecDeque
<A
> {
2743 fn index_mut(&mut self, index
: usize) -> &mut A
{
2744 self.get_mut(index
).expect("Out of bounds access")
2748 #[stable(feature = "rust1", since = "1.0.0")]
2749 impl<A
> FromIterator
<A
> for VecDeque
<A
> {
2750 fn from_iter
<T
: IntoIterator
<Item
= A
>>(iter
: T
) -> VecDeque
<A
> {
2751 let iterator
= iter
.into_iter();
2752 let (lower
, _
) = iterator
.size_hint();
2753 let mut deq
= VecDeque
::with_capacity(lower
);
2754 deq
.extend(iterator
);
2759 #[stable(feature = "rust1", since = "1.0.0")]
2760 impl<T
> IntoIterator
for VecDeque
<T
> {
2762 type IntoIter
= IntoIter
<T
>;
2764 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2766 fn into_iter(self) -> IntoIter
<T
> {
2767 IntoIter { inner: self }
2771 #[stable(feature = "rust1", since = "1.0.0")]
2772 impl<'a
, T
> IntoIterator
for &'a VecDeque
<T
> {
2774 type IntoIter
= Iter
<'a
, T
>;
2776 fn into_iter(self) -> Iter
<'a
, T
> {
2781 #[stable(feature = "rust1", since = "1.0.0")]
2782 impl<'a
, T
> IntoIterator
for &'a
mut VecDeque
<T
> {
2783 type Item
= &'a
mut T
;
2784 type IntoIter
= IterMut
<'a
, T
>;
2786 fn into_iter(self) -> IterMut
<'a
, T
> {
2791 #[stable(feature = "rust1", since = "1.0.0")]
2792 impl<A
> Extend
<A
> for VecDeque
<A
> {
2793 fn extend
<T
: IntoIterator
<Item
= A
>>(&mut self, iter
: T
) {
2794 // This function should be the moral equivalent of:
2796 // for item in iter.into_iter() {
2797 // self.push_back(item);
2799 let mut iter
= iter
.into_iter();
2800 while let Some(element
) = iter
.next() {
2801 if self.len() == self.capacity() {
2802 let (lower
, _
) = iter
.size_hint();
2803 self.reserve(lower
.saturating_add(1));
2806 let head
= self.head
;
2807 self.head
= self.wrap_add(self.head
, 1);
2809 self.buffer_write(head
, element
);
2815 #[stable(feature = "extend_ref", since = "1.2.0")]
2816 impl<'a
, T
: 'a
+ Copy
> Extend
<&'a T
> for VecDeque
<T
> {
2817 fn extend
<I
: IntoIterator
<Item
= &'a T
>>(&mut self, iter
: I
) {
2818 self.extend(iter
.into_iter().cloned());
2822 #[stable(feature = "rust1", since = "1.0.0")]
2823 impl<T
: fmt
::Debug
> fmt
::Debug
for VecDeque
<T
> {
2824 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2825 f
.debug_list().entries(self).finish()
2829 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2830 impl<T
> From
<Vec
<T
>> for VecDeque
<T
> {
2831 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2833 /// [`Vec<T>`]: crate::vec::Vec
2834 /// [`VecDeque<T>`]: crate::collections::VecDeque
2836 /// This avoids reallocating where possible, but the conditions for that are
2837 /// strict, and subject to change, and so shouldn't be relied upon unless the
2838 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
2839 fn from(mut other
: Vec
<T
>) -> Self {
2841 let other_buf
= other
.as_mut_ptr();
2842 let mut buf
= RawVec
::from_raw_parts(other_buf
, other
.capacity());
2843 let len
= other
.len();
2846 // We need to extend the buf if it's not a power of two, too small
2847 // or doesn't have at least one free space
2848 if !buf
.capacity().is_power_of_two()
2849 || (buf
.capacity() < (MINIMUM_CAPACITY
+ 1))
2850 || (buf
.capacity() == len
)
2852 let cap
= cmp
::max(buf
.capacity() + 1, MINIMUM_CAPACITY
+ 1).next_power_of_two();
2853 buf
.reserve_exact(len
, cap
- len
);
2856 VecDeque { tail: 0, head: len, buf }
2861 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2862 impl<T
> From
<VecDeque
<T
>> for Vec
<T
> {
2863 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2865 /// [`Vec<T>`]: crate::vec::Vec
2866 /// [`VecDeque<T>`]: crate::collections::VecDeque
2868 /// This never needs to re-allocate, but does need to do O(n) data movement if
2869 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2874 /// use std::collections::VecDeque;
2876 /// // This one is O(1).
2877 /// let deque: VecDeque<_> = (1..5).collect();
2878 /// let ptr = deque.as_slices().0.as_ptr();
2879 /// let vec = Vec::from(deque);
2880 /// assert_eq!(vec, [1, 2, 3, 4]);
2881 /// assert_eq!(vec.as_ptr(), ptr);
2883 /// // This one needs data rearranging.
2884 /// let mut deque: VecDeque<_> = (1..5).collect();
2885 /// deque.push_front(9);
2886 /// deque.push_front(8);
2887 /// let ptr = deque.as_slices().1.as_ptr();
2888 /// let vec = Vec::from(deque);
2889 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2890 /// assert_eq!(vec.as_ptr(), ptr);
2892 fn from(other
: VecDeque
<T
>) -> Self {
2894 let buf
= other
.buf
.ptr();
2895 let len
= other
.len();
2896 let tail
= other
.tail
;
2897 let head
= other
.head
;
2898 let cap
= other
.cap();
2900 // Need to move the ring to the front of the buffer, as vec will expect this.
2901 if other
.is_contiguous() {
2902 ptr
::copy(buf
.add(tail
), buf
, len
);
2904 if (tail
- head
) >= cmp
::min(cap
- tail
, head
) {
2905 // There is enough free space in the centre for the shortest block so we can
2906 // do this in at most three copy moves.
2907 if (cap
- tail
) > head
{
2908 // right hand block is the long one; move that enough for the left
2909 ptr
::copy(buf
.add(tail
), buf
.add(tail
- head
), cap
- tail
);
2910 // copy left in the end
2911 ptr
::copy(buf
, buf
.add(cap
- head
), head
);
2912 // shift the new thing to the start
2913 ptr
::copy(buf
.add(tail
- head
), buf
, len
);
2915 // left hand block is the long one, we can do it in two!
2916 ptr
::copy(buf
, buf
.add(cap
- tail
), head
);
2917 ptr
::copy(buf
.add(tail
), buf
, cap
- tail
);
2920 // Need to use N swaps to move the ring
2921 // We can use the space at the end of the ring as a temp store
2923 let mut left_edge
: usize = 0;
2924 let mut right_edge
: usize = tail
;
2926 // The general problem looks like this
2927 // GHIJKLM...ABCDEF - before any swaps
2928 // ABCDEFM...GHIJKL - after 1 pass of swaps
2929 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2930 // - then restart the algorithm with a new (smaller) store
2931 // Sometimes the temp store is reached when the right edge is at the end
2932 // of the buffer - this means we've hit the right order with fewer swaps!
2935 // ABCDEF.. - after four only swaps we've finished
2937 while left_edge
< len
&& right_edge
!= cap
{
2938 let mut right_offset
= 0;
2939 for i
in left_edge
..right_edge
{
2940 right_offset
= (i
- left_edge
) % (cap
- right_edge
);
2941 let src
: isize = (right_edge
+ right_offset
) as isize;
2942 ptr
::swap(buf
.add(i
), buf
.offset(src
));
2944 let n_ops
= right_edge
- left_edge
;
2946 right_edge
+= right_offset
+ 1;
2950 let out
= Vec
::from_raw_parts(buf
, len
, cap
);