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
::cmp
::{self, Ordering}
;
12 use core
::hash
::{Hash, Hasher}
;
13 use core
::iter
::{repeat_with, FromIterator}
;
14 use core
::marker
::PhantomData
;
15 use core
::mem
::{self, ManuallyDrop}
;
16 use core
::ops
::{Index, IndexMut, Range, RangeBounds}
;
17 use core
::ptr
::{self, NonNull}
;
20 use crate::collections
::TryReserveError
;
21 use crate::raw_vec
::RawVec
;
27 #[stable(feature = "drain", since = "1.6.0")]
28 pub use self::drain
::Drain
;
32 #[stable(feature = "rust1", since = "1.0.0")]
33 pub use self::iter_mut
::IterMut
;
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use self::into_iter
::IntoIter
;
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub use self::iter
::Iter
;
47 use self::pair_slices
::PairSlices
;
51 use self::ring_slices
::RingSlices
;
58 const INITIAL_CAPACITY
: usize = 7; // 2^3 - 1
59 const MINIMUM_CAPACITY
: usize = 1; // 2 - 1
61 const MAXIMUM_ZST_CAPACITY
: usize = 1 << (core
::mem
::size_of
::<usize>() * 8 - 1); // Largest possible power of two
63 /// A double-ended queue implemented with a growable ring buffer.
65 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
66 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
67 /// push onto the back in this manner, and iterating over `VecDeque` goes front
70 /// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
71 /// in memory. If you want to access the elements as a single slice, such as for
72 /// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
73 /// so that its elements do not wrap, and returns a mutable slice to the
74 /// now-contiguous element sequence.
76 /// [`push_back`]: VecDeque::push_back
77 /// [`pop_front`]: VecDeque::pop_front
78 /// [`extend`]: VecDeque::extend
79 /// [`append`]: VecDeque::append
80 /// [`make_contiguous`]: VecDeque::make_contiguous
81 #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_type")]
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub struct VecDeque
<T
> {
84 // tail and head are pointers into the buffer. Tail always points
85 // to the first element that could be read, Head always points
86 // to where data should be written.
87 // If tail == head the buffer is empty. The length of the ringbuffer
88 // is defined as the distance between the two.
94 #[stable(feature = "rust1", since = "1.0.0")]
95 impl<T
: Clone
> Clone
for VecDeque
<T
> {
96 fn clone(&self) -> VecDeque
<T
> {
97 self.iter().cloned().collect()
100 fn clone_from(&mut self, other
: &Self) {
101 self.truncate(other
.len());
103 let mut iter
= PairSlices
::from(self, other
);
104 while let Some((dst
, src
)) = iter
.next() {
105 dst
.clone_from_slice(&src
);
108 if iter
.has_remainder() {
109 for remainder
in iter
.remainder() {
110 self.extend(remainder
.iter().cloned());
116 #[stable(feature = "rust1", since = "1.0.0")]
117 unsafe impl<#[may_dangle] T> Drop for VecDeque<T> {
119 /// Runs the destructor for all items in the slice when it gets dropped (normally or
120 /// during unwinding).
121 struct Dropper
<'a
, T
>(&'a
mut [T
]);
123 impl<'a
, T
> Drop
for Dropper
<'a
, T
> {
126 ptr
::drop_in_place(self.0);
131 let (front
, back
) = self.as_mut_slices();
133 let _back_dropper
= Dropper(back
);
135 ptr
::drop_in_place(front
);
137 // RawVec handles deallocation
141 #[stable(feature = "rust1", since = "1.0.0")]
142 impl<T
> Default
for VecDeque
<T
> {
143 /// Creates an empty `VecDeque<T>`.
145 fn default() -> VecDeque
<T
> {
150 impl<T
> VecDeque
<T
> {
151 /// Marginally more convenient
153 fn ptr(&self) -> *mut T
{
157 /// Marginally more convenient
159 fn cap(&self) -> usize {
160 if mem
::size_of
::<T
>() == 0 {
161 // For zero sized types, we are always at maximum capacity
168 /// Turn ptr into a slice
170 unsafe fn buffer_as_slice(&self) -> &[T
] {
171 unsafe { slice::from_raw_parts(self.ptr(), self.cap()) }
174 /// Turn ptr into a mut slice
176 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T
] {
177 unsafe { slice::from_raw_parts_mut(self.ptr(), self.cap()) }
180 /// Moves an element out of the buffer
182 unsafe fn buffer_read(&mut self, off
: usize) -> T
{
183 unsafe { ptr::read(self.ptr().add(off)) }
186 /// Writes an element into the buffer, moving it.
188 unsafe fn buffer_write(&mut self, off
: usize, value
: T
) {
190 ptr
::write(self.ptr().add(off
), value
);
194 /// Returns `true` if the buffer is at full capacity.
196 fn is_full(&self) -> bool
{
197 self.cap() - self.len() == 1
200 /// Returns the index in the underlying buffer for a given logical element
203 fn wrap_index(&self, idx
: usize) -> usize {
204 wrap_index(idx
, self.cap())
207 /// Returns the index in the underlying buffer for a given logical element
210 fn wrap_add(&self, idx
: usize, addend
: usize) -> usize {
211 wrap_index(idx
.wrapping_add(addend
), self.cap())
214 /// Returns the index in the underlying buffer for a given logical element
215 /// index - subtrahend.
217 fn wrap_sub(&self, idx
: usize, subtrahend
: usize) -> usize {
218 wrap_index(idx
.wrapping_sub(subtrahend
), self.cap())
221 /// Copies a contiguous block of memory len long from src to dst
223 unsafe fn copy(&self, dst
: usize, src
: usize, len
: usize) {
225 dst
+ len
<= self.cap(),
226 "cpy dst={} src={} len={} cap={}",
233 src
+ len
<= self.cap(),
234 "cpy dst={} src={} len={} cap={}",
241 ptr
::copy(self.ptr().add(src
), self.ptr().add(dst
), len
);
245 /// Copies a contiguous block of memory len long from src to dst
247 unsafe fn copy_nonoverlapping(&self, dst
: usize, src
: usize, len
: usize) {
249 dst
+ len
<= self.cap(),
250 "cno dst={} src={} len={} cap={}",
257 src
+ len
<= self.cap(),
258 "cno dst={} src={} len={} cap={}",
265 ptr
::copy_nonoverlapping(self.ptr().add(src
), self.ptr().add(dst
), len
);
269 /// Copies a potentially wrapping block of memory len long from src to dest.
270 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
271 /// most one continuous overlapping region between src and dest).
272 unsafe fn wrap_copy(&self, dst
: usize, src
: usize, len
: usize) {
274 fn diff(a
: usize, b
: usize) -> usize {
275 if a
<= b { b - a }
else { a - b }
278 cmp
::min(diff(dst
, src
), self.cap() - diff(dst
, src
)) + len
<= self.cap(),
279 "wrc dst={} src={} len={} cap={}",
286 if src
== dst
|| len
== 0 {
290 let dst_after_src
= self.wrap_sub(dst
, src
) < len
;
292 let src_pre_wrap_len
= self.cap() - src
;
293 let dst_pre_wrap_len
= self.cap() - dst
;
294 let src_wraps
= src_pre_wrap_len
< len
;
295 let dst_wraps
= dst_pre_wrap_len
< len
;
297 match (dst_after_src
, src_wraps
, dst_wraps
) {
298 (_
, false, false) => {
299 // src doesn't wrap, dst doesn't wrap
302 // 1 [_ _ A A B B C C _]
303 // 2 [_ _ A A A A B B _]
307 self.copy(dst
, src
, len
);
310 (false, false, true) => {
311 // dst before src, src doesn't wrap, dst wraps
314 // 1 [A A B B _ _ _ C C]
315 // 2 [A A B B _ _ _ A A]
316 // 3 [B B B B _ _ _ A A]
320 self.copy(dst
, src
, dst_pre_wrap_len
);
321 self.copy(0, src
+ dst_pre_wrap_len
, len
- dst_pre_wrap_len
);
324 (true, false, true) => {
325 // src before dst, src doesn't wrap, dst wraps
328 // 1 [C C _ _ _ A A B B]
329 // 2 [B B _ _ _ A A B B]
330 // 3 [B B _ _ _ A A A A]
334 self.copy(0, src
+ dst_pre_wrap_len
, len
- dst_pre_wrap_len
);
335 self.copy(dst
, src
, dst_pre_wrap_len
);
338 (false, true, false) => {
339 // dst before src, src wraps, dst doesn't wrap
342 // 1 [C C _ _ _ A A B B]
343 // 2 [C C _ _ _ B B B B]
344 // 3 [C C _ _ _ B B C C]
348 self.copy(dst
, src
, src_pre_wrap_len
);
349 self.copy(dst
+ src_pre_wrap_len
, 0, len
- src_pre_wrap_len
);
352 (true, true, false) => {
353 // src before dst, src wraps, dst doesn't wrap
356 // 1 [A A B B _ _ _ C C]
357 // 2 [A A A A _ _ _ C C]
358 // 3 [C C A A _ _ _ C C]
362 self.copy(dst
+ src_pre_wrap_len
, 0, len
- src_pre_wrap_len
);
363 self.copy(dst
, src
, src_pre_wrap_len
);
366 (false, true, true) => {
367 // dst before src, src wraps, dst wraps
370 // 1 [A B C D _ E F G H]
371 // 2 [A B C D _ E G H H]
372 // 3 [A B C D _ E G H A]
373 // 4 [B C C D _ E G H A]
376 debug_assert
!(dst_pre_wrap_len
> src_pre_wrap_len
);
377 let delta
= dst_pre_wrap_len
- src_pre_wrap_len
;
379 self.copy(dst
, src
, src_pre_wrap_len
);
380 self.copy(dst
+ src_pre_wrap_len
, 0, delta
);
381 self.copy(0, delta
, len
- dst_pre_wrap_len
);
384 (true, true, true) => {
385 // src before dst, src wraps, dst wraps
388 // 1 [A B C D _ E F G H]
389 // 2 [A A B D _ E F G H]
390 // 3 [H A B D _ E F G H]
391 // 4 [H A B D _ E F F G]
394 debug_assert
!(src_pre_wrap_len
> dst_pre_wrap_len
);
395 let delta
= src_pre_wrap_len
- dst_pre_wrap_len
;
397 self.copy(delta
, 0, len
- src_pre_wrap_len
);
398 self.copy(0, self.cap() - delta
, delta
);
399 self.copy(dst
, src
, dst_pre_wrap_len
);
405 /// Frobs the head and tail sections around to handle the fact that we
406 /// just reallocated. Unsafe because it trusts old_capacity.
408 unsafe fn handle_capacity_increase(&mut self, old_capacity
: usize) {
409 let new_capacity
= self.cap();
411 // Move the shortest contiguous section of the ring buffer
413 // [o o o o o o o . ]
415 // A [o o o o o o o . . . . . . . . . ]
417 // [o o . o o o o o ]
419 // B [. . . o o o o o o o . . . . . . ]
421 // [o o o o o . o o ]
423 // C [o o o o o . . . . . . . . . o o ]
425 if self.tail
<= self.head
{
428 } else if self.head
< old_capacity
- self.tail
{
431 self.copy_nonoverlapping(old_capacity
, 0, self.head
);
433 self.head
+= old_capacity
;
434 debug_assert
!(self.head
> self.tail
);
437 let new_tail
= new_capacity
- (old_capacity
- self.tail
);
439 self.copy_nonoverlapping(new_tail
, self.tail
, old_capacity
- self.tail
);
441 self.tail
= new_tail
;
442 debug_assert
!(self.head
< self.tail
);
444 debug_assert
!(self.head
< self.cap());
445 debug_assert
!(self.tail
< self.cap());
446 debug_assert
!(self.cap().count_ones() == 1);
450 impl<T
> VecDeque
<T
> {
451 /// Creates an empty `VecDeque`.
456 /// use std::collections::VecDeque;
458 /// let vector: VecDeque<u32> = VecDeque::new();
460 #[stable(feature = "rust1", since = "1.0.0")]
461 pub fn new() -> VecDeque
<T
> {
462 VecDeque
::with_capacity(INITIAL_CAPACITY
)
465 /// Creates an empty `VecDeque` with space for at least `capacity` elements.
470 /// use std::collections::VecDeque;
472 /// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn with_capacity(capacity
: usize) -> VecDeque
<T
> {
476 // +1 since the ringbuffer always leaves one space empty
477 let cap
= cmp
::max(capacity
+ 1, MINIMUM_CAPACITY
+ 1).next_power_of_two();
478 assert
!(cap
> capacity
, "capacity overflow");
480 VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity(cap) }
483 /// Provides a reference to the element at the given index.
485 /// Element at index 0 is the front of the queue.
490 /// use std::collections::VecDeque;
492 /// let mut buf = VecDeque::new();
493 /// buf.push_back(3);
494 /// buf.push_back(4);
495 /// buf.push_back(5);
496 /// assert_eq!(buf.get(1), Some(&4));
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn get(&self, index
: usize) -> Option
<&T
> {
500 if index
< self.len() {
501 let idx
= self.wrap_add(self.tail
, index
);
502 unsafe { Some(&*self.ptr().add(idx)) }
508 /// Provides a mutable reference to the element at the given index.
510 /// Element at index 0 is the front of the queue.
515 /// use std::collections::VecDeque;
517 /// let mut buf = VecDeque::new();
518 /// buf.push_back(3);
519 /// buf.push_back(4);
520 /// buf.push_back(5);
521 /// if let Some(elem) = buf.get_mut(1) {
525 /// assert_eq!(buf[1], 7);
527 #[stable(feature = "rust1", since = "1.0.0")]
528 pub fn get_mut(&mut self, index
: usize) -> Option
<&mut T
> {
529 if index
< self.len() {
530 let idx
= self.wrap_add(self.tail
, index
);
531 unsafe { Some(&mut *self.ptr().add(idx)) }
537 /// Swaps elements at indices `i` and `j`.
539 /// `i` and `j` may be equal.
541 /// Element at index 0 is the front of the queue.
545 /// Panics if either index is out of bounds.
550 /// use std::collections::VecDeque;
552 /// let mut buf = VecDeque::new();
553 /// buf.push_back(3);
554 /// buf.push_back(4);
555 /// buf.push_back(5);
556 /// assert_eq!(buf, [3, 4, 5]);
558 /// assert_eq!(buf, [5, 4, 3]);
560 #[stable(feature = "rust1", since = "1.0.0")]
561 pub fn swap(&mut self, i
: usize, j
: usize) {
562 assert
!(i
< self.len());
563 assert
!(j
< self.len());
564 let ri
= self.wrap_add(self.tail
, i
);
565 let rj
= self.wrap_add(self.tail
, j
);
566 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
569 /// Returns the number of elements the `VecDeque` can hold without
575 /// use std::collections::VecDeque;
577 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
578 /// assert!(buf.capacity() >= 10);
581 #[stable(feature = "rust1", since = "1.0.0")]
582 pub fn capacity(&self) -> usize {
586 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
587 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
589 /// Note that the allocator may give the collection more space than it requests. Therefore
590 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
591 /// insertions are expected.
595 /// Panics if the new capacity overflows `usize`.
600 /// use std::collections::VecDeque;
602 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
603 /// buf.reserve_exact(10);
604 /// assert!(buf.capacity() >= 11);
607 /// [`reserve`]: VecDeque::reserve
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub fn reserve_exact(&mut self, additional
: usize) {
610 self.reserve(additional
);
613 /// Reserves capacity for at least `additional` more elements to be inserted in the given
614 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
618 /// Panics if the new capacity overflows `usize`.
623 /// use std::collections::VecDeque;
625 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
627 /// assert!(buf.capacity() >= 11);
629 #[stable(feature = "rust1", since = "1.0.0")]
630 pub fn reserve(&mut self, additional
: usize) {
631 let old_cap
= self.cap();
632 let used_cap
= self.len() + 1;
633 let new_cap
= used_cap
634 .checked_add(additional
)
635 .and_then(|needed_cap
| needed_cap
.checked_next_power_of_two())
636 .expect("capacity overflow");
638 if new_cap
> old_cap
{
639 self.buf
.reserve_exact(used_cap
, new_cap
- used_cap
);
641 self.handle_capacity_increase(old_cap
);
646 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
647 /// be inserted in the given `VecDeque<T>`. After calling `try_reserve_exact`,
648 /// capacity will be greater than or equal to `self.len() + additional`.
649 /// Does nothing if the capacity is already sufficient.
651 /// Note that the allocator may give the collection more space than it
652 /// requests. Therefore, capacity can not be relied upon to be precisely
653 /// minimal. Prefer `reserve` if future insertions are expected.
657 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
663 /// #![feature(try_reserve)]
664 /// use std::collections::TryReserveError;
665 /// use std::collections::VecDeque;
667 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
668 /// let mut output = VecDeque::new();
670 /// // Pre-reserve the memory, exiting if we can't
671 /// output.try_reserve_exact(data.len())?;
673 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
674 /// output.extend(data.iter().map(|&val| {
675 /// val * 2 + 5 // very complicated
680 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
682 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
683 pub fn try_reserve_exact(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
684 self.try_reserve(additional
)
687 /// Tries to reserve capacity for at least `additional` more elements to be inserted
688 /// in the given `VecDeque<T>`. The collection may reserve more space to avoid
689 /// frequent reallocations. After calling `try_reserve`, capacity will be
690 /// greater than or equal to `self.len() + additional`. Does nothing if
691 /// capacity is already sufficient.
695 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
701 /// #![feature(try_reserve)]
702 /// use std::collections::TryReserveError;
703 /// use std::collections::VecDeque;
705 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
706 /// let mut output = VecDeque::new();
708 /// // Pre-reserve the memory, exiting if we can't
709 /// output.try_reserve(data.len())?;
711 /// // Now we know this can't OOM in the middle of our complex work
712 /// output.extend(data.iter().map(|&val| {
713 /// val * 2 + 5 // very complicated
718 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
720 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
721 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
722 let old_cap
= self.cap();
723 let used_cap
= self.len() + 1;
724 let new_cap
= used_cap
725 .checked_add(additional
)
726 .and_then(|needed_cap
| needed_cap
.checked_next_power_of_two())
727 .ok_or(TryReserveError
::CapacityOverflow
)?
;
729 if new_cap
> old_cap
{
730 self.buf
.try_reserve_exact(used_cap
, new_cap
- used_cap
)?
;
732 self.handle_capacity_increase(old_cap
);
738 /// Shrinks the capacity of the `VecDeque` as much as possible.
740 /// It will drop down as close as possible to the length but the allocator may still inform the
741 /// `VecDeque` that there is space for a few more elements.
746 /// use std::collections::VecDeque;
748 /// let mut buf = VecDeque::with_capacity(15);
749 /// buf.extend(0..4);
750 /// assert_eq!(buf.capacity(), 15);
751 /// buf.shrink_to_fit();
752 /// assert!(buf.capacity() >= 4);
754 #[stable(feature = "deque_extras_15", since = "1.5.0")]
755 pub fn shrink_to_fit(&mut self) {
759 /// Shrinks the capacity of the `VecDeque` with a lower bound.
761 /// The capacity will remain at least as large as both the length
762 /// and the supplied value.
764 /// If the current capacity is less than the lower limit, this is a no-op.
769 /// #![feature(shrink_to)]
770 /// use std::collections::VecDeque;
772 /// let mut buf = VecDeque::with_capacity(15);
773 /// buf.extend(0..4);
774 /// assert_eq!(buf.capacity(), 15);
775 /// buf.shrink_to(6);
776 /// assert!(buf.capacity() >= 6);
777 /// buf.shrink_to(0);
778 /// assert!(buf.capacity() >= 4);
780 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
781 pub fn shrink_to(&mut self, min_capacity
: usize) {
782 let min_capacity
= cmp
::min(min_capacity
, self.capacity());
783 // We don't have to worry about an overflow as neither `self.len()` nor `self.capacity()`
784 // can ever be `usize::MAX`. +1 as the ringbuffer always leaves one space empty.
785 let target_cap
= cmp
::max(cmp
::max(min_capacity
, self.len()) + 1, MINIMUM_CAPACITY
+ 1)
786 .next_power_of_two();
788 if target_cap
< self.cap() {
789 // There are three cases of interest:
790 // All elements are out of desired bounds
791 // Elements are contiguous, and head is out of desired bounds
792 // Elements are discontiguous, and tail is out of desired bounds
794 // At all other times, element positions are unaffected.
796 // Indicates that elements at the head should be moved.
797 let head_outside
= self.head
== 0 || self.head
>= target_cap
;
798 // Move elements from out of desired bounds (positions after target_cap)
799 if self.tail
>= target_cap
&& head_outside
{
801 // [. . . . . . . . o o o o o o o . ]
803 // [o o o o o o o . ]
805 self.copy_nonoverlapping(0, self.tail
, self.len());
807 self.head
= self.len();
809 } else if self.tail
!= 0 && self.tail
< target_cap
&& head_outside
{
811 // [. . . o o o o o o o . . . . . . ]
813 // [o o . o o o o o ]
814 let len
= self.wrap_sub(self.head
, target_cap
);
816 self.copy_nonoverlapping(0, target_cap
, len
);
819 debug_assert
!(self.head
< self.tail
);
820 } else if self.tail
>= target_cap
{
822 // [o o o o o . . . . . . . . . o o ]
824 // [o o o o o . o o ]
825 debug_assert
!(self.wrap_sub(self.head
, 1) < target_cap
);
826 let len
= self.cap() - self.tail
;
827 let new_tail
= target_cap
- len
;
829 self.copy_nonoverlapping(new_tail
, self.tail
, len
);
831 self.tail
= new_tail
;
832 debug_assert
!(self.head
< self.tail
);
835 self.buf
.shrink_to_fit(target_cap
);
837 debug_assert
!(self.head
< self.cap());
838 debug_assert
!(self.tail
< self.cap());
839 debug_assert
!(self.cap().count_ones() == 1);
843 /// Shortens the `VecDeque`, keeping the first `len` elements and dropping
846 /// If `len` is greater than the `VecDeque`'s current length, this has no
852 /// use std::collections::VecDeque;
854 /// let mut buf = VecDeque::new();
855 /// buf.push_back(5);
856 /// buf.push_back(10);
857 /// buf.push_back(15);
858 /// assert_eq!(buf, [5, 10, 15]);
860 /// assert_eq!(buf, [5]);
862 #[stable(feature = "deque_extras", since = "1.16.0")]
863 pub fn truncate(&mut self, len
: usize) {
864 /// Runs the destructor for all items in the slice when it gets dropped (normally or
865 /// during unwinding).
866 struct Dropper
<'a
, T
>(&'a
mut [T
]);
868 impl<'a
, T
> Drop
for Dropper
<'a
, T
> {
871 ptr
::drop_in_place(self.0);
878 // * Any slice passed to `drop_in_place` is valid; the second case has
879 // `len <= front.len()` and returning on `len > self.len()` ensures
880 // `begin <= back.len()` in the first case
881 // * The head of the VecDeque is moved before calling `drop_in_place`,
882 // so no value is dropped twice if `drop_in_place` panics
884 if len
> self.len() {
887 let num_dropped
= self.len() - len
;
888 let (front
, back
) = self.as_mut_slices();
889 if len
> front
.len() {
890 let begin
= len
- front
.len();
891 let drop_back
= back
.get_unchecked_mut(begin
..) as *mut _
;
892 self.head
= self.wrap_sub(self.head
, num_dropped
);
893 ptr
::drop_in_place(drop_back
);
895 let drop_back
= back
as *mut _
;
896 let drop_front
= front
.get_unchecked_mut(len
..) as *mut _
;
897 self.head
= self.wrap_sub(self.head
, num_dropped
);
899 // Make sure the second half is dropped even when a destructor
900 // in the first one panics.
901 let _back_dropper
= Dropper(&mut *drop_back
);
902 ptr
::drop_in_place(drop_front
);
907 /// Returns a front-to-back iterator.
912 /// use std::collections::VecDeque;
914 /// let mut buf = VecDeque::new();
915 /// buf.push_back(5);
916 /// buf.push_back(3);
917 /// buf.push_back(4);
918 /// let b: &[_] = &[&5, &3, &4];
919 /// let c: Vec<&i32> = buf.iter().collect();
920 /// assert_eq!(&c[..], b);
922 #[stable(feature = "rust1", since = "1.0.0")]
923 pub fn iter(&self) -> Iter
<'_
, T
> {
924 Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() }
}
927 /// Returns a front-to-back iterator that returns mutable references.
932 /// use std::collections::VecDeque;
934 /// let mut buf = VecDeque::new();
935 /// buf.push_back(5);
936 /// buf.push_back(3);
937 /// buf.push_back(4);
938 /// for num in buf.iter_mut() {
941 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
942 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
944 #[stable(feature = "rust1", since = "1.0.0")]
945 pub fn iter_mut(&mut self) -> IterMut
<'_
, T
> {
946 // SAFETY: The internal `IterMut` safety invariant is established because the
947 // `ring` we create is a dereferencable slice for lifetime '_.
951 ring
: ptr
::slice_from_raw_parts_mut(self.ptr(), self.cap()),
952 phantom
: PhantomData
,
956 /// Returns a pair of slices which contain, in order, the contents of the
959 /// If [`make_contiguous`] was previously called, all elements of the
960 /// `VecDeque` will be in the first slice and the second slice will be empty.
962 /// [`make_contiguous`]: VecDeque::make_contiguous
967 /// use std::collections::VecDeque;
969 /// let mut vector = VecDeque::new();
971 /// vector.push_back(0);
972 /// vector.push_back(1);
973 /// vector.push_back(2);
975 /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
977 /// vector.push_front(10);
978 /// vector.push_front(9);
980 /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
983 #[stable(feature = "deque_extras_15", since = "1.5.0")]
984 pub fn as_slices(&self) -> (&[T
], &[T
]) {
986 let buf
= self.buffer_as_slice();
987 RingSlices
::ring_slices(buf
, self.head
, self.tail
)
991 /// Returns a pair of slices which contain, in order, the contents of the
994 /// If [`make_contiguous`] was previously called, all elements of the
995 /// `VecDeque` will be in the first slice and the second slice will be empty.
997 /// [`make_contiguous`]: VecDeque::make_contiguous
1002 /// use std::collections::VecDeque;
1004 /// let mut vector = VecDeque::new();
1006 /// vector.push_back(0);
1007 /// vector.push_back(1);
1009 /// vector.push_front(10);
1010 /// vector.push_front(9);
1012 /// vector.as_mut_slices().0[0] = 42;
1013 /// vector.as_mut_slices().1[0] = 24;
1014 /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
1017 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1018 pub fn as_mut_slices(&mut self) -> (&mut [T
], &mut [T
]) {
1020 let head
= self.head
;
1021 let tail
= self.tail
;
1022 let buf
= self.buffer_as_mut_slice();
1023 RingSlices
::ring_slices(buf
, head
, tail
)
1027 /// Returns the number of elements in the `VecDeque`.
1032 /// use std::collections::VecDeque;
1034 /// let mut v = VecDeque::new();
1035 /// assert_eq!(v.len(), 0);
1037 /// assert_eq!(v.len(), 1);
1039 #[doc(alias = "length")]
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 pub fn len(&self) -> usize {
1042 count(self.tail
, self.head
, self.cap())
1045 /// Returns `true` if the `VecDeque` is empty.
1050 /// use std::collections::VecDeque;
1052 /// let mut v = VecDeque::new();
1053 /// assert!(v.is_empty());
1054 /// v.push_front(1);
1055 /// assert!(!v.is_empty());
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 pub fn is_empty(&self) -> bool
{
1059 self.tail
== self.head
1062 fn range_tail_head
<R
>(&self, range
: R
) -> (usize, usize)
1064 R
: RangeBounds
<usize>,
1066 let Range { start, end }
= slice
::range(range
, ..self.len());
1067 let tail
= self.wrap_add(self.tail
, start
);
1068 let head
= self.wrap_add(self.tail
, end
);
1072 /// Creates an iterator that covers the specified range in the `VecDeque`.
1076 /// Panics if the starting point is greater than the end point or if
1077 /// the end point is greater than the length of the vector.
1082 /// use std::collections::VecDeque;
1084 /// let v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1085 /// let range = v.range(2..).copied().collect::<VecDeque<_>>();
1086 /// assert_eq!(range, [3]);
1088 /// // A full range covers all contents
1089 /// let all = v.range(..);
1090 /// assert_eq!(all.len(), 3);
1093 #[stable(feature = "deque_range", since = "1.51.0")]
1094 pub fn range
<R
>(&self, range
: R
) -> Iter
<'_
, T
>
1096 R
: RangeBounds
<usize>,
1098 let (tail
, head
) = self.range_tail_head(range
);
1102 // The shared reference we have in &self is maintained in the '_ of Iter.
1103 ring
: unsafe { self.buffer_as_slice() }
,
1107 /// Creates an iterator that covers the specified mutable range in the `VecDeque`.
1111 /// Panics if the starting point is greater than the end point or if
1112 /// the end point is greater than the length of the vector.
1117 /// use std::collections::VecDeque;
1119 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1120 /// for v in v.range_mut(2..) {
1123 /// assert_eq!(v, vec![1, 2, 6]);
1125 /// // A full range covers all contents
1126 /// for v in v.range_mut(..) {
1129 /// assert_eq!(v, vec![2, 4, 12]);
1132 #[stable(feature = "deque_range", since = "1.51.0")]
1133 pub fn range_mut
<R
>(&mut self, range
: R
) -> IterMut
<'_
, T
>
1135 R
: RangeBounds
<usize>,
1137 let (tail
, head
) = self.range_tail_head(range
);
1139 // SAFETY: The internal `IterMut` safety invariant is established because the
1140 // `ring` we create is a dereferencable slice for lifetime '_.
1144 ring
: ptr
::slice_from_raw_parts_mut(self.ptr(), self.cap()),
1145 phantom
: PhantomData
,
1149 /// Creates a draining iterator that removes the specified range in the
1150 /// `VecDeque` and yields the removed items.
1152 /// Note 1: The element range is removed even if the iterator is not
1153 /// consumed until the end.
1155 /// Note 2: It is unspecified how many elements are removed from the deque,
1156 /// if the `Drain` value is not dropped, but the borrow it holds expires
1157 /// (e.g., due to `mem::forget`).
1161 /// Panics if the starting point is greater than the end point or if
1162 /// the end point is greater than the length of the vector.
1167 /// use std::collections::VecDeque;
1169 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1170 /// let drained = v.drain(2..).collect::<VecDeque<_>>();
1171 /// assert_eq!(drained, [3]);
1172 /// assert_eq!(v, [1, 2]);
1174 /// // A full range clears all contents
1176 /// assert!(v.is_empty());
1179 #[stable(feature = "drain", since = "1.6.0")]
1180 pub fn drain
<R
>(&mut self, range
: R
) -> Drain
<'_
, T
>
1182 R
: RangeBounds
<usize>,
1186 // When the Drain is first created, the source deque is shortened to
1187 // make sure no uninitialized or moved-from elements are accessible at
1188 // all if the Drain's destructor never gets to run.
1190 // Drain will ptr::read out the values to remove.
1191 // When finished, the remaining data will be copied back to cover the hole,
1192 // and the head/tail values will be restored correctly.
1194 let (drain_tail
, drain_head
) = self.range_tail_head(range
);
1196 // The deque's elements are parted into three segments:
1197 // * self.tail -> drain_tail
1198 // * drain_tail -> drain_head
1199 // * drain_head -> self.head
1201 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1203 // We store drain_tail as self.head, and drain_head and self.head as
1204 // after_tail and after_head respectively on the Drain. This also
1205 // truncates the effective array such that if the Drain is leaked, we
1206 // have forgotten about the potentially moved values after the start of
1210 // [. . . o o x x o o . . .]
1212 let head
= self.head
;
1214 // "forget" about the values after the start of the drain until after
1215 // the drain is complete and the Drain destructor is run.
1216 self.head
= drain_tail
;
1219 deque
: NonNull
::from(&mut *self),
1220 after_tail
: drain_head
,
1225 // Crucially, we only create shared references from `self` here and read from
1226 // it. We do not write to `self` nor reborrow to a mutable reference.
1227 // Hence the raw pointer we created above, for `deque`, remains valid.
1228 ring
: unsafe { self.buffer_as_slice() }
,
1233 /// Clears the `VecDeque`, removing all values.
1238 /// use std::collections::VecDeque;
1240 /// let mut v = VecDeque::new();
1243 /// assert!(v.is_empty());
1245 #[stable(feature = "rust1", since = "1.0.0")]
1247 pub fn clear(&mut self) {
1251 /// Returns `true` if the `VecDeque` contains an element equal to the
1257 /// use std::collections::VecDeque;
1259 /// let mut vector: VecDeque<u32> = VecDeque::new();
1261 /// vector.push_back(0);
1262 /// vector.push_back(1);
1264 /// assert_eq!(vector.contains(&1), true);
1265 /// assert_eq!(vector.contains(&10), false);
1267 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1268 pub fn contains(&self, x
: &T
) -> bool
1272 let (a
, b
) = self.as_slices();
1273 a
.contains(x
) || b
.contains(x
)
1276 /// Provides a reference to the front element, or `None` if the `VecDeque` is
1282 /// use std::collections::VecDeque;
1284 /// let mut d = VecDeque::new();
1285 /// assert_eq!(d.front(), None);
1289 /// assert_eq!(d.front(), Some(&1));
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 pub fn front(&self) -> Option
<&T
> {
1296 /// Provides a mutable reference to the front element, or `None` if the
1297 /// `VecDeque` is empty.
1302 /// use std::collections::VecDeque;
1304 /// let mut d = VecDeque::new();
1305 /// assert_eq!(d.front_mut(), None);
1309 /// match d.front_mut() {
1310 /// Some(x) => *x = 9,
1313 /// assert_eq!(d.front(), Some(&9));
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 pub fn front_mut(&mut self) -> Option
<&mut T
> {
1320 /// Provides a reference to the back element, or `None` if the `VecDeque` is
1326 /// use std::collections::VecDeque;
1328 /// let mut d = VecDeque::new();
1329 /// assert_eq!(d.back(), None);
1333 /// assert_eq!(d.back(), Some(&2));
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 pub fn back(&self) -> Option
<&T
> {
1337 self.get(self.len().wrapping_sub(1))
1340 /// Provides a mutable reference to the back element, or `None` if the
1341 /// `VecDeque` is empty.
1346 /// use std::collections::VecDeque;
1348 /// let mut d = VecDeque::new();
1349 /// assert_eq!(d.back(), None);
1353 /// match d.back_mut() {
1354 /// Some(x) => *x = 9,
1357 /// assert_eq!(d.back(), Some(&9));
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 pub fn back_mut(&mut self) -> Option
<&mut T
> {
1361 self.get_mut(self.len().wrapping_sub(1))
1364 /// Removes the first element and returns it, or `None` if the `VecDeque` is
1370 /// use std::collections::VecDeque;
1372 /// let mut d = VecDeque::new();
1376 /// assert_eq!(d.pop_front(), Some(1));
1377 /// assert_eq!(d.pop_front(), Some(2));
1378 /// assert_eq!(d.pop_front(), None);
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 pub fn pop_front(&mut self) -> Option
<T
> {
1382 if self.is_empty() {
1385 let tail
= self.tail
;
1386 self.tail
= self.wrap_add(self.tail
, 1);
1387 unsafe { Some(self.buffer_read(tail)) }
1391 /// Removes the last element from the `VecDeque` and returns it, or `None` if
1397 /// use std::collections::VecDeque;
1399 /// let mut buf = VecDeque::new();
1400 /// assert_eq!(buf.pop_back(), None);
1401 /// buf.push_back(1);
1402 /// buf.push_back(3);
1403 /// assert_eq!(buf.pop_back(), Some(3));
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 pub fn pop_back(&mut self) -> Option
<T
> {
1407 if self.is_empty() {
1410 self.head
= self.wrap_sub(self.head
, 1);
1411 let head
= self.head
;
1412 unsafe { Some(self.buffer_read(head)) }
1416 /// Prepends an element to the `VecDeque`.
1421 /// use std::collections::VecDeque;
1423 /// let mut d = VecDeque::new();
1424 /// d.push_front(1);
1425 /// d.push_front(2);
1426 /// assert_eq!(d.front(), Some(&2));
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 pub fn push_front(&mut self, value
: T
) {
1434 self.tail
= self.wrap_sub(self.tail
, 1);
1435 let tail
= self.tail
;
1437 self.buffer_write(tail
, value
);
1441 /// Appends an element to the back of the `VecDeque`.
1446 /// use std::collections::VecDeque;
1448 /// let mut buf = VecDeque::new();
1449 /// buf.push_back(1);
1450 /// buf.push_back(3);
1451 /// assert_eq!(3, *buf.back().unwrap());
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 pub fn push_back(&mut self, value
: T
) {
1459 let head
= self.head
;
1460 self.head
= self.wrap_add(self.head
, 1);
1461 unsafe { self.buffer_write(head, value) }
1465 fn is_contiguous(&self) -> bool
{
1466 // FIXME: Should we consider `head == 0` to mean
1467 // that `self` is contiguous?
1468 self.tail
<= self.head
1471 /// Removes an element from anywhere in the `VecDeque` and returns it,
1472 /// replacing it with the first element.
1474 /// This does not preserve ordering, but is *O*(1).
1476 /// Returns `None` if `index` is out of bounds.
1478 /// Element at index 0 is the front of the queue.
1483 /// use std::collections::VecDeque;
1485 /// let mut buf = VecDeque::new();
1486 /// assert_eq!(buf.swap_remove_front(0), None);
1487 /// buf.push_back(1);
1488 /// buf.push_back(2);
1489 /// buf.push_back(3);
1490 /// assert_eq!(buf, [1, 2, 3]);
1492 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1493 /// assert_eq!(buf, [2, 1]);
1495 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1496 pub fn swap_remove_front(&mut self, index
: usize) -> Option
<T
> {
1497 let length
= self.len();
1498 if length
> 0 && index
< length
&& index
!= 0 {
1499 self.swap(index
, 0);
1500 } else if index
>= length
{
1506 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1509 /// This does not preserve ordering, but is *O*(1).
1511 /// Returns `None` if `index` is out of bounds.
1513 /// Element at index 0 is the front of the queue.
1518 /// use std::collections::VecDeque;
1520 /// let mut buf = VecDeque::new();
1521 /// assert_eq!(buf.swap_remove_back(0), None);
1522 /// buf.push_back(1);
1523 /// buf.push_back(2);
1524 /// buf.push_back(3);
1525 /// assert_eq!(buf, [1, 2, 3]);
1527 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1528 /// assert_eq!(buf, [3, 2]);
1530 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1531 pub fn swap_remove_back(&mut self, index
: usize) -> Option
<T
> {
1532 let length
= self.len();
1533 if length
> 0 && index
< length
- 1 {
1534 self.swap(index
, length
- 1);
1535 } else if index
>= length
{
1541 /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1542 /// greater than or equal to `index` towards the back.
1544 /// Element at index 0 is the front of the queue.
1548 /// Panics if `index` is greater than `VecDeque`'s length
1553 /// use std::collections::VecDeque;
1555 /// let mut vec_deque = VecDeque::new();
1556 /// vec_deque.push_back('a');
1557 /// vec_deque.push_back('b');
1558 /// vec_deque.push_back('c');
1559 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1561 /// vec_deque.insert(1, 'd');
1562 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1564 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1565 pub fn insert(&mut self, index
: usize, value
: T
) {
1566 assert
!(index
<= self.len(), "index out of bounds");
1571 // Move the least number of elements in the ring buffer and insert
1574 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1576 // There are three main cases:
1577 // Elements are contiguous
1578 // - special case when tail is 0
1579 // Elements are discontiguous and the insert is in the tail section
1580 // Elements are discontiguous and the insert is in the head section
1582 // For each of those there are two more cases:
1583 // Insert is closer to tail
1584 // Insert is closer to head
1586 // Key: H - self.head
1588 // o - Valid element
1589 // I - Insertion element
1590 // A - The element that should be after the insertion point
1591 // M - Indicates element was moved
1593 let idx
= self.wrap_add(self.tail
, index
);
1595 let distance_to_tail
= index
;
1596 let distance_to_head
= self.len() - index
;
1598 let contiguous
= self.is_contiguous();
1600 match (contiguous
, distance_to_tail
<= distance_to_head
, idx
>= self.tail
) {
1601 (true, true, _
) if index
== 0 => {
1606 // [A o o o o o o . . . . . . . . .]
1609 // [A o o o o o o o . . . . . I]
1612 self.tail
= self.wrap_sub(self.tail
, 1);
1614 (true, true, _
) => {
1616 // contiguous, insert closer to tail:
1619 // [. . . o o A o o o o . . . . . .]
1622 // [. . o o I A o o o o . . . . . .]
1625 // contiguous, insert closer to tail and tail is 0:
1629 // [o o A o o o o . . . . . . . . .]
1632 // [o I A o o o o o . . . . . . . o]
1635 let new_tail
= self.wrap_sub(self.tail
, 1);
1637 self.copy(new_tail
, self.tail
, 1);
1638 // Already moved the tail, so we only copy `index - 1` elements.
1639 self.copy(self.tail
, self.tail
+ 1, index
- 1);
1641 self.tail
= new_tail
;
1644 (true, false, _
) => {
1646 // contiguous, insert closer to head:
1649 // [. . . o o o o A o o . . . . . .]
1652 // [. . . o o o o I A o o . . . . .]
1655 self.copy(idx
+ 1, idx
, self.head
- idx
);
1656 self.head
= self.wrap_add(self.head
, 1);
1659 (false, true, true) => {
1661 // discontiguous, insert closer to tail, tail section:
1664 // [o o o o o o . . . . . o o A o o]
1667 // [o o o o o o . . . . o o I A o o]
1670 self.copy(self.tail
- 1, self.tail
, index
);
1674 (false, false, true) => {
1676 // discontiguous, insert closer to head, tail section:
1679 // [o o . . . . . . . o o o o o A o]
1682 // [o o o . . . . . . o o o o o I A]
1685 // copy elements up to new head
1686 self.copy(1, 0, self.head
);
1688 // copy last element into empty spot at bottom of buffer
1689 self.copy(0, self.cap() - 1, 1);
1691 // move elements from idx to end forward not including ^ element
1692 self.copy(idx
+ 1, idx
, self.cap() - 1 - idx
);
1697 (false, true, false) if idx
== 0 => {
1699 // discontiguous, insert is closer to tail, head section,
1700 // and is at index zero in the internal buffer:
1703 // [A o o o o o o o o o . . . o o o]
1706 // [A o o o o o o o o o . . o o o I]
1709 // copy elements up to new tail
1710 self.copy(self.tail
- 1, self.tail
, self.cap() - self.tail
);
1712 // copy last element into empty spot at bottom of buffer
1713 self.copy(self.cap() - 1, 0, 1);
1718 (false, true, false) => {
1720 // discontiguous, insert closer to tail, head section:
1723 // [o o o A o o o o o o . . . o o o]
1726 // [o o I A o o o o o o . . o o o o]
1729 // copy elements up to new tail
1730 self.copy(self.tail
- 1, self.tail
, self.cap() - self.tail
);
1732 // copy last element into empty spot at bottom of buffer
1733 self.copy(self.cap() - 1, 0, 1);
1735 // move elements from idx-1 to end forward not including ^ element
1736 self.copy(0, 1, idx
- 1);
1741 (false, false, false) => {
1743 // discontiguous, insert closer to head, head section:
1746 // [o o o o A o o . . . . . . o o o]
1749 // [o o o o I A o o . . . . . o o o]
1752 self.copy(idx
+ 1, idx
, self.head
- idx
);
1758 // tail might've been changed so we need to recalculate
1759 let new_idx
= self.wrap_add(self.tail
, index
);
1761 self.buffer_write(new_idx
, value
);
1765 /// Removes and returns the element at `index` from the `VecDeque`.
1766 /// Whichever end is closer to the removal point will be moved to make
1767 /// room, and all the affected elements will be moved to new positions.
1768 /// Returns `None` if `index` is out of bounds.
1770 /// Element at index 0 is the front of the queue.
1775 /// use std::collections::VecDeque;
1777 /// let mut buf = VecDeque::new();
1778 /// buf.push_back(1);
1779 /// buf.push_back(2);
1780 /// buf.push_back(3);
1781 /// assert_eq!(buf, [1, 2, 3]);
1783 /// assert_eq!(buf.remove(1), Some(2));
1784 /// assert_eq!(buf, [1, 3]);
1786 #[stable(feature = "rust1", since = "1.0.0")]
1787 pub fn remove(&mut self, index
: usize) -> Option
<T
> {
1788 if self.is_empty() || self.len() <= index
{
1792 // There are three main cases:
1793 // Elements are contiguous
1794 // Elements are discontiguous and the removal is in the tail section
1795 // Elements are discontiguous and the removal is in the head section
1796 // - special case when elements are technically contiguous,
1797 // but self.head = 0
1799 // For each of those there are two more cases:
1800 // Insert is closer to tail
1801 // Insert is closer to head
1803 // Key: H - self.head
1805 // o - Valid element
1806 // x - Element marked for removal
1807 // R - Indicates element that is being removed
1808 // M - Indicates element was moved
1810 let idx
= self.wrap_add(self.tail
, index
);
1812 let elem
= unsafe { Some(self.buffer_read(idx)) }
;
1814 let distance_to_tail
= index
;
1815 let distance_to_head
= self.len() - index
;
1817 let contiguous
= self.is_contiguous();
1819 match (contiguous
, distance_to_tail
<= distance_to_head
, idx
>= self.tail
) {
1820 (true, true, _
) => {
1822 // contiguous, remove closer to tail:
1825 // [. . . o o x o o o o . . . . . .]
1828 // [. . . . o o o o o o . . . . . .]
1831 self.copy(self.tail
+ 1, self.tail
, index
);
1835 (true, false, _
) => {
1837 // contiguous, remove closer to head:
1840 // [. . . o o o o x o o . . . . . .]
1843 // [. . . o o o o o o . . . . . . .]
1846 self.copy(idx
, idx
+ 1, self.head
- idx
- 1);
1850 (false, true, true) => {
1852 // discontiguous, remove closer to tail, tail section:
1855 // [o o o o o o . . . . . o o x o o]
1858 // [o o o o o o . . . . . . o o o o]
1861 self.copy(self.tail
+ 1, self.tail
, index
);
1862 self.tail
= self.wrap_add(self.tail
, 1);
1865 (false, false, false) => {
1867 // discontiguous, remove closer to head, head section:
1870 // [o o o o x o o . . . . . . o o o]
1873 // [o o o o o o . . . . . . . o o o]
1876 self.copy(idx
, idx
+ 1, self.head
- idx
- 1);
1880 (false, false, true) => {
1882 // discontiguous, remove closer to head, tail section:
1885 // [o o o . . . . . . o o o o o x o]
1888 // [o o . . . . . . . o o o o o o o]
1891 // or quasi-discontiguous, remove next to head, tail section:
1894 // [. . . . . . . . . o o o o o x o]
1897 // [. . . . . . . . . o o o o o o .]
1900 // draw in elements in the tail section
1901 self.copy(idx
, idx
+ 1, self.cap() - idx
- 1);
1903 // Prevents underflow.
1905 // copy first element into empty spot
1906 self.copy(self.cap() - 1, 0, 1);
1908 // move elements in the head section backwards
1909 self.copy(0, 1, self.head
- 1);
1912 self.head
= self.wrap_sub(self.head
, 1);
1915 (false, true, false) => {
1917 // discontiguous, remove closer to tail, head section:
1920 // [o o x o o o o o o o . . . o o o]
1923 // [o o o o o o o o o o . . . . o o]
1926 // draw in elements up to idx
1927 self.copy(1, 0, idx
);
1929 // copy last element into empty spot
1930 self.copy(0, self.cap() - 1, 1);
1932 // move elements from tail to end forward, excluding the last one
1933 self.copy(self.tail
+ 1, self.tail
, self.cap() - self.tail
- 1);
1935 self.tail
= self.wrap_add(self.tail
, 1);
1943 /// Splits the `VecDeque` into two at the given index.
1945 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1946 /// and the returned `VecDeque` contains elements `[at, len)`.
1948 /// Note that the capacity of `self` does not change.
1950 /// Element at index 0 is the front of the queue.
1954 /// Panics if `at > len`.
1959 /// use std::collections::VecDeque;
1961 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1962 /// let buf2 = buf.split_off(1);
1963 /// assert_eq!(buf, [1]);
1964 /// assert_eq!(buf2, [2, 3]);
1967 #[must_use = "use `.truncate()` if you don't need the other half"]
1968 #[stable(feature = "split_off", since = "1.4.0")]
1969 pub fn split_off(&mut self, at
: usize) -> Self {
1970 let len
= self.len();
1971 assert
!(at
<= len
, "`at` out of bounds");
1973 let other_len
= len
- at
;
1974 let mut other
= VecDeque
::with_capacity(other_len
);
1977 let (first_half
, second_half
) = self.as_slices();
1979 let first_len
= first_half
.len();
1980 let second_len
= second_half
.len();
1982 // `at` lies in the first half.
1983 let amount_in_first
= first_len
- at
;
1985 ptr
::copy_nonoverlapping(first_half
.as_ptr().add(at
), other
.ptr(), amount_in_first
);
1987 // just take all of the second half.
1988 ptr
::copy_nonoverlapping(
1989 second_half
.as_ptr(),
1990 other
.ptr().add(amount_in_first
),
1994 // `at` lies in the second half, need to factor in the elements we skipped
1995 // in the first half.
1996 let offset
= at
- first_len
;
1997 let amount_in_second
= second_len
- offset
;
1998 ptr
::copy_nonoverlapping(
1999 second_half
.as_ptr().add(offset
),
2006 // Cleanup where the ends of the buffers are
2007 self.head
= self.wrap_sub(self.head
, other_len
);
2008 other
.head
= other
.wrap_index(other_len
);
2013 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2017 /// Panics if the new number of elements in self overflows a `usize`.
2022 /// use std::collections::VecDeque;
2024 /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
2025 /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
2026 /// buf.append(&mut buf2);
2027 /// assert_eq!(buf, [1, 2, 3, 4]);
2028 /// assert_eq!(buf2, []);
2031 #[stable(feature = "append", since = "1.4.0")]
2032 pub fn append(&mut self, other
: &mut Self) {
2034 self.extend(other
.drain(..));
2037 /// Retains only the elements specified by the predicate.
2039 /// In other words, remove all elements `e` such that `f(&e)` returns false.
2040 /// This method operates in place, visiting each element exactly once in the
2041 /// original order, and preserves the order of the retained elements.
2046 /// use std::collections::VecDeque;
2048 /// let mut buf = VecDeque::new();
2049 /// buf.extend(1..5);
2050 /// buf.retain(|&x| x % 2 == 0);
2051 /// assert_eq!(buf, [2, 4]);
2054 /// The exact order may be useful for tracking external state, like an index.
2057 /// use std::collections::VecDeque;
2059 /// let mut buf = VecDeque::new();
2060 /// buf.extend(1..6);
2062 /// let keep = [false, true, true, false, true];
2064 /// buf.retain(|_| (keep[i], i += 1).0);
2065 /// assert_eq!(buf, [2, 3, 5]);
2067 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2068 pub fn retain
<F
>(&mut self, mut f
: F
)
2070 F
: FnMut(&T
) -> bool
,
2072 let len
= self.len();
2078 self.swap(i
- del
, i
);
2082 self.truncate(len
- del
);
2086 // This may panic or abort
2088 fn grow(&mut self) {
2090 let old_cap
= self.cap();
2091 // Double the buffer size.
2092 self.buf
.reserve_exact(old_cap
, old_cap
);
2093 assert
!(self.cap() == old_cap
* 2);
2095 self.handle_capacity_increase(old_cap
);
2097 debug_assert
!(!self.is_full());
2101 /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
2102 /// either by removing excess elements from the back or by appending
2103 /// elements generated by calling `generator` to the back.
2108 /// use std::collections::VecDeque;
2110 /// let mut buf = VecDeque::new();
2111 /// buf.push_back(5);
2112 /// buf.push_back(10);
2113 /// buf.push_back(15);
2114 /// assert_eq!(buf, [5, 10, 15]);
2116 /// buf.resize_with(5, Default::default);
2117 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2119 /// buf.resize_with(2, || unreachable!());
2120 /// assert_eq!(buf, [5, 10]);
2122 /// let mut state = 100;
2123 /// buf.resize_with(5, || { state += 1; state });
2124 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2126 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2127 pub fn resize_with(&mut self, new_len
: usize, generator
: impl FnMut() -> T
) {
2128 let len
= self.len();
2131 self.extend(repeat_with(generator
).take(new_len
- len
))
2133 self.truncate(new_len
);
2137 /// Rearranges the internal storage of this deque so it is one contiguous
2138 /// slice, which is then returned.
2140 /// This method does not allocate and does not change the order of the
2141 /// inserted elements. As it returns a mutable slice, this can be used to
2144 /// Once the internal storage is contiguous, the [`as_slices`] and
2145 /// [`as_mut_slices`] methods will return the entire contents of the
2146 /// `VecDeque` in a single slice.
2148 /// [`as_slices`]: VecDeque::as_slices
2149 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2153 /// Sorting the content of a deque.
2156 /// use std::collections::VecDeque;
2158 /// let mut buf = VecDeque::with_capacity(15);
2160 /// buf.push_back(2);
2161 /// buf.push_back(1);
2162 /// buf.push_front(3);
2164 /// // sorting the deque
2165 /// buf.make_contiguous().sort();
2166 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2168 /// // sorting it in reverse order
2169 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2170 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2173 /// Getting immutable access to the contiguous slice.
2176 /// use std::collections::VecDeque;
2178 /// let mut buf = VecDeque::new();
2180 /// buf.push_back(2);
2181 /// buf.push_back(1);
2182 /// buf.push_front(3);
2184 /// buf.make_contiguous();
2185 /// if let (slice, &[]) = buf.as_slices() {
2186 /// // we can now be sure that `slice` contains all elements of the deque,
2187 /// // while still having immutable access to `buf`.
2188 /// assert_eq!(buf.len(), slice.len());
2189 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2192 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2193 pub fn make_contiguous(&mut self) -> &mut [T
] {
2194 if self.is_contiguous() {
2195 let tail
= self.tail
;
2196 let head
= self.head
;
2197 return unsafe { RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0 }
;
2200 let buf
= self.buf
.ptr();
2201 let cap
= self.cap();
2202 let len
= self.len();
2204 let free
= self.tail
- self.head
;
2205 let tail_len
= cap
- self.tail
;
2207 if free
>= tail_len
{
2208 // there is enough free space to copy the tail in one go,
2209 // this means that we first shift the head backwards, and then
2210 // copy the tail to the correct position.
2212 // from: DEFGH....ABC
2215 ptr
::copy(buf
, buf
.add(tail_len
), self.head
);
2217 ptr
::copy_nonoverlapping(buf
.add(self.tail
), buf
, tail_len
);
2223 } else if free
> self.head
{
2224 // FIXME: We currently do not consider ....ABCDEFGH
2225 // to be contiguous because `head` would be `0` in this
2226 // case. While we probably want to change this it
2227 // isn't trivial as a few places expect `is_contiguous`
2228 // to mean that we can just slice using `buf[tail..head]`.
2230 // there is enough free space to copy the head in one go,
2231 // this means that we first shift the tail forwards, and then
2232 // copy the head to the correct position.
2234 // from: FGH....ABCDE
2237 ptr
::copy(buf
.add(self.tail
), buf
.add(self.head
), tail_len
);
2239 ptr
::copy_nonoverlapping(buf
, buf
.add(self.head
+ tail_len
), self.head
);
2242 self.tail
= self.head
;
2243 self.head
= self.wrap_add(self.tail
, len
);
2246 // free is smaller than both head and tail,
2247 // this means we have to slowly "swap" the tail and the head.
2249 // from: EFGHI...ABCD or HIJK.ABCDEFG
2250 // to: ABCDEFGHI... or ABCDEFGHIJK.
2251 let mut left_edge
: usize = 0;
2252 let mut right_edge
: usize = self.tail
;
2254 // The general problem looks like this
2255 // GHIJKLM...ABCDEF - before any swaps
2256 // ABCDEFM...GHIJKL - after 1 pass of swaps
2257 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2258 // - then restart the algorithm with a new (smaller) store
2259 // Sometimes the temp store is reached when the right edge is at the end
2260 // of the buffer - this means we've hit the right order with fewer swaps!
2263 // ABCDEF.. - after four only swaps we've finished
2264 while left_edge
< len
&& right_edge
!= cap
{
2265 let mut right_offset
= 0;
2266 for i
in left_edge
..right_edge
{
2267 right_offset
= (i
- left_edge
) % (cap
- right_edge
);
2268 let src
: isize = (right_edge
+ right_offset
) as isize;
2269 ptr
::swap(buf
.add(i
), buf
.offset(src
));
2271 let n_ops
= right_edge
- left_edge
;
2273 right_edge
+= right_offset
+ 1;
2281 let tail
= self.tail
;
2282 let head
= self.head
;
2283 unsafe { RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0 }
2286 /// Rotates the double-ended queue `mid` places to the left.
2289 /// - Rotates item `mid` into the first position.
2290 /// - Pops the first `mid` items and pushes them to the end.
2291 /// - Rotates `len() - mid` places to the right.
2295 /// If `mid` is greater than `len()`. Note that `mid == len()`
2296 /// does _not_ panic and is a no-op rotation.
2300 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2305 /// use std::collections::VecDeque;
2307 /// let mut buf: VecDeque<_> = (0..10).collect();
2309 /// buf.rotate_left(3);
2310 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2312 /// for i in 1..10 {
2313 /// assert_eq!(i * 3 % 10, buf[0]);
2314 /// buf.rotate_left(3);
2316 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2318 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2319 pub fn rotate_left(&mut self, mid
: usize) {
2320 assert
!(mid
<= self.len());
2321 let k
= self.len() - mid
;
2323 unsafe { self.rotate_left_inner(mid) }
2325 unsafe { self.rotate_right_inner(k) }
2329 /// Rotates the double-ended queue `k` places to the right.
2332 /// - Rotates the first item into position `k`.
2333 /// - Pops the last `k` items and pushes them to the front.
2334 /// - Rotates `len() - k` places to the left.
2338 /// If `k` is greater than `len()`. Note that `k == len()`
2339 /// does _not_ panic and is a no-op rotation.
2343 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2348 /// use std::collections::VecDeque;
2350 /// let mut buf: VecDeque<_> = (0..10).collect();
2352 /// buf.rotate_right(3);
2353 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2355 /// for i in 1..10 {
2356 /// assert_eq!(0, buf[i * 3 % 10]);
2357 /// buf.rotate_right(3);
2359 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2361 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2362 pub fn rotate_right(&mut self, k
: usize) {
2363 assert
!(k
<= self.len());
2364 let mid
= self.len() - k
;
2366 unsafe { self.rotate_right_inner(k) }
2368 unsafe { self.rotate_left_inner(mid) }
2372 // SAFETY: the following two methods require that the rotation amount
2373 // be less than half the length of the deque.
2375 // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2376 // but than `min` is never more than half the capacity, regardless of x,
2377 // so it's sound to call here because we're calling with something
2378 // less than half the length, which is never above half the capacity.
2380 unsafe fn rotate_left_inner(&mut self, mid
: usize) {
2381 debug_assert
!(mid
* 2 <= self.len());
2383 self.wrap_copy(self.head
, self.tail
, mid
);
2385 self.head
= self.wrap_add(self.head
, mid
);
2386 self.tail
= self.wrap_add(self.tail
, mid
);
2389 unsafe fn rotate_right_inner(&mut self, k
: usize) {
2390 debug_assert
!(k
* 2 <= self.len());
2391 self.head
= self.wrap_sub(self.head
, k
);
2392 self.tail
= self.wrap_sub(self.tail
, k
);
2394 self.wrap_copy(self.tail
, self.head
, k
);
2398 /// Binary searches this sorted `VecDeque` for a given element.
2400 /// If the value is found then [`Result::Ok`] is returned, containing the
2401 /// index of the matching element. If there are multiple matches, then any
2402 /// one of the matches could be returned. If the value is not found then
2403 /// [`Result::Err`] is returned, containing the index where a matching
2404 /// element could be inserted while maintaining sorted order.
2408 /// Looks up a series of four elements. The first is found, with a
2409 /// uniquely determined position; the second and third are not
2410 /// found; the fourth could match any position in `[1, 4]`.
2413 /// #![feature(vecdeque_binary_search)]
2414 /// use std::collections::VecDeque;
2416 /// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2418 /// assert_eq!(deque.binary_search(&13), Ok(9));
2419 /// assert_eq!(deque.binary_search(&4), Err(7));
2420 /// assert_eq!(deque.binary_search(&100), Err(13));
2421 /// let r = deque.binary_search(&1);
2422 /// assert!(matches!(r, Ok(1..=4)));
2425 /// If you want to insert an item to a sorted `VecDeque`, while maintaining
2429 /// #![feature(vecdeque_binary_search)]
2430 /// use std::collections::VecDeque;
2432 /// let mut deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2434 /// let idx = deque.binary_search(&num).unwrap_or_else(|x| x);
2435 /// deque.insert(idx, num);
2436 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2438 #[unstable(feature = "vecdeque_binary_search", issue = "78021")]
2440 pub fn binary_search(&self, x
: &T
) -> Result
<usize, usize>
2444 self.binary_search_by(|e
| e
.cmp(x
))
2447 /// Binary searches this sorted `VecDeque` with a comparator function.
2449 /// The comparator function should implement an order consistent
2450 /// with the sort order of the underlying `VecDeque`, returning an
2451 /// order code that indicates whether its argument is `Less`,
2452 /// `Equal` or `Greater` than the desired target.
2454 /// If the value is found then [`Result::Ok`] is returned, containing the
2455 /// index of the matching element. If there are multiple matches, then any
2456 /// one of the matches could be returned. If the value is not found then
2457 /// [`Result::Err`] is returned, containing the index where a matching
2458 /// element could be inserted while maintaining sorted order.
2462 /// Looks up a series of four elements. The first is found, with a
2463 /// uniquely determined position; the second and third are not
2464 /// found; the fourth could match any position in `[1, 4]`.
2467 /// #![feature(vecdeque_binary_search)]
2468 /// use std::collections::VecDeque;
2470 /// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2472 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2473 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2474 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2475 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2476 /// assert!(matches!(r, Ok(1..=4)));
2478 #[unstable(feature = "vecdeque_binary_search", issue = "78021")]
2479 pub fn binary_search_by
<'a
, F
>(&'a
self, mut f
: F
) -> Result
<usize, usize>
2481 F
: FnMut(&'a T
) -> Ordering
,
2483 let (front
, back
) = self.as_slices();
2485 if let Some(Ordering
::Less
| Ordering
::Equal
) = back
.first().map(|elem
| f(elem
)) {
2486 back
.binary_search_by(f
).map(|idx
| idx
+ front
.len()).map_err(|idx
| idx
+ front
.len())
2488 front
.binary_search_by(f
)
2492 /// Binary searches this sorted `VecDeque` with a key extraction function.
2494 /// Assumes that the `VecDeque` is sorted by the key, for instance with
2495 /// [`make_contiguous().sort_by_key()`](#method.make_contiguous) using the same
2496 /// key extraction function.
2498 /// If the value is found then [`Result::Ok`] is returned, containing the
2499 /// index of the matching element. If there are multiple matches, then any
2500 /// one of the matches could be returned. If the value is not found then
2501 /// [`Result::Err`] is returned, containing the index where a matching
2502 /// element could be inserted while maintaining sorted order.
2506 /// Looks up a series of four elements in a slice of pairs sorted by
2507 /// their second elements. The first is found, with a uniquely
2508 /// determined position; the second and third are not found; the
2509 /// fourth could match any position in `[1, 4]`.
2512 /// #![feature(vecdeque_binary_search)]
2513 /// use std::collections::VecDeque;
2515 /// let deque: VecDeque<_> = vec![(0, 0), (2, 1), (4, 1), (5, 1),
2516 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2517 /// (1, 21), (2, 34), (4, 55)].into();
2519 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2520 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2521 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2522 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2523 /// assert!(matches!(r, Ok(1..=4)));
2525 #[unstable(feature = "vecdeque_binary_search", issue = "78021")]
2527 pub fn binary_search_by_key
<'a
, B
, F
>(&'a
self, b
: &B
, mut f
: F
) -> Result
<usize, usize>
2529 F
: FnMut(&'a T
) -> B
,
2532 self.binary_search_by(|k
| f(k
).cmp(b
))
2536 impl<T
: Clone
> VecDeque
<T
> {
2537 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
2538 /// either by removing excess elements from the back or by appending clones of `value`
2544 /// use std::collections::VecDeque;
2546 /// let mut buf = VecDeque::new();
2547 /// buf.push_back(5);
2548 /// buf.push_back(10);
2549 /// buf.push_back(15);
2550 /// assert_eq!(buf, [5, 10, 15]);
2552 /// buf.resize(2, 0);
2553 /// assert_eq!(buf, [5, 10]);
2555 /// buf.resize(5, 20);
2556 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2558 #[stable(feature = "deque_extras", since = "1.16.0")]
2559 pub fn resize(&mut self, new_len
: usize, value
: T
) {
2560 self.resize_with(new_len
, || value
.clone());
2564 /// Returns the index in the underlying buffer for a given logical element index.
2566 fn wrap_index(index
: usize, size
: usize) -> usize {
2567 // size is always a power of 2
2568 debug_assert
!(size
.is_power_of_two());
2572 /// Calculate the number of elements left to be read in the buffer
2574 fn count(tail
: usize, head
: usize, size
: usize) -> usize {
2575 // size is always a power of 2
2576 (head
.wrapping_sub(tail
)) & (size
- 1)
2579 #[stable(feature = "rust1", since = "1.0.0")]
2580 impl<A
: PartialEq
> PartialEq
for VecDeque
<A
> {
2581 fn eq(&self, other
: &VecDeque
<A
>) -> bool
{
2582 if self.len() != other
.len() {
2585 let (sa
, sb
) = self.as_slices();
2586 let (oa
, ob
) = other
.as_slices();
2587 if sa
.len() == oa
.len() {
2588 sa
== oa
&& sb
== ob
2589 } else if sa
.len() < oa
.len() {
2590 // Always divisible in three sections, for example:
2591 // self: [a b c|d e f]
2592 // other: [0 1 2 3|4 5]
2593 // front = 3, mid = 1,
2594 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2595 let front
= sa
.len();
2596 let mid
= oa
.len() - front
;
2598 let (oa_front
, oa_mid
) = oa
.split_at(front
);
2599 let (sb_mid
, sb_back
) = sb
.split_at(mid
);
2600 debug_assert_eq
!(sa
.len(), oa_front
.len());
2601 debug_assert_eq
!(sb_mid
.len(), oa_mid
.len());
2602 debug_assert_eq
!(sb_back
.len(), ob
.len());
2603 sa
== oa_front
&& sb_mid
== oa_mid
&& sb_back
== ob
2605 let front
= oa
.len();
2606 let mid
= sa
.len() - front
;
2608 let (sa_front
, sa_mid
) = sa
.split_at(front
);
2609 let (ob_mid
, ob_back
) = ob
.split_at(mid
);
2610 debug_assert_eq
!(sa_front
.len(), oa
.len());
2611 debug_assert_eq
!(sa_mid
.len(), ob_mid
.len());
2612 debug_assert_eq
!(sb
.len(), ob_back
.len());
2613 sa_front
== oa
&& sa_mid
== ob_mid
&& sb
== ob_back
2618 #[stable(feature = "rust1", since = "1.0.0")]
2619 impl<A
: Eq
> Eq
for VecDeque
<A
> {}
2621 __impl_slice_eq1
! { [] VecDeque<A>, Vec<B>, }
2622 __impl_slice_eq1
! { [] VecDeque<A>, &[B], }
2623 __impl_slice_eq1
! { [] VecDeque<A>, &mut [B], }
2624 __impl_slice_eq1
! { [const N: usize] VecDeque<A>, [B; N], }
2625 __impl_slice_eq1
! { [const N: usize] VecDeque<A>, &[B; N], }
2626 __impl_slice_eq1
! { [const N: usize] VecDeque<A>, &mut [B; N], }
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 impl<A
: PartialOrd
> PartialOrd
for VecDeque
<A
> {
2630 fn partial_cmp(&self, other
: &VecDeque
<A
>) -> Option
<Ordering
> {
2631 self.iter().partial_cmp(other
.iter())
2635 #[stable(feature = "rust1", since = "1.0.0")]
2636 impl<A
: Ord
> Ord
for VecDeque
<A
> {
2638 fn cmp(&self, other
: &VecDeque
<A
>) -> Ordering
{
2639 self.iter().cmp(other
.iter())
2643 #[stable(feature = "rust1", since = "1.0.0")]
2644 impl<A
: Hash
> Hash
for VecDeque
<A
> {
2645 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
2646 self.len().hash(state
);
2647 // It's not possible to use Hash::hash_slice on slices
2648 // returned by as_slices method as their length can vary
2649 // in otherwise identical deques.
2651 // Hasher only guarantees equivalence for the exact same
2652 // set of calls to its methods.
2653 self.iter().for_each(|elem
| elem
.hash(state
));
2657 #[stable(feature = "rust1", since = "1.0.0")]
2658 impl<A
> Index
<usize> for VecDeque
<A
> {
2662 fn index(&self, index
: usize) -> &A
{
2663 self.get(index
).expect("Out of bounds access")
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 impl<A
> IndexMut
<usize> for VecDeque
<A
> {
2670 fn index_mut(&mut self, index
: usize) -> &mut A
{
2671 self.get_mut(index
).expect("Out of bounds access")
2675 #[stable(feature = "rust1", since = "1.0.0")]
2676 impl<A
> FromIterator
<A
> for VecDeque
<A
> {
2677 fn from_iter
<T
: IntoIterator
<Item
= A
>>(iter
: T
) -> VecDeque
<A
> {
2678 let iterator
= iter
.into_iter();
2679 let (lower
, _
) = iterator
.size_hint();
2680 let mut deq
= VecDeque
::with_capacity(lower
);
2681 deq
.extend(iterator
);
2686 #[stable(feature = "rust1", since = "1.0.0")]
2687 impl<T
> IntoIterator
for VecDeque
<T
> {
2689 type IntoIter
= IntoIter
<T
>;
2691 /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2693 fn into_iter(self) -> IntoIter
<T
> {
2694 IntoIter { inner: self }
2698 #[stable(feature = "rust1", since = "1.0.0")]
2699 impl<'a
, T
> IntoIterator
for &'a VecDeque
<T
> {
2701 type IntoIter
= Iter
<'a
, T
>;
2703 fn into_iter(self) -> Iter
<'a
, T
> {
2708 #[stable(feature = "rust1", since = "1.0.0")]
2709 impl<'a
, T
> IntoIterator
for &'a
mut VecDeque
<T
> {
2710 type Item
= &'a
mut T
;
2711 type IntoIter
= IterMut
<'a
, T
>;
2713 fn into_iter(self) -> IterMut
<'a
, T
> {
2718 #[stable(feature = "rust1", since = "1.0.0")]
2719 impl<A
> Extend
<A
> for VecDeque
<A
> {
2720 fn extend
<T
: IntoIterator
<Item
= A
>>(&mut self, iter
: T
) {
2721 // This function should be the moral equivalent of:
2723 // for item in iter.into_iter() {
2724 // self.push_back(item);
2726 let mut iter
= iter
.into_iter();
2727 while let Some(element
) = iter
.next() {
2728 if self.len() == self.capacity() {
2729 let (lower
, _
) = iter
.size_hint();
2730 self.reserve(lower
.saturating_add(1));
2733 let head
= self.head
;
2734 self.head
= self.wrap_add(self.head
, 1);
2736 self.buffer_write(head
, element
);
2742 fn extend_one(&mut self, elem
: A
) {
2743 self.push_back(elem
);
2747 fn extend_reserve(&mut self, additional
: usize) {
2748 self.reserve(additional
);
2752 #[stable(feature = "extend_ref", since = "1.2.0")]
2753 impl<'a
, T
: 'a
+ Copy
> Extend
<&'a T
> for VecDeque
<T
> {
2754 fn extend
<I
: IntoIterator
<Item
= &'a T
>>(&mut self, iter
: I
) {
2755 self.extend(iter
.into_iter().cloned());
2759 fn extend_one(&mut self, &elem
: &T
) {
2760 self.push_back(elem
);
2764 fn extend_reserve(&mut self, additional
: usize) {
2765 self.reserve(additional
);
2769 #[stable(feature = "rust1", since = "1.0.0")]
2770 impl<T
: fmt
::Debug
> fmt
::Debug
for VecDeque
<T
> {
2771 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2772 f
.debug_list().entries(self).finish()
2776 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2777 impl<T
> From
<Vec
<T
>> for VecDeque
<T
> {
2778 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2780 /// [`Vec<T>`]: crate::vec::Vec
2781 /// [`VecDeque<T>`]: crate::collections::VecDeque
2783 /// This avoids reallocating where possible, but the conditions for that are
2784 /// strict, and subject to change, and so shouldn't be relied upon unless the
2785 /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
2786 fn from(mut other
: Vec
<T
>) -> Self {
2787 let len
= other
.len();
2788 if mem
::size_of
::<T
>() == 0 {
2789 // There's no actual allocation for ZSTs to worry about capacity,
2790 // but `VecDeque` can't handle as much length as `Vec`.
2791 assert
!(len
< MAXIMUM_ZST_CAPACITY
, "capacity overflow");
2793 // We need to resize if the capacity is not a power of two, too small or
2794 // doesn't have at least one free space. We do this while it's still in
2795 // the `Vec` so the items will drop on panic.
2796 let min_cap
= cmp
::max(MINIMUM_CAPACITY
, len
) + 1;
2797 let cap
= cmp
::max(min_cap
, other
.capacity()).next_power_of_two();
2798 if other
.capacity() != cap
{
2799 other
.reserve_exact(cap
- len
);
2804 let (other_buf
, len
, capacity
) = other
.into_raw_parts();
2805 let buf
= RawVec
::from_raw_parts(other_buf
, capacity
);
2806 VecDeque { tail: 0, head: len, buf }
2811 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2812 impl<T
> From
<VecDeque
<T
>> for Vec
<T
> {
2813 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2815 /// [`Vec<T>`]: crate::vec::Vec
2816 /// [`VecDeque<T>`]: crate::collections::VecDeque
2818 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
2819 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2824 /// use std::collections::VecDeque;
2826 /// // This one is *O*(1).
2827 /// let deque: VecDeque<_> = (1..5).collect();
2828 /// let ptr = deque.as_slices().0.as_ptr();
2829 /// let vec = Vec::from(deque);
2830 /// assert_eq!(vec, [1, 2, 3, 4]);
2831 /// assert_eq!(vec.as_ptr(), ptr);
2833 /// // This one needs data rearranging.
2834 /// let mut deque: VecDeque<_> = (1..5).collect();
2835 /// deque.push_front(9);
2836 /// deque.push_front(8);
2837 /// let ptr = deque.as_slices().1.as_ptr();
2838 /// let vec = Vec::from(deque);
2839 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2840 /// assert_eq!(vec.as_ptr(), ptr);
2842 fn from(mut other
: VecDeque
<T
>) -> Self {
2843 other
.make_contiguous();
2846 let other
= ManuallyDrop
::new(other
);
2847 let buf
= other
.buf
.ptr();
2848 let len
= other
.len();
2849 let cap
= other
.cap();
2851 if other
.tail
!= 0 {
2852 ptr
::copy(buf
.add(other
.tail
), buf
, len
);
2854 Vec
::from_raw_parts(buf
, len
, cap
)