alloc/collections/vec_deque/mod.rs
1//! A double-ended queue (deque) implemented with a growable ring buffer.
2//!
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.
7
8#![stable(feature = "rust1", since = "1.0.0")]
9
10use core::cmp::{self, Ordering};
11use core::hash::{Hash, Hasher};
12use core::iter::{ByRefSized, repeat_n, repeat_with};
13// This is used in a bunch of intra-doc links.
14// FIXME: For some reason, `#[cfg(doc)]` wasn't sufficient, resulting in
15// failures in linkchecker even though rustdoc built the docs just fine.
16#[allow(unused_imports)]
17use core::mem;
18use core::mem::{ManuallyDrop, SizedTypeProperties};
19use core::ops::{Index, IndexMut, Range, RangeBounds};
20use core::{fmt, ptr, slice};
21
22use crate::alloc::{Allocator, Global};
23use crate::collections::{TryReserveError, TryReserveErrorKind};
24use crate::raw_vec::RawVec;
25use crate::vec::Vec;
26
27#[macro_use]
28mod macros;
29
30#[stable(feature = "drain", since = "1.6.0")]
31pub use self::drain::Drain;
32
33mod drain;
34
35#[stable(feature = "rust1", since = "1.0.0")]
36pub use self::iter_mut::IterMut;
37
38mod iter_mut;
39
40#[stable(feature = "rust1", since = "1.0.0")]
41pub use self::into_iter::IntoIter;
42
43mod into_iter;
44
45#[stable(feature = "rust1", since = "1.0.0")]
46pub use self::iter::Iter;
47
48mod iter;
49
50use self::spec_extend::SpecExtend;
51
52mod spec_extend;
53
54use self::spec_from_iter::SpecFromIter;
55
56mod spec_from_iter;
57
58#[cfg(test)]
59mod tests;
60
61/// A double-ended queue implemented with a growable ring buffer.
62///
63/// The "default" usage of this type as a queue is to use [`push_back`] to add to
64/// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
65/// push onto the back in this manner, and iterating over `VecDeque` goes front
66/// to back.
67///
68/// A `VecDeque` with a known list of items can be initialized from an array:
69///
70/// ```
71/// use std::collections::VecDeque;
72///
73/// let deq = VecDeque::from([-1, 0, 1]);
74/// ```
75///
76/// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
77/// in memory. If you want to access the elements as a single slice, such as for
78/// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
79/// so that its elements do not wrap, and returns a mutable slice to the
80/// now-contiguous element sequence.
81///
82/// [`push_back`]: VecDeque::push_back
83/// [`pop_front`]: VecDeque::pop_front
84/// [`extend`]: VecDeque::extend
85/// [`append`]: VecDeque::append
86/// [`make_contiguous`]: VecDeque::make_contiguous
87#[cfg_attr(not(test), rustc_diagnostic_item = "VecDeque")]
88#[stable(feature = "rust1", since = "1.0.0")]
89#[rustc_insignificant_dtor]
90pub struct VecDeque<
91 T,
92 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
93> {
94 // `self[0]`, if it exists, is `buf[head]`.
95 // `head < buf.capacity()`, unless `buf.capacity() == 0` when `head == 0`.
96 head: usize,
97 // the number of initialized elements, starting from the one at `head` and potentially wrapping around.
98 // if `len == 0`, the exact value of `head` is unimportant.
99 // if `T` is zero-Sized, then `self.len <= usize::MAX`, otherwise `self.len <= isize::MAX as usize`.
100 len: usize,
101 buf: RawVec<T, A>,
102}
103
104#[stable(feature = "rust1", since = "1.0.0")]
105impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A> {
106 #[track_caller]
107 fn clone(&self) -> Self {
108 let mut deq = Self::with_capacity_in(self.len(), self.allocator().clone());
109 deq.extend(self.iter().cloned());
110 deq
111 }
112
113 /// Overwrites the contents of `self` with a clone of the contents of `source`.
114 ///
115 /// This method is preferred over simply assigning `source.clone()` to `self`,
116 /// as it avoids reallocation if possible.
117 #[track_caller]
118 fn clone_from(&mut self, source: &Self) {
119 self.clear();
120 self.extend(source.iter().cloned());
121 }
122}
123
124#[stable(feature = "rust1", since = "1.0.0")]
125unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
126 fn drop(&mut self) {
127 /// Runs the destructor for all items in the slice when it gets dropped (normally or
128 /// during unwinding).
129 struct Dropper<'a, T>(&'a mut [T]);
130
131 impl<'a, T> Drop for Dropper<'a, T> {
132 fn drop(&mut self) {
133 unsafe {
134 ptr::drop_in_place(self.0);
135 }
136 }
137 }
138
139 let (front, back) = self.as_mut_slices();
140 unsafe {
141 let _back_dropper = Dropper(back);
142 // use drop for [T]
143 ptr::drop_in_place(front);
144 }
145 // RawVec handles deallocation
146 }
147}
148
149#[stable(feature = "rust1", since = "1.0.0")]
150impl<T> Default for VecDeque<T> {
151 /// Creates an empty deque.
152 #[inline]
153 fn default() -> VecDeque<T> {
154 VecDeque::new()
155 }
156}
157
158impl<T, A: Allocator> VecDeque<T, A> {
159 /// Marginally more convenient
160 #[inline]
161 fn ptr(&self) -> *mut T {
162 self.buf.ptr()
163 }
164
165 /// Appends an element to the buffer.
166 ///
167 /// # Safety
168 ///
169 /// May only be called if `deque.len() < deque.capacity()`
170 #[inline]
171 unsafe fn push_unchecked(&mut self, element: T) {
172 // SAFETY: Because of the precondition, it's guaranteed that there is space
173 // in the logical array after the last element.
174 unsafe { self.buffer_write(self.to_physical_idx(self.len), element) };
175 // This can't overflow because `deque.len() < deque.capacity() <= usize::MAX`.
176 self.len += 1;
177 }
178
179 /// Moves an element out of the buffer
180 #[inline]
181 unsafe fn buffer_read(&mut self, off: usize) -> T {
182 unsafe { ptr::read(self.ptr().add(off)) }
183 }
184
185 /// Writes an element into the buffer, moving it.
186 #[inline]
187 unsafe fn buffer_write(&mut self, off: usize, value: T) {
188 unsafe {
189 ptr::write(self.ptr().add(off), value);
190 }
191 }
192
193 /// Returns a slice pointer into the buffer.
194 /// `range` must lie inside `0..self.capacity()`.
195 #[inline]
196 unsafe fn buffer_range(&self, range: Range<usize>) -> *mut [T] {
197 unsafe {
198 ptr::slice_from_raw_parts_mut(self.ptr().add(range.start), range.end - range.start)
199 }
200 }
201
202 /// Returns `true` if the buffer is at full capacity.
203 #[inline]
204 fn is_full(&self) -> bool {
205 self.len == self.capacity()
206 }
207
208 /// Returns the index in the underlying buffer for a given logical element
209 /// index + addend.
210 #[inline]
211 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
212 wrap_index(idx.wrapping_add(addend), self.capacity())
213 }
214
215 #[inline]
216 fn to_physical_idx(&self, idx: usize) -> usize {
217 self.wrap_add(self.head, idx)
218 }
219
220 /// Returns the index in the underlying buffer for a given logical element
221 /// index - subtrahend.
222 #[inline]
223 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
224 wrap_index(idx.wrapping_sub(subtrahend).wrapping_add(self.capacity()), self.capacity())
225 }
226
227 /// Copies a contiguous block of memory len long from src to dst
228 #[inline]
229 unsafe fn copy(&mut self, src: usize, dst: usize, len: usize) {
230 debug_assert!(
231 dst + len <= self.capacity(),
232 "cpy dst={} src={} len={} cap={}",
233 dst,
234 src,
235 len,
236 self.capacity()
237 );
238 debug_assert!(
239 src + len <= self.capacity(),
240 "cpy dst={} src={} len={} cap={}",
241 dst,
242 src,
243 len,
244 self.capacity()
245 );
246 unsafe {
247 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
248 }
249 }
250
251 /// Copies a contiguous block of memory len long from src to dst
252 #[inline]
253 unsafe fn copy_nonoverlapping(&mut self, src: usize, dst: usize, len: usize) {
254 debug_assert!(
255 dst + len <= self.capacity(),
256 "cno dst={} src={} len={} cap={}",
257 dst,
258 src,
259 len,
260 self.capacity()
261 );
262 debug_assert!(
263 src + len <= self.capacity(),
264 "cno dst={} src={} len={} cap={}",
265 dst,
266 src,
267 len,
268 self.capacity()
269 );
270 unsafe {
271 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
272 }
273 }
274
275 /// Copies a potentially wrapping block of memory len long from src to dest.
276 /// (abs(dst - src) + len) must be no larger than capacity() (There must be at
277 /// most one continuous overlapping region between src and dest).
278 unsafe fn wrap_copy(&mut self, src: usize, dst: usize, len: usize) {
279 debug_assert!(
280 cmp::min(src.abs_diff(dst), self.capacity() - src.abs_diff(dst)) + len
281 <= self.capacity(),
282 "wrc dst={} src={} len={} cap={}",
283 dst,
284 src,
285 len,
286 self.capacity()
287 );
288
289 // If T is a ZST, don't do any copying.
290 if T::IS_ZST || src == dst || len == 0 {
291 return;
292 }
293
294 let dst_after_src = self.wrap_sub(dst, src) < len;
295
296 let src_pre_wrap_len = self.capacity() - src;
297 let dst_pre_wrap_len = self.capacity() - dst;
298 let src_wraps = src_pre_wrap_len < len;
299 let dst_wraps = dst_pre_wrap_len < len;
300
301 match (dst_after_src, src_wraps, dst_wraps) {
302 (_, false, false) => {
303 // src doesn't wrap, dst doesn't wrap
304 //
305 // S . . .
306 // 1 [_ _ A A B B C C _]
307 // 2 [_ _ A A A A B B _]
308 // D . . .
309 //
310 unsafe {
311 self.copy(src, dst, len);
312 }
313 }
314 (false, false, true) => {
315 // dst before src, src doesn't wrap, dst wraps
316 //
317 // S . . .
318 // 1 [A A B B _ _ _ C C]
319 // 2 [A A B B _ _ _ A A]
320 // 3 [B B B B _ _ _ A A]
321 // . . D .
322 //
323 unsafe {
324 self.copy(src, dst, dst_pre_wrap_len);
325 self.copy(src + dst_pre_wrap_len, 0, len - dst_pre_wrap_len);
326 }
327 }
328 (true, false, true) => {
329 // src before dst, src doesn't wrap, dst wraps
330 //
331 // S . . .
332 // 1 [C C _ _ _ A A B B]
333 // 2 [B B _ _ _ A A B B]
334 // 3 [B B _ _ _ A A A A]
335 // . . D .
336 //
337 unsafe {
338 self.copy(src + dst_pre_wrap_len, 0, len - dst_pre_wrap_len);
339 self.copy(src, dst, dst_pre_wrap_len);
340 }
341 }
342 (false, true, false) => {
343 // dst before src, src wraps, dst doesn't wrap
344 //
345 // . . S .
346 // 1 [C C _ _ _ A A B B]
347 // 2 [C C _ _ _ B B B B]
348 // 3 [C C _ _ _ B B C C]
349 // D . . .
350 //
351 unsafe {
352 self.copy(src, dst, src_pre_wrap_len);
353 self.copy(0, dst + src_pre_wrap_len, len - src_pre_wrap_len);
354 }
355 }
356 (true, true, false) => {
357 // src before dst, src wraps, dst doesn't wrap
358 //
359 // . . S .
360 // 1 [A A B B _ _ _ C C]
361 // 2 [A A A A _ _ _ C C]
362 // 3 [C C A A _ _ _ C C]
363 // D . . .
364 //
365 unsafe {
366 self.copy(0, dst + src_pre_wrap_len, len - src_pre_wrap_len);
367 self.copy(src, dst, src_pre_wrap_len);
368 }
369 }
370 (false, true, true) => {
371 // dst before src, src wraps, dst wraps
372 //
373 // . . . S .
374 // 1 [A B C D _ E F G H]
375 // 2 [A B C D _ E G H H]
376 // 3 [A B C D _ E G H A]
377 // 4 [B C C D _ E G H A]
378 // . . D . .
379 //
380 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
381 let delta = dst_pre_wrap_len - src_pre_wrap_len;
382 unsafe {
383 self.copy(src, dst, src_pre_wrap_len);
384 self.copy(0, dst + src_pre_wrap_len, delta);
385 self.copy(delta, 0, len - dst_pre_wrap_len);
386 }
387 }
388 (true, true, true) => {
389 // src before dst, src wraps, dst wraps
390 //
391 // . . S . .
392 // 1 [A B C D _ E F G H]
393 // 2 [A A B D _ E F G H]
394 // 3 [H A B D _ E F G H]
395 // 4 [H A B D _ E F F G]
396 // . . . D .
397 //
398 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
399 let delta = src_pre_wrap_len - dst_pre_wrap_len;
400 unsafe {
401 self.copy(0, delta, len - src_pre_wrap_len);
402 self.copy(self.capacity() - delta, 0, delta);
403 self.copy(src, dst, dst_pre_wrap_len);
404 }
405 }
406 }
407 }
408
409 /// Copies all values from `src` to `dst`, wrapping around if needed.
410 /// Assumes capacity is sufficient.
411 #[inline]
412 unsafe fn copy_slice(&mut self, dst: usize, src: &[T]) {
413 debug_assert!(src.len() <= self.capacity());
414 let head_room = self.capacity() - dst;
415 if src.len() <= head_room {
416 unsafe {
417 ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst), src.len());
418 }
419 } else {
420 let (left, right) = src.split_at(head_room);
421 unsafe {
422 ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst), left.len());
423 ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
424 }
425 }
426 }
427
428 /// Writes all values from `iter` to `dst`.
429 ///
430 /// # Safety
431 ///
432 /// Assumes no wrapping around happens.
433 /// Assumes capacity is sufficient.
434 #[inline]
435 unsafe fn write_iter(
436 &mut self,
437 dst: usize,
438 iter: impl Iterator<Item = T>,
439 written: &mut usize,
440 ) {
441 iter.enumerate().for_each(|(i, element)| unsafe {
442 self.buffer_write(dst + i, element);
443 *written += 1;
444 });
445 }
446
447 /// Writes all values from `iter` to `dst`, wrapping
448 /// at the end of the buffer and returns the number
449 /// of written values.
450 ///
451 /// # Safety
452 ///
453 /// Assumes that `iter` yields at most `len` items.
454 /// Assumes capacity is sufficient.
455 unsafe fn write_iter_wrapping(
456 &mut self,
457 dst: usize,
458 mut iter: impl Iterator<Item = T>,
459 len: usize,
460 ) -> usize {
461 struct Guard<'a, T, A: Allocator> {
462 deque: &'a mut VecDeque<T, A>,
463 written: usize,
464 }
465
466 impl<'a, T, A: Allocator> Drop for Guard<'a, T, A> {
467 fn drop(&mut self) {
468 self.deque.len += self.written;
469 }
470 }
471
472 let head_room = self.capacity() - dst;
473
474 let mut guard = Guard { deque: self, written: 0 };
475
476 if head_room >= len {
477 unsafe { guard.deque.write_iter(dst, iter, &mut guard.written) };
478 } else {
479 unsafe {
480 guard.deque.write_iter(
481 dst,
482 ByRefSized(&mut iter).take(head_room),
483 &mut guard.written,
484 );
485 guard.deque.write_iter(0, iter, &mut guard.written)
486 };
487 }
488
489 guard.written
490 }
491
492 /// Frobs the head and tail sections around to handle the fact that we
493 /// just reallocated. Unsafe because it trusts old_capacity.
494 #[inline]
495 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
496 let new_capacity = self.capacity();
497 debug_assert!(new_capacity >= old_capacity);
498
499 // Move the shortest contiguous section of the ring buffer
500 //
501 // H := head
502 // L := last element (`self.to_physical_idx(self.len - 1)`)
503 //
504 // H L
505 // [o o o o o o o o ]
506 // H L
507 // A [o o o o o o o o . . . . . . . . ]
508 // L H
509 // [o o o o o o o o ]
510 // H L
511 // B [. . . o o o o o o o o . . . . . ]
512 // L H
513 // [o o o o o o o o ]
514 // L H
515 // C [o o o o o o . . . . . . . . o o ]
516
517 // can't use is_contiguous() because the capacity is already updated.
518 if self.head <= old_capacity - self.len {
519 // A
520 // Nop
521 } else {
522 let head_len = old_capacity - self.head;
523 let tail_len = self.len - head_len;
524 if head_len > tail_len && new_capacity - old_capacity >= tail_len {
525 // B
526 unsafe {
527 self.copy_nonoverlapping(0, old_capacity, tail_len);
528 }
529 } else {
530 // C
531 let new_head = new_capacity - head_len;
532 unsafe {
533 // can't use copy_nonoverlapping here, because if e.g. head_len = 2
534 // and new_capacity = old_capacity + 1, then the heads overlap.
535 self.copy(self.head, new_head, head_len);
536 }
537 self.head = new_head;
538 }
539 }
540 debug_assert!(self.head < self.capacity() || self.capacity() == 0);
541 }
542}
543
544impl<T> VecDeque<T> {
545 /// Creates an empty deque.
546 ///
547 /// # Examples
548 ///
549 /// ```
550 /// use std::collections::VecDeque;
551 ///
552 /// let deque: VecDeque<u32> = VecDeque::new();
553 /// ```
554 #[inline]
555 #[stable(feature = "rust1", since = "1.0.0")]
556 #[rustc_const_stable(feature = "const_vec_deque_new", since = "1.68.0")]
557 #[must_use]
558 pub const fn new() -> VecDeque<T> {
559 // FIXME(const-hack): This should just be `VecDeque::new_in(Global)` once that hits stable.
560 VecDeque { head: 0, len: 0, buf: RawVec::new() }
561 }
562
563 /// Creates an empty deque with space for at least `capacity` elements.
564 ///
565 /// # Examples
566 ///
567 /// ```
568 /// use std::collections::VecDeque;
569 ///
570 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
571 /// ```
572 #[inline]
573 #[stable(feature = "rust1", since = "1.0.0")]
574 #[must_use]
575 #[track_caller]
576 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
577 Self::with_capacity_in(capacity, Global)
578 }
579
580 /// Creates an empty deque with space for at least `capacity` elements.
581 ///
582 /// # Errors
583 ///
584 /// Returns an error if the capacity exceeds `isize::MAX` _bytes_,
585 /// or if the allocator reports allocation failure.
586 ///
587 /// # Examples
588 ///
589 /// ```
590 /// # #![feature(try_with_capacity)]
591 /// # #[allow(unused)]
592 /// # fn example() -> Result<(), std::collections::TryReserveError> {
593 /// use std::collections::VecDeque;
594 ///
595 /// let deque: VecDeque<u32> = VecDeque::try_with_capacity(10)?;
596 /// # Ok(()) }
597 /// ```
598 #[inline]
599 #[unstable(feature = "try_with_capacity", issue = "91913")]
600 pub fn try_with_capacity(capacity: usize) -> Result<VecDeque<T>, TryReserveError> {
601 Ok(VecDeque { head: 0, len: 0, buf: RawVec::try_with_capacity_in(capacity, Global)? })
602 }
603}
604
605impl<T, A: Allocator> VecDeque<T, A> {
606 /// Creates an empty deque.
607 ///
608 /// # Examples
609 ///
610 /// ```
611 /// use std::collections::VecDeque;
612 ///
613 /// let deque: VecDeque<u32> = VecDeque::new();
614 /// ```
615 #[inline]
616 #[unstable(feature = "allocator_api", issue = "32838")]
617 pub const fn new_in(alloc: A) -> VecDeque<T, A> {
618 VecDeque { head: 0, len: 0, buf: RawVec::new_in(alloc) }
619 }
620
621 /// Creates an empty deque with space for at least `capacity` elements.
622 ///
623 /// # Examples
624 ///
625 /// ```
626 /// use std::collections::VecDeque;
627 ///
628 /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
629 /// ```
630 #[unstable(feature = "allocator_api", issue = "32838")]
631 #[track_caller]
632 pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
633 VecDeque { head: 0, len: 0, buf: RawVec::with_capacity_in(capacity, alloc) }
634 }
635
636 /// Creates a `VecDeque` from a raw allocation, when the initialized
637 /// part of that allocation forms a *contiguous* subslice thereof.
638 ///
639 /// For use by `vec::IntoIter::into_vecdeque`
640 ///
641 /// # Safety
642 ///
643 /// All the usual requirements on the allocated memory like in
644 /// `Vec::from_raw_parts_in`, but takes a *range* of elements that are
645 /// initialized rather than only supporting `0..len`. Requires that
646 /// `initialized.start` ≤ `initialized.end` ≤ `capacity`.
647 #[inline]
648 pub(crate) unsafe fn from_contiguous_raw_parts_in(
649 ptr: *mut T,
650 initialized: Range<usize>,
651 capacity: usize,
652 alloc: A,
653 ) -> Self {
654 debug_assert!(initialized.start <= initialized.end);
655 debug_assert!(initialized.end <= capacity);
656
657 // SAFETY: Our safety precondition guarantees the range length won't wrap,
658 // and that the allocation is valid for use in `RawVec`.
659 unsafe {
660 VecDeque {
661 head: initialized.start,
662 len: initialized.end.unchecked_sub(initialized.start),
663 buf: RawVec::from_raw_parts_in(ptr, capacity, alloc),
664 }
665 }
666 }
667
668 /// Provides a reference to the element at the given index.
669 ///
670 /// Element at index 0 is the front of the queue.
671 ///
672 /// # Examples
673 ///
674 /// ```
675 /// use std::collections::VecDeque;
676 ///
677 /// let mut buf = VecDeque::new();
678 /// buf.push_back(3);
679 /// buf.push_back(4);
680 /// buf.push_back(5);
681 /// buf.push_back(6);
682 /// assert_eq!(buf.get(1), Some(&4));
683 /// ```
684 #[stable(feature = "rust1", since = "1.0.0")]
685 pub fn get(&self, index: usize) -> Option<&T> {
686 if index < self.len {
687 let idx = self.to_physical_idx(index);
688 unsafe { Some(&*self.ptr().add(idx)) }
689 } else {
690 None
691 }
692 }
693
694 /// Provides a mutable reference to the element at the given index.
695 ///
696 /// Element at index 0 is the front of the queue.
697 ///
698 /// # Examples
699 ///
700 /// ```
701 /// use std::collections::VecDeque;
702 ///
703 /// let mut buf = VecDeque::new();
704 /// buf.push_back(3);
705 /// buf.push_back(4);
706 /// buf.push_back(5);
707 /// buf.push_back(6);
708 /// assert_eq!(buf[1], 4);
709 /// if let Some(elem) = buf.get_mut(1) {
710 /// *elem = 7;
711 /// }
712 /// assert_eq!(buf[1], 7);
713 /// ```
714 #[stable(feature = "rust1", since = "1.0.0")]
715 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
716 if index < self.len {
717 let idx = self.to_physical_idx(index);
718 unsafe { Some(&mut *self.ptr().add(idx)) }
719 } else {
720 None
721 }
722 }
723
724 /// Swaps elements at indices `i` and `j`.
725 ///
726 /// `i` and `j` may be equal.
727 ///
728 /// Element at index 0 is the front of the queue.
729 ///
730 /// # Panics
731 ///
732 /// Panics if either index is out of bounds.
733 ///
734 /// # Examples
735 ///
736 /// ```
737 /// use std::collections::VecDeque;
738 ///
739 /// let mut buf = VecDeque::new();
740 /// buf.push_back(3);
741 /// buf.push_back(4);
742 /// buf.push_back(5);
743 /// assert_eq!(buf, [3, 4, 5]);
744 /// buf.swap(0, 2);
745 /// assert_eq!(buf, [5, 4, 3]);
746 /// ```
747 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn swap(&mut self, i: usize, j: usize) {
749 assert!(i < self.len());
750 assert!(j < self.len());
751 let ri = self.to_physical_idx(i);
752 let rj = self.to_physical_idx(j);
753 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
754 }
755
756 /// Returns the number of elements the deque can hold without
757 /// reallocating.
758 ///
759 /// # Examples
760 ///
761 /// ```
762 /// use std::collections::VecDeque;
763 ///
764 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
765 /// assert!(buf.capacity() >= 10);
766 /// ```
767 #[inline]
768 #[stable(feature = "rust1", since = "1.0.0")]
769 pub fn capacity(&self) -> usize {
770 if T::IS_ZST { usize::MAX } else { self.buf.capacity() }
771 }
772
773 /// Reserves the minimum capacity for at least `additional` more elements to be inserted in the
774 /// given deque. Does nothing if the capacity is already sufficient.
775 ///
776 /// Note that the allocator may give the collection more space than it requests. Therefore
777 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
778 /// insertions are expected.
779 ///
780 /// # Panics
781 ///
782 /// Panics if the new capacity overflows `usize`.
783 ///
784 /// # Examples
785 ///
786 /// ```
787 /// use std::collections::VecDeque;
788 ///
789 /// let mut buf: VecDeque<i32> = [1].into();
790 /// buf.reserve_exact(10);
791 /// assert!(buf.capacity() >= 11);
792 /// ```
793 ///
794 /// [`reserve`]: VecDeque::reserve
795 #[stable(feature = "rust1", since = "1.0.0")]
796 #[track_caller]
797 pub fn reserve_exact(&mut self, additional: usize) {
798 let new_cap = self.len.checked_add(additional).expect("capacity overflow");
799 let old_cap = self.capacity();
800
801 if new_cap > old_cap {
802 self.buf.reserve_exact(self.len, additional);
803 unsafe {
804 self.handle_capacity_increase(old_cap);
805 }
806 }
807 }
808
809 /// Reserves capacity for at least `additional` more elements to be inserted in the given
810 /// deque. The collection may reserve more space to speculatively avoid frequent reallocations.
811 ///
812 /// # Panics
813 ///
814 /// Panics if the new capacity overflows `usize`.
815 ///
816 /// # Examples
817 ///
818 /// ```
819 /// use std::collections::VecDeque;
820 ///
821 /// let mut buf: VecDeque<i32> = [1].into();
822 /// buf.reserve(10);
823 /// assert!(buf.capacity() >= 11);
824 /// ```
825 #[stable(feature = "rust1", since = "1.0.0")]
826 #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_reserve")]
827 #[track_caller]
828 pub fn reserve(&mut self, additional: usize) {
829 let new_cap = self.len.checked_add(additional).expect("capacity overflow");
830 let old_cap = self.capacity();
831
832 if new_cap > old_cap {
833 // we don't need to reserve_exact(), as the size doesn't have
834 // to be a power of 2.
835 self.buf.reserve(self.len, additional);
836 unsafe {
837 self.handle_capacity_increase(old_cap);
838 }
839 }
840 }
841
842 /// Tries to reserve the minimum capacity for at least `additional` more elements to
843 /// be inserted in the given deque. After calling `try_reserve_exact`,
844 /// capacity will be greater than or equal to `self.len() + additional` if
845 /// it returns `Ok(())`. Does nothing if the capacity is already sufficient.
846 ///
847 /// Note that the allocator may give the collection more space than it
848 /// requests. Therefore, capacity can not be relied upon to be precisely
849 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
850 ///
851 /// [`try_reserve`]: VecDeque::try_reserve
852 ///
853 /// # Errors
854 ///
855 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
856 /// is returned.
857 ///
858 /// # Examples
859 ///
860 /// ```
861 /// use std::collections::TryReserveError;
862 /// use std::collections::VecDeque;
863 ///
864 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
865 /// let mut output = VecDeque::new();
866 ///
867 /// // Pre-reserve the memory, exiting if we can't
868 /// output.try_reserve_exact(data.len())?;
869 ///
870 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
871 /// output.extend(data.iter().map(|&val| {
872 /// val * 2 + 5 // very complicated
873 /// }));
874 ///
875 /// Ok(output)
876 /// }
877 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
878 /// ```
879 #[stable(feature = "try_reserve", since = "1.57.0")]
880 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
881 let new_cap =
882 self.len.checked_add(additional).ok_or(TryReserveErrorKind::CapacityOverflow)?;
883 let old_cap = self.capacity();
884
885 if new_cap > old_cap {
886 self.buf.try_reserve_exact(self.len, additional)?;
887 unsafe {
888 self.handle_capacity_increase(old_cap);
889 }
890 }
891 Ok(())
892 }
893
894 /// Tries to reserve capacity for at least `additional` more elements to be inserted
895 /// in the given deque. The collection may reserve more space to speculatively avoid
896 /// frequent reallocations. After calling `try_reserve`, capacity will be
897 /// greater than or equal to `self.len() + additional` if it returns
898 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
899 /// preserves the contents even if an error occurs.
900 ///
901 /// # Errors
902 ///
903 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
904 /// is returned.
905 ///
906 /// # Examples
907 ///
908 /// ```
909 /// use std::collections::TryReserveError;
910 /// use std::collections::VecDeque;
911 ///
912 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
913 /// let mut output = VecDeque::new();
914 ///
915 /// // Pre-reserve the memory, exiting if we can't
916 /// output.try_reserve(data.len())?;
917 ///
918 /// // Now we know this can't OOM in the middle of our complex work
919 /// output.extend(data.iter().map(|&val| {
920 /// val * 2 + 5 // very complicated
921 /// }));
922 ///
923 /// Ok(output)
924 /// }
925 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
926 /// ```
927 #[stable(feature = "try_reserve", since = "1.57.0")]
928 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
929 let new_cap =
930 self.len.checked_add(additional).ok_or(TryReserveErrorKind::CapacityOverflow)?;
931 let old_cap = self.capacity();
932
933 if new_cap > old_cap {
934 self.buf.try_reserve(self.len, additional)?;
935 unsafe {
936 self.handle_capacity_increase(old_cap);
937 }
938 }
939 Ok(())
940 }
941
942 /// Shrinks the capacity of the deque as much as possible.
943 ///
944 /// It will drop down as close as possible to the length but the allocator may still inform the
945 /// deque that there is space for a few more elements.
946 ///
947 /// # Examples
948 ///
949 /// ```
950 /// use std::collections::VecDeque;
951 ///
952 /// let mut buf = VecDeque::with_capacity(15);
953 /// buf.extend(0..4);
954 /// assert_eq!(buf.capacity(), 15);
955 /// buf.shrink_to_fit();
956 /// assert!(buf.capacity() >= 4);
957 /// ```
958 #[stable(feature = "deque_extras_15", since = "1.5.0")]
959 #[track_caller]
960 pub fn shrink_to_fit(&mut self) {
961 self.shrink_to(0);
962 }
963
964 /// Shrinks the capacity of the deque with a lower bound.
965 ///
966 /// The capacity will remain at least as large as both the length
967 /// and the supplied value.
968 ///
969 /// If the current capacity is less than the lower limit, this is a no-op.
970 ///
971 /// # Examples
972 ///
973 /// ```
974 /// use std::collections::VecDeque;
975 ///
976 /// let mut buf = VecDeque::with_capacity(15);
977 /// buf.extend(0..4);
978 /// assert_eq!(buf.capacity(), 15);
979 /// buf.shrink_to(6);
980 /// assert!(buf.capacity() >= 6);
981 /// buf.shrink_to(0);
982 /// assert!(buf.capacity() >= 4);
983 /// ```
984 #[stable(feature = "shrink_to", since = "1.56.0")]
985 #[track_caller]
986 pub fn shrink_to(&mut self, min_capacity: usize) {
987 let target_cap = min_capacity.max(self.len);
988
989 // never shrink ZSTs
990 if T::IS_ZST || self.capacity() <= target_cap {
991 return;
992 }
993
994 // There are three cases of interest:
995 // All elements are out of desired bounds
996 // Elements are contiguous, and tail is out of desired bounds
997 // Elements are discontiguous
998 //
999 // At all other times, element positions are unaffected.
1000
1001 // `head` and `len` are at most `isize::MAX` and `target_cap < self.capacity()`, so nothing can
1002 // overflow.
1003 let tail_outside = (target_cap + 1..=self.capacity()).contains(&(self.head + self.len));
1004 // Used in the drop guard below.
1005 let old_head = self.head;
1006
1007 if self.len == 0 {
1008 self.head = 0;
1009 } else if self.head >= target_cap && tail_outside {
1010 // Head and tail are both out of bounds, so copy all of them to the front.
1011 //
1012 // H := head
1013 // L := last element
1014 // H L
1015 // [. . . . . . . . o o o o o o o . ]
1016 // H L
1017 // [o o o o o o o . ]
1018 unsafe {
1019 // nonoverlapping because `self.head >= target_cap >= self.len`.
1020 self.copy_nonoverlapping(self.head, 0, self.len);
1021 }
1022 self.head = 0;
1023 } else if self.head < target_cap && tail_outside {
1024 // Head is in bounds, tail is out of bounds.
1025 // Copy the overflowing part to the beginning of the
1026 // buffer. This won't overlap because `target_cap >= self.len`.
1027 //
1028 // H := head
1029 // L := last element
1030 // H L
1031 // [. . . o o o o o o o . . . . . . ]
1032 // L H
1033 // [o o . o o o o o ]
1034 let len = self.head + self.len - target_cap;
1035 unsafe {
1036 self.copy_nonoverlapping(target_cap, 0, len);
1037 }
1038 } else if !self.is_contiguous() {
1039 // The head slice is at least partially out of bounds, tail is in bounds.
1040 // Copy the head backwards so it lines up with the target capacity.
1041 // This won't overlap because `target_cap >= self.len`.
1042 //
1043 // H := head
1044 // L := last element
1045 // L H
1046 // [o o o o o . . . . . . . . . o o ]
1047 // L H
1048 // [o o o o o . o o ]
1049 let head_len = self.capacity() - self.head;
1050 let new_head = target_cap - head_len;
1051 unsafe {
1052 // can't use `copy_nonoverlapping()` here because the new and old
1053 // regions for the head might overlap.
1054 self.copy(self.head, new_head, head_len);
1055 }
1056 self.head = new_head;
1057 }
1058
1059 struct Guard<'a, T, A: Allocator> {
1060 deque: &'a mut VecDeque<T, A>,
1061 old_head: usize,
1062 target_cap: usize,
1063 }
1064
1065 impl<T, A: Allocator> Drop for Guard<'_, T, A> {
1066 #[cold]
1067 fn drop(&mut self) {
1068 unsafe {
1069 // SAFETY: This is only called if `buf.shrink_to_fit` unwinds,
1070 // which is the only time it's safe to call `abort_shrink`.
1071 self.deque.abort_shrink(self.old_head, self.target_cap)
1072 }
1073 }
1074 }
1075
1076 let guard = Guard { deque: self, old_head, target_cap };
1077
1078 guard.deque.buf.shrink_to_fit(target_cap);
1079
1080 // Don't drop the guard if we didn't unwind.
1081 mem::forget(guard);
1082
1083 debug_assert!(self.head < self.capacity() || self.capacity() == 0);
1084 debug_assert!(self.len <= self.capacity());
1085 }
1086
1087 /// Reverts the deque back into a consistent state in case `shrink_to` failed.
1088 /// This is necessary to prevent UB if the backing allocator returns an error
1089 /// from `shrink` and `handle_alloc_error` subsequently unwinds (see #123369).
1090 ///
1091 /// `old_head` refers to the head index before `shrink_to` was called. `target_cap`
1092 /// is the capacity that it was trying to shrink to.
1093 unsafe fn abort_shrink(&mut self, old_head: usize, target_cap: usize) {
1094 // Moral equivalent of self.head + self.len <= target_cap. Won't overflow
1095 // because `self.len <= target_cap`.
1096 if self.head <= target_cap - self.len {
1097 // The deque's buffer is contiguous, so no need to copy anything around.
1098 return;
1099 }
1100
1101 // `shrink_to` already copied the head to fit into the new capacity, so this won't overflow.
1102 let head_len = target_cap - self.head;
1103 // `self.head > target_cap - self.len` => `self.len > target_cap - self.head =: head_len` so this must be positive.
1104 let tail_len = self.len - head_len;
1105
1106 if tail_len <= cmp::min(head_len, self.capacity() - target_cap) {
1107 // There's enough spare capacity to copy the tail to the back (because `tail_len < self.capacity() - target_cap`),
1108 // and copying the tail should be cheaper than copying the head (because `tail_len <= head_len`).
1109
1110 unsafe {
1111 // The old tail and the new tail can't overlap because the head slice lies between them. The
1112 // head slice ends at `target_cap`, so that's where we copy to.
1113 self.copy_nonoverlapping(0, target_cap, tail_len);
1114 }
1115 } else {
1116 // Either there's not enough spare capacity to make the deque contiguous, or the head is shorter than the tail
1117 // (and therefore hopefully cheaper to copy).
1118 unsafe {
1119 // The old and the new head slice can overlap, so we can't use `copy_nonoverlapping` here.
1120 self.copy(self.head, old_head, head_len);
1121 self.head = old_head;
1122 }
1123 }
1124 }
1125
1126 /// Shortens the deque, keeping the first `len` elements and dropping
1127 /// the rest.
1128 ///
1129 /// If `len` is greater or equal to the deque's current length, this has
1130 /// no effect.
1131 ///
1132 /// # Examples
1133 ///
1134 /// ```
1135 /// use std::collections::VecDeque;
1136 ///
1137 /// let mut buf = VecDeque::new();
1138 /// buf.push_back(5);
1139 /// buf.push_back(10);
1140 /// buf.push_back(15);
1141 /// assert_eq!(buf, [5, 10, 15]);
1142 /// buf.truncate(1);
1143 /// assert_eq!(buf, [5]);
1144 /// ```
1145 #[stable(feature = "deque_extras", since = "1.16.0")]
1146 pub fn truncate(&mut self, len: usize) {
1147 /// Runs the destructor for all items in the slice when it gets dropped (normally or
1148 /// during unwinding).
1149 struct Dropper<'a, T>(&'a mut [T]);
1150
1151 impl<'a, T> Drop for Dropper<'a, T> {
1152 fn drop(&mut self) {
1153 unsafe {
1154 ptr::drop_in_place(self.0);
1155 }
1156 }
1157 }
1158
1159 // Safe because:
1160 //
1161 // * Any slice passed to `drop_in_place` is valid; the second case has
1162 // `len <= front.len()` and returning on `len > self.len()` ensures
1163 // `begin <= back.len()` in the first case
1164 // * The head of the VecDeque is moved before calling `drop_in_place`,
1165 // so no value is dropped twice if `drop_in_place` panics
1166 unsafe {
1167 if len >= self.len {
1168 return;
1169 }
1170
1171 let (front, back) = self.as_mut_slices();
1172 if len > front.len() {
1173 let begin = len - front.len();
1174 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
1175 self.len = len;
1176 ptr::drop_in_place(drop_back);
1177 } else {
1178 let drop_back = back as *mut _;
1179 let drop_front = front.get_unchecked_mut(len..) as *mut _;
1180 self.len = len;
1181
1182 // Make sure the second half is dropped even when a destructor
1183 // in the first one panics.
1184 let _back_dropper = Dropper(&mut *drop_back);
1185 ptr::drop_in_place(drop_front);
1186 }
1187 }
1188 }
1189
1190 /// Returns a reference to the underlying allocator.
1191 #[unstable(feature = "allocator_api", issue = "32838")]
1192 #[inline]
1193 pub fn allocator(&self) -> &A {
1194 self.buf.allocator()
1195 }
1196
1197 /// Returns a front-to-back iterator.
1198 ///
1199 /// # Examples
1200 ///
1201 /// ```
1202 /// use std::collections::VecDeque;
1203 ///
1204 /// let mut buf = VecDeque::new();
1205 /// buf.push_back(5);
1206 /// buf.push_back(3);
1207 /// buf.push_back(4);
1208 /// let b: &[_] = &[&5, &3, &4];
1209 /// let c: Vec<&i32> = buf.iter().collect();
1210 /// assert_eq!(&c[..], b);
1211 /// ```
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_iter")]
1214 pub fn iter(&self) -> Iter<'_, T> {
1215 let (a, b) = self.as_slices();
1216 Iter::new(a.iter(), b.iter())
1217 }
1218
1219 /// Returns a front-to-back iterator that returns mutable references.
1220 ///
1221 /// # Examples
1222 ///
1223 /// ```
1224 /// use std::collections::VecDeque;
1225 ///
1226 /// let mut buf = VecDeque::new();
1227 /// buf.push_back(5);
1228 /// buf.push_back(3);
1229 /// buf.push_back(4);
1230 /// for num in buf.iter_mut() {
1231 /// *num = *num - 2;
1232 /// }
1233 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1234 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1235 /// ```
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1238 let (a, b) = self.as_mut_slices();
1239 IterMut::new(a.iter_mut(), b.iter_mut())
1240 }
1241
1242 /// Returns a pair of slices which contain, in order, the contents of the
1243 /// deque.
1244 ///
1245 /// If [`make_contiguous`] was previously called, all elements of the
1246 /// deque will be in the first slice and the second slice will be empty.
1247 ///
1248 /// [`make_contiguous`]: VecDeque::make_contiguous
1249 ///
1250 /// # Examples
1251 ///
1252 /// ```
1253 /// use std::collections::VecDeque;
1254 ///
1255 /// let mut deque = VecDeque::new();
1256 ///
1257 /// deque.push_back(0);
1258 /// deque.push_back(1);
1259 /// deque.push_back(2);
1260 ///
1261 /// assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..]));
1262 ///
1263 /// deque.push_front(10);
1264 /// deque.push_front(9);
1265 ///
1266 /// assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1267 /// ```
1268 #[inline]
1269 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1270 pub fn as_slices(&self) -> (&[T], &[T]) {
1271 let (a_range, b_range) = self.slice_ranges(.., self.len);
1272 // SAFETY: `slice_ranges` always returns valid ranges into
1273 // the physical buffer.
1274 unsafe { (&*self.buffer_range(a_range), &*self.buffer_range(b_range)) }
1275 }
1276
1277 /// Returns a pair of slices which contain, in order, the contents of the
1278 /// deque.
1279 ///
1280 /// If [`make_contiguous`] was previously called, all elements of the
1281 /// deque will be in the first slice and the second slice will be empty.
1282 ///
1283 /// [`make_contiguous`]: VecDeque::make_contiguous
1284 ///
1285 /// # Examples
1286 ///
1287 /// ```
1288 /// use std::collections::VecDeque;
1289 ///
1290 /// let mut deque = VecDeque::new();
1291 ///
1292 /// deque.push_back(0);
1293 /// deque.push_back(1);
1294 ///
1295 /// deque.push_front(10);
1296 /// deque.push_front(9);
1297 ///
1298 /// deque.as_mut_slices().0[0] = 42;
1299 /// deque.as_mut_slices().1[0] = 24;
1300 /// assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
1301 /// ```
1302 #[inline]
1303 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1304 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1305 let (a_range, b_range) = self.slice_ranges(.., self.len);
1306 // SAFETY: `slice_ranges` always returns valid ranges into
1307 // the physical buffer.
1308 unsafe { (&mut *self.buffer_range(a_range), &mut *self.buffer_range(b_range)) }
1309 }
1310
1311 /// Returns the number of elements in the deque.
1312 ///
1313 /// # Examples
1314 ///
1315 /// ```
1316 /// use std::collections::VecDeque;
1317 ///
1318 /// let mut deque = VecDeque::new();
1319 /// assert_eq!(deque.len(), 0);
1320 /// deque.push_back(1);
1321 /// assert_eq!(deque.len(), 1);
1322 /// ```
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 #[rustc_confusables("length", "size")]
1325 pub fn len(&self) -> usize {
1326 self.len
1327 }
1328
1329 /// Returns `true` if the deque is empty.
1330 ///
1331 /// # Examples
1332 ///
1333 /// ```
1334 /// use std::collections::VecDeque;
1335 ///
1336 /// let mut deque = VecDeque::new();
1337 /// assert!(deque.is_empty());
1338 /// deque.push_front(1);
1339 /// assert!(!deque.is_empty());
1340 /// ```
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 pub fn is_empty(&self) -> bool {
1343 self.len == 0
1344 }
1345
1346 /// Given a range into the logical buffer of the deque, this function
1347 /// return two ranges into the physical buffer that correspond to
1348 /// the given range. The `len` parameter should usually just be `self.len`;
1349 /// the reason it's passed explicitly is that if the deque is wrapped in
1350 /// a `Drain`, then `self.len` is not actually the length of the deque.
1351 ///
1352 /// # Safety
1353 ///
1354 /// This function is always safe to call. For the resulting ranges to be valid
1355 /// ranges into the physical buffer, the caller must ensure that the result of
1356 /// calling `slice::range(range, ..len)` represents a valid range into the
1357 /// logical buffer, and that all elements in that range are initialized.
1358 fn slice_ranges<R>(&self, range: R, len: usize) -> (Range<usize>, Range<usize>)
1359 where
1360 R: RangeBounds<usize>,
1361 {
1362 let Range { start, end } = slice::range(range, ..len);
1363 let len = end - start;
1364
1365 if len == 0 {
1366 (0..0, 0..0)
1367 } else {
1368 // `slice::range` guarantees that `start <= end <= len`.
1369 // because `len != 0`, we know that `start < end`, so `start < len`
1370 // and the indexing is valid.
1371 let wrapped_start = self.to_physical_idx(start);
1372
1373 // this subtraction can never overflow because `wrapped_start` is
1374 // at most `self.capacity()` (and if `self.capacity != 0`, then `wrapped_start` is strictly less
1375 // than `self.capacity`).
1376 let head_len = self.capacity() - wrapped_start;
1377
1378 if head_len >= len {
1379 // we know that `len + wrapped_start <= self.capacity <= usize::MAX`, so this addition can't overflow
1380 (wrapped_start..wrapped_start + len, 0..0)
1381 } else {
1382 // can't overflow because of the if condition
1383 let tail_len = len - head_len;
1384 (wrapped_start..self.capacity(), 0..tail_len)
1385 }
1386 }
1387 }
1388
1389 /// Creates an iterator that covers the specified range in the deque.
1390 ///
1391 /// # Panics
1392 ///
1393 /// Panics if the starting point is greater than the end point or if
1394 /// the end point is greater than the length of the deque.
1395 ///
1396 /// # Examples
1397 ///
1398 /// ```
1399 /// use std::collections::VecDeque;
1400 ///
1401 /// let deque: VecDeque<_> = [1, 2, 3].into();
1402 /// let range = deque.range(2..).copied().collect::<VecDeque<_>>();
1403 /// assert_eq!(range, [3]);
1404 ///
1405 /// // A full range covers all contents
1406 /// let all = deque.range(..);
1407 /// assert_eq!(all.len(), 3);
1408 /// ```
1409 #[inline]
1410 #[stable(feature = "deque_range", since = "1.51.0")]
1411 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1412 where
1413 R: RangeBounds<usize>,
1414 {
1415 let (a_range, b_range) = self.slice_ranges(range, self.len);
1416 // SAFETY: The ranges returned by `slice_ranges`
1417 // are valid ranges into the physical buffer, so
1418 // it's ok to pass them to `buffer_range` and
1419 // dereference the result.
1420 let a = unsafe { &*self.buffer_range(a_range) };
1421 let b = unsafe { &*self.buffer_range(b_range) };
1422 Iter::new(a.iter(), b.iter())
1423 }
1424
1425 /// Creates an iterator that covers the specified mutable range in the deque.
1426 ///
1427 /// # Panics
1428 ///
1429 /// Panics if the starting point is greater than the end point or if
1430 /// the end point is greater than the length of the deque.
1431 ///
1432 /// # Examples
1433 ///
1434 /// ```
1435 /// use std::collections::VecDeque;
1436 ///
1437 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1438 /// for v in deque.range_mut(2..) {
1439 /// *v *= 2;
1440 /// }
1441 /// assert_eq!(deque, [1, 2, 6]);
1442 ///
1443 /// // A full range covers all contents
1444 /// for v in deque.range_mut(..) {
1445 /// *v *= 2;
1446 /// }
1447 /// assert_eq!(deque, [2, 4, 12]);
1448 /// ```
1449 #[inline]
1450 #[stable(feature = "deque_range", since = "1.51.0")]
1451 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1452 where
1453 R: RangeBounds<usize>,
1454 {
1455 let (a_range, b_range) = self.slice_ranges(range, self.len);
1456 // SAFETY: The ranges returned by `slice_ranges`
1457 // are valid ranges into the physical buffer, so
1458 // it's ok to pass them to `buffer_range` and
1459 // dereference the result.
1460 let a = unsafe { &mut *self.buffer_range(a_range) };
1461 let b = unsafe { &mut *self.buffer_range(b_range) };
1462 IterMut::new(a.iter_mut(), b.iter_mut())
1463 }
1464
1465 /// Removes the specified range from the deque in bulk, returning all
1466 /// removed elements as an iterator. If the iterator is dropped before
1467 /// being fully consumed, it drops the remaining removed elements.
1468 ///
1469 /// The returned iterator keeps a mutable borrow on the queue to optimize
1470 /// its implementation.
1471 ///
1472 ///
1473 /// # Panics
1474 ///
1475 /// Panics if the starting point is greater than the end point or if
1476 /// the end point is greater than the length of the deque.
1477 ///
1478 /// # Leaking
1479 ///
1480 /// If the returned iterator goes out of scope without being dropped (due to
1481 /// [`mem::forget`], for example), the deque may have lost and leaked
1482 /// elements arbitrarily, including elements outside the range.
1483 ///
1484 /// # Examples
1485 ///
1486 /// ```
1487 /// use std::collections::VecDeque;
1488 ///
1489 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1490 /// let drained = deque.drain(2..).collect::<VecDeque<_>>();
1491 /// assert_eq!(drained, [3]);
1492 /// assert_eq!(deque, [1, 2]);
1493 ///
1494 /// // A full range clears all contents, like `clear()` does
1495 /// deque.drain(..);
1496 /// assert!(deque.is_empty());
1497 /// ```
1498 #[inline]
1499 #[stable(feature = "drain", since = "1.6.0")]
1500 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1501 where
1502 R: RangeBounds<usize>,
1503 {
1504 // Memory safety
1505 //
1506 // When the Drain is first created, the source deque is shortened to
1507 // make sure no uninitialized or moved-from elements are accessible at
1508 // all if the Drain's destructor never gets to run.
1509 //
1510 // Drain will ptr::read out the values to remove.
1511 // When finished, the remaining data will be copied back to cover the hole,
1512 // and the head/tail values will be restored correctly.
1513 //
1514 let Range { start, end } = slice::range(range, ..self.len);
1515 let drain_start = start;
1516 let drain_len = end - start;
1517
1518 // The deque's elements are parted into three segments:
1519 // * 0 -> drain_start
1520 // * drain_start -> drain_start+drain_len
1521 // * drain_start+drain_len -> self.len
1522 //
1523 // H = self.head; T = self.head+self.len; t = drain_start+drain_len; h = drain_head
1524 //
1525 // We store drain_start as self.len, and drain_len and self.len as
1526 // drain_len and orig_len respectively on the Drain. This also
1527 // truncates the effective array such that if the Drain is leaked, we
1528 // have forgotten about the potentially moved values after the start of
1529 // the drain.
1530 //
1531 // H h t T
1532 // [. . . o o x x o o . . .]
1533 //
1534 // "forget" about the values after the start of the drain until after
1535 // the drain is complete and the Drain destructor is run.
1536
1537 unsafe { Drain::new(self, drain_start, drain_len) }
1538 }
1539
1540 /// Clears the deque, removing all values.
1541 ///
1542 /// # Examples
1543 ///
1544 /// ```
1545 /// use std::collections::VecDeque;
1546 ///
1547 /// let mut deque = VecDeque::new();
1548 /// deque.push_back(1);
1549 /// deque.clear();
1550 /// assert!(deque.is_empty());
1551 /// ```
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 #[inline]
1554 pub fn clear(&mut self) {
1555 self.truncate(0);
1556 // Not strictly necessary, but leaves things in a more consistent/predictable state.
1557 self.head = 0;
1558 }
1559
1560 /// Returns `true` if the deque contains an element equal to the
1561 /// given value.
1562 ///
1563 /// This operation is *O*(*n*).
1564 ///
1565 /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
1566 ///
1567 /// [`binary_search`]: VecDeque::binary_search
1568 ///
1569 /// # Examples
1570 ///
1571 /// ```
1572 /// use std::collections::VecDeque;
1573 ///
1574 /// let mut deque: VecDeque<u32> = VecDeque::new();
1575 ///
1576 /// deque.push_back(0);
1577 /// deque.push_back(1);
1578 ///
1579 /// assert_eq!(deque.contains(&1), true);
1580 /// assert_eq!(deque.contains(&10), false);
1581 /// ```
1582 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1583 pub fn contains(&self, x: &T) -> bool
1584 where
1585 T: PartialEq<T>,
1586 {
1587 let (a, b) = self.as_slices();
1588 a.contains(x) || b.contains(x)
1589 }
1590
1591 /// Provides a reference to the front element, or `None` if the deque is
1592 /// empty.
1593 ///
1594 /// # Examples
1595 ///
1596 /// ```
1597 /// use std::collections::VecDeque;
1598 ///
1599 /// let mut d = VecDeque::new();
1600 /// assert_eq!(d.front(), None);
1601 ///
1602 /// d.push_back(1);
1603 /// d.push_back(2);
1604 /// assert_eq!(d.front(), Some(&1));
1605 /// ```
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 #[rustc_confusables("first")]
1608 pub fn front(&self) -> Option<&T> {
1609 self.get(0)
1610 }
1611
1612 /// Provides a mutable reference to the front element, or `None` if the
1613 /// deque is empty.
1614 ///
1615 /// # Examples
1616 ///
1617 /// ```
1618 /// use std::collections::VecDeque;
1619 ///
1620 /// let mut d = VecDeque::new();
1621 /// assert_eq!(d.front_mut(), None);
1622 ///
1623 /// d.push_back(1);
1624 /// d.push_back(2);
1625 /// match d.front_mut() {
1626 /// Some(x) => *x = 9,
1627 /// None => (),
1628 /// }
1629 /// assert_eq!(d.front(), Some(&9));
1630 /// ```
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 pub fn front_mut(&mut self) -> Option<&mut T> {
1633 self.get_mut(0)
1634 }
1635
1636 /// Provides a reference to the back element, or `None` if the deque is
1637 /// empty.
1638 ///
1639 /// # Examples
1640 ///
1641 /// ```
1642 /// use std::collections::VecDeque;
1643 ///
1644 /// let mut d = VecDeque::new();
1645 /// assert_eq!(d.back(), None);
1646 ///
1647 /// d.push_back(1);
1648 /// d.push_back(2);
1649 /// assert_eq!(d.back(), Some(&2));
1650 /// ```
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 #[rustc_confusables("last")]
1653 pub fn back(&self) -> Option<&T> {
1654 self.get(self.len.wrapping_sub(1))
1655 }
1656
1657 /// Provides a mutable reference to the back element, or `None` if the
1658 /// deque is empty.
1659 ///
1660 /// # Examples
1661 ///
1662 /// ```
1663 /// use std::collections::VecDeque;
1664 ///
1665 /// let mut d = VecDeque::new();
1666 /// assert_eq!(d.back(), None);
1667 ///
1668 /// d.push_back(1);
1669 /// d.push_back(2);
1670 /// match d.back_mut() {
1671 /// Some(x) => *x = 9,
1672 /// None => (),
1673 /// }
1674 /// assert_eq!(d.back(), Some(&9));
1675 /// ```
1676 #[stable(feature = "rust1", since = "1.0.0")]
1677 pub fn back_mut(&mut self) -> Option<&mut T> {
1678 self.get_mut(self.len.wrapping_sub(1))
1679 }
1680
1681 /// Removes the first element and returns it, or `None` if the deque is
1682 /// empty.
1683 ///
1684 /// # Examples
1685 ///
1686 /// ```
1687 /// use std::collections::VecDeque;
1688 ///
1689 /// let mut d = VecDeque::new();
1690 /// d.push_back(1);
1691 /// d.push_back(2);
1692 ///
1693 /// assert_eq!(d.pop_front(), Some(1));
1694 /// assert_eq!(d.pop_front(), Some(2));
1695 /// assert_eq!(d.pop_front(), None);
1696 /// ```
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 pub fn pop_front(&mut self) -> Option<T> {
1699 if self.is_empty() {
1700 None
1701 } else {
1702 let old_head = self.head;
1703 self.head = self.to_physical_idx(1);
1704 self.len -= 1;
1705 unsafe {
1706 core::hint::assert_unchecked(self.len < self.capacity());
1707 Some(self.buffer_read(old_head))
1708 }
1709 }
1710 }
1711
1712 /// Removes the last element from the deque and returns it, or `None` if
1713 /// it is empty.
1714 ///
1715 /// # Examples
1716 ///
1717 /// ```
1718 /// use std::collections::VecDeque;
1719 ///
1720 /// let mut buf = VecDeque::new();
1721 /// assert_eq!(buf.pop_back(), None);
1722 /// buf.push_back(1);
1723 /// buf.push_back(3);
1724 /// assert_eq!(buf.pop_back(), Some(3));
1725 /// ```
1726 #[stable(feature = "rust1", since = "1.0.0")]
1727 pub fn pop_back(&mut self) -> Option<T> {
1728 if self.is_empty() {
1729 None
1730 } else {
1731 self.len -= 1;
1732 unsafe {
1733 core::hint::assert_unchecked(self.len < self.capacity());
1734 Some(self.buffer_read(self.to_physical_idx(self.len)))
1735 }
1736 }
1737 }
1738
1739 /// Removes and returns the first element from the deque if the predicate
1740 /// returns `true`, or [`None`] if the predicate returns false or the deque
1741 /// is empty (the predicate will not be called in that case).
1742 ///
1743 /// # Examples
1744 ///
1745 /// ```
1746 /// #![feature(vec_deque_pop_if)]
1747 /// use std::collections::VecDeque;
1748 ///
1749 /// let mut deque: VecDeque<i32> = vec![0, 1, 2, 3, 4].into();
1750 /// let pred = |x: &mut i32| *x % 2 == 0;
1751 ///
1752 /// assert_eq!(deque.pop_front_if(pred), Some(0));
1753 /// assert_eq!(deque, [1, 2, 3, 4]);
1754 /// assert_eq!(deque.pop_front_if(pred), None);
1755 /// ```
1756 #[unstable(feature = "vec_deque_pop_if", issue = "135889")]
1757 pub fn pop_front_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
1758 let first = self.front_mut()?;
1759 if predicate(first) { self.pop_front() } else { None }
1760 }
1761
1762 /// Removes and returns the last element from the deque if the predicate
1763 /// returns `true`, or [`None`] if the predicate returns false or the deque
1764 /// is empty (the predicate will not be called in that case).
1765 ///
1766 /// # Examples
1767 ///
1768 /// ```
1769 /// #![feature(vec_deque_pop_if)]
1770 /// use std::collections::VecDeque;
1771 ///
1772 /// let mut deque: VecDeque<i32> = vec![0, 1, 2, 3, 4].into();
1773 /// let pred = |x: &mut i32| *x % 2 == 0;
1774 ///
1775 /// assert_eq!(deque.pop_back_if(pred), Some(4));
1776 /// assert_eq!(deque, [0, 1, 2, 3]);
1777 /// assert_eq!(deque.pop_back_if(pred), None);
1778 /// ```
1779 #[unstable(feature = "vec_deque_pop_if", issue = "135889")]
1780 pub fn pop_back_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
1781 let first = self.back_mut()?;
1782 if predicate(first) { self.pop_back() } else { None }
1783 }
1784
1785 /// Prepends an element to the deque.
1786 ///
1787 /// # Examples
1788 ///
1789 /// ```
1790 /// use std::collections::VecDeque;
1791 ///
1792 /// let mut d = VecDeque::new();
1793 /// d.push_front(1);
1794 /// d.push_front(2);
1795 /// assert_eq!(d.front(), Some(&2));
1796 /// ```
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 #[track_caller]
1799 pub fn push_front(&mut self, value: T) {
1800 if self.is_full() {
1801 self.grow();
1802 }
1803
1804 self.head = self.wrap_sub(self.head, 1);
1805 self.len += 1;
1806
1807 unsafe {
1808 self.buffer_write(self.head, value);
1809 }
1810 }
1811
1812 /// Appends an element to the back of the deque.
1813 ///
1814 /// # Examples
1815 ///
1816 /// ```
1817 /// use std::collections::VecDeque;
1818 ///
1819 /// let mut buf = VecDeque::new();
1820 /// buf.push_back(1);
1821 /// buf.push_back(3);
1822 /// assert_eq!(3, *buf.back().unwrap());
1823 /// ```
1824 #[stable(feature = "rust1", since = "1.0.0")]
1825 #[rustc_confusables("push", "put", "append")]
1826 #[track_caller]
1827 pub fn push_back(&mut self, value: T) {
1828 if self.is_full() {
1829 self.grow();
1830 }
1831
1832 unsafe { self.buffer_write(self.to_physical_idx(self.len), value) }
1833 self.len += 1;
1834 }
1835
1836 #[inline]
1837 fn is_contiguous(&self) -> bool {
1838 // Do the calculation like this to avoid overflowing if len + head > usize::MAX
1839 self.head <= self.capacity() - self.len
1840 }
1841
1842 /// Removes an element from anywhere in the deque and returns it,
1843 /// replacing it with the first element.
1844 ///
1845 /// This does not preserve ordering, but is *O*(1).
1846 ///
1847 /// Returns `None` if `index` is out of bounds.
1848 ///
1849 /// Element at index 0 is the front of the queue.
1850 ///
1851 /// # Examples
1852 ///
1853 /// ```
1854 /// use std::collections::VecDeque;
1855 ///
1856 /// let mut buf = VecDeque::new();
1857 /// assert_eq!(buf.swap_remove_front(0), None);
1858 /// buf.push_back(1);
1859 /// buf.push_back(2);
1860 /// buf.push_back(3);
1861 /// assert_eq!(buf, [1, 2, 3]);
1862 ///
1863 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1864 /// assert_eq!(buf, [2, 1]);
1865 /// ```
1866 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1867 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1868 let length = self.len;
1869 if index < length && index != 0 {
1870 self.swap(index, 0);
1871 } else if index >= length {
1872 return None;
1873 }
1874 self.pop_front()
1875 }
1876
1877 /// Removes an element from anywhere in the deque and returns it,
1878 /// replacing it with the last element.
1879 ///
1880 /// This does not preserve ordering, but is *O*(1).
1881 ///
1882 /// Returns `None` if `index` is out of bounds.
1883 ///
1884 /// Element at index 0 is the front of the queue.
1885 ///
1886 /// # Examples
1887 ///
1888 /// ```
1889 /// use std::collections::VecDeque;
1890 ///
1891 /// let mut buf = VecDeque::new();
1892 /// assert_eq!(buf.swap_remove_back(0), None);
1893 /// buf.push_back(1);
1894 /// buf.push_back(2);
1895 /// buf.push_back(3);
1896 /// assert_eq!(buf, [1, 2, 3]);
1897 ///
1898 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1899 /// assert_eq!(buf, [3, 2]);
1900 /// ```
1901 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1902 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1903 let length = self.len;
1904 if length > 0 && index < length - 1 {
1905 self.swap(index, length - 1);
1906 } else if index >= length {
1907 return None;
1908 }
1909 self.pop_back()
1910 }
1911
1912 /// Inserts an element at `index` within the deque, shifting all elements
1913 /// with indices greater than or equal to `index` towards the back.
1914 ///
1915 /// Element at index 0 is the front of the queue.
1916 ///
1917 /// # Panics
1918 ///
1919 /// Panics if `index` is strictly greater than deque's length
1920 ///
1921 /// # Examples
1922 ///
1923 /// ```
1924 /// use std::collections::VecDeque;
1925 ///
1926 /// let mut vec_deque = VecDeque::new();
1927 /// vec_deque.push_back('a');
1928 /// vec_deque.push_back('b');
1929 /// vec_deque.push_back('c');
1930 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1931 ///
1932 /// vec_deque.insert(1, 'd');
1933 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1934 ///
1935 /// vec_deque.insert(4, 'e');
1936 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c', 'e']);
1937 /// ```
1938 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1939 #[track_caller]
1940 pub fn insert(&mut self, index: usize, value: T) {
1941 assert!(index <= self.len(), "index out of bounds");
1942 if self.is_full() {
1943 self.grow();
1944 }
1945
1946 let k = self.len - index;
1947 if k < index {
1948 // `index + 1` can't overflow, because if index was usize::MAX, then either the
1949 // assert would've failed, or the deque would've tried to grow past usize::MAX
1950 // and panicked.
1951 unsafe {
1952 // see `remove()` for explanation why this wrap_copy() call is safe.
1953 self.wrap_copy(self.to_physical_idx(index), self.to_physical_idx(index + 1), k);
1954 self.buffer_write(self.to_physical_idx(index), value);
1955 self.len += 1;
1956 }
1957 } else {
1958 let old_head = self.head;
1959 self.head = self.wrap_sub(self.head, 1);
1960 unsafe {
1961 self.wrap_copy(old_head, self.head, index);
1962 self.buffer_write(self.to_physical_idx(index), value);
1963 self.len += 1;
1964 }
1965 }
1966 }
1967
1968 /// Removes and returns the element at `index` from the deque.
1969 /// Whichever end is closer to the removal point will be moved to make
1970 /// room, and all the affected elements will be moved to new positions.
1971 /// Returns `None` if `index` is out of bounds.
1972 ///
1973 /// Element at index 0 is the front of the queue.
1974 ///
1975 /// # Examples
1976 ///
1977 /// ```
1978 /// use std::collections::VecDeque;
1979 ///
1980 /// let mut buf = VecDeque::new();
1981 /// buf.push_back('a');
1982 /// buf.push_back('b');
1983 /// buf.push_back('c');
1984 /// assert_eq!(buf, ['a', 'b', 'c']);
1985 ///
1986 /// assert_eq!(buf.remove(1), Some('b'));
1987 /// assert_eq!(buf, ['a', 'c']);
1988 /// ```
1989 #[stable(feature = "rust1", since = "1.0.0")]
1990 #[rustc_confusables("delete", "take")]
1991 pub fn remove(&mut self, index: usize) -> Option<T> {
1992 if self.len <= index {
1993 return None;
1994 }
1995
1996 let wrapped_idx = self.to_physical_idx(index);
1997
1998 let elem = unsafe { Some(self.buffer_read(wrapped_idx)) };
1999
2000 let k = self.len - index - 1;
2001 // safety: due to the nature of the if-condition, whichever wrap_copy gets called,
2002 // its length argument will be at most `self.len / 2`, so there can't be more than
2003 // one overlapping area.
2004 if k < index {
2005 unsafe { self.wrap_copy(self.wrap_add(wrapped_idx, 1), wrapped_idx, k) };
2006 self.len -= 1;
2007 } else {
2008 let old_head = self.head;
2009 self.head = self.to_physical_idx(1);
2010 unsafe { self.wrap_copy(old_head, self.head, index) };
2011 self.len -= 1;
2012 }
2013
2014 elem
2015 }
2016
2017 /// Splits the deque into two at the given index.
2018 ///
2019 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2020 /// and the returned deque contains elements `[at, len)`.
2021 ///
2022 /// Note that the capacity of `self` does not change.
2023 ///
2024 /// Element at index 0 is the front of the queue.
2025 ///
2026 /// # Panics
2027 ///
2028 /// Panics if `at > len`.
2029 ///
2030 /// # Examples
2031 ///
2032 /// ```
2033 /// use std::collections::VecDeque;
2034 ///
2035 /// let mut buf: VecDeque<_> = ['a', 'b', 'c'].into();
2036 /// let buf2 = buf.split_off(1);
2037 /// assert_eq!(buf, ['a']);
2038 /// assert_eq!(buf2, ['b', 'c']);
2039 /// ```
2040 #[inline]
2041 #[must_use = "use `.truncate()` if you don't need the other half"]
2042 #[stable(feature = "split_off", since = "1.4.0")]
2043 #[track_caller]
2044 pub fn split_off(&mut self, at: usize) -> Self
2045 where
2046 A: Clone,
2047 {
2048 let len = self.len;
2049 assert!(at <= len, "`at` out of bounds");
2050
2051 let other_len = len - at;
2052 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2053
2054 unsafe {
2055 let (first_half, second_half) = self.as_slices();
2056
2057 let first_len = first_half.len();
2058 let second_len = second_half.len();
2059 if at < first_len {
2060 // `at` lies in the first half.
2061 let amount_in_first = first_len - at;
2062
2063 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2064
2065 // just take all of the second half.
2066 ptr::copy_nonoverlapping(
2067 second_half.as_ptr(),
2068 other.ptr().add(amount_in_first),
2069 second_len,
2070 );
2071 } else {
2072 // `at` lies in the second half, need to factor in the elements we skipped
2073 // in the first half.
2074 let offset = at - first_len;
2075 let amount_in_second = second_len - offset;
2076 ptr::copy_nonoverlapping(
2077 second_half.as_ptr().add(offset),
2078 other.ptr(),
2079 amount_in_second,
2080 );
2081 }
2082 }
2083
2084 // Cleanup where the ends of the buffers are
2085 self.len = at;
2086 other.len = other_len;
2087
2088 other
2089 }
2090
2091 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2092 ///
2093 /// # Panics
2094 ///
2095 /// Panics if the new number of elements in self overflows a `usize`.
2096 ///
2097 /// # Examples
2098 ///
2099 /// ```
2100 /// use std::collections::VecDeque;
2101 ///
2102 /// let mut buf: VecDeque<_> = [1, 2].into();
2103 /// let mut buf2: VecDeque<_> = [3, 4].into();
2104 /// buf.append(&mut buf2);
2105 /// assert_eq!(buf, [1, 2, 3, 4]);
2106 /// assert_eq!(buf2, []);
2107 /// ```
2108 #[inline]
2109 #[stable(feature = "append", since = "1.4.0")]
2110 #[track_caller]
2111 pub fn append(&mut self, other: &mut Self) {
2112 if T::IS_ZST {
2113 self.len = self.len.checked_add(other.len).expect("capacity overflow");
2114 other.len = 0;
2115 other.head = 0;
2116 return;
2117 }
2118
2119 self.reserve(other.len);
2120 unsafe {
2121 let (left, right) = other.as_slices();
2122 self.copy_slice(self.to_physical_idx(self.len), left);
2123 // no overflow, because self.capacity() >= old_cap + left.len() >= self.len + left.len()
2124 self.copy_slice(self.to_physical_idx(self.len + left.len()), right);
2125 }
2126 // SAFETY: Update pointers after copying to avoid leaving doppelganger
2127 // in case of panics.
2128 self.len += other.len;
2129 // Now that we own its values, forget everything in `other`.
2130 other.len = 0;
2131 other.head = 0;
2132 }
2133
2134 /// Retains only the elements specified by the predicate.
2135 ///
2136 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2137 /// This method operates in place, visiting each element exactly once in the
2138 /// original order, and preserves the order of the retained elements.
2139 ///
2140 /// # Examples
2141 ///
2142 /// ```
2143 /// use std::collections::VecDeque;
2144 ///
2145 /// let mut buf = VecDeque::new();
2146 /// buf.extend(1..5);
2147 /// buf.retain(|&x| x % 2 == 0);
2148 /// assert_eq!(buf, [2, 4]);
2149 /// ```
2150 ///
2151 /// Because the elements are visited exactly once in the original order,
2152 /// external state may be used to decide which elements to keep.
2153 ///
2154 /// ```
2155 /// use std::collections::VecDeque;
2156 ///
2157 /// let mut buf = VecDeque::new();
2158 /// buf.extend(1..6);
2159 ///
2160 /// let keep = [false, true, true, false, true];
2161 /// let mut iter = keep.iter();
2162 /// buf.retain(|_| *iter.next().unwrap());
2163 /// assert_eq!(buf, [2, 3, 5]);
2164 /// ```
2165 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2166 pub fn retain<F>(&mut self, mut f: F)
2167 where
2168 F: FnMut(&T) -> bool,
2169 {
2170 self.retain_mut(|elem| f(elem));
2171 }
2172
2173 /// Retains only the elements specified by the predicate.
2174 ///
2175 /// In other words, remove all elements `e` for which `f(&mut e)` returns false.
2176 /// This method operates in place, visiting each element exactly once in the
2177 /// original order, and preserves the order of the retained elements.
2178 ///
2179 /// # Examples
2180 ///
2181 /// ```
2182 /// use std::collections::VecDeque;
2183 ///
2184 /// let mut buf = VecDeque::new();
2185 /// buf.extend(1..5);
2186 /// buf.retain_mut(|x| if *x % 2 == 0 {
2187 /// *x += 1;
2188 /// true
2189 /// } else {
2190 /// false
2191 /// });
2192 /// assert_eq!(buf, [3, 5]);
2193 /// ```
2194 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2195 pub fn retain_mut<F>(&mut self, mut f: F)
2196 where
2197 F: FnMut(&mut T) -> bool,
2198 {
2199 let len = self.len;
2200 let mut idx = 0;
2201 let mut cur = 0;
2202
2203 // Stage 1: All values are retained.
2204 while cur < len {
2205 if !f(&mut self[cur]) {
2206 cur += 1;
2207 break;
2208 }
2209 cur += 1;
2210 idx += 1;
2211 }
2212 // Stage 2: Swap retained value into current idx.
2213 while cur < len {
2214 if !f(&mut self[cur]) {
2215 cur += 1;
2216 continue;
2217 }
2218
2219 self.swap(idx, cur);
2220 cur += 1;
2221 idx += 1;
2222 }
2223 // Stage 3: Truncate all values after idx.
2224 if cur != idx {
2225 self.truncate(idx);
2226 }
2227 }
2228
2229 // Double the buffer size. This method is inline(never), so we expect it to only
2230 // be called in cold paths.
2231 // This may panic or abort
2232 #[inline(never)]
2233 #[track_caller]
2234 fn grow(&mut self) {
2235 // Extend or possibly remove this assertion when valid use-cases for growing the
2236 // buffer without it being full emerge
2237 debug_assert!(self.is_full());
2238 let old_cap = self.capacity();
2239 self.buf.grow_one();
2240 unsafe {
2241 self.handle_capacity_increase(old_cap);
2242 }
2243 debug_assert!(!self.is_full());
2244 }
2245
2246 /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2247 /// either by removing excess elements from the back or by appending
2248 /// elements generated by calling `generator` to the back.
2249 ///
2250 /// # Examples
2251 ///
2252 /// ```
2253 /// use std::collections::VecDeque;
2254 ///
2255 /// let mut buf = VecDeque::new();
2256 /// buf.push_back(5);
2257 /// buf.push_back(10);
2258 /// buf.push_back(15);
2259 /// assert_eq!(buf, [5, 10, 15]);
2260 ///
2261 /// buf.resize_with(5, Default::default);
2262 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2263 ///
2264 /// buf.resize_with(2, || unreachable!());
2265 /// assert_eq!(buf, [5, 10]);
2266 ///
2267 /// let mut state = 100;
2268 /// buf.resize_with(5, || { state += 1; state });
2269 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2270 /// ```
2271 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2272 #[track_caller]
2273 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2274 let len = self.len;
2275
2276 if new_len > len {
2277 self.extend(repeat_with(generator).take(new_len - len))
2278 } else {
2279 self.truncate(new_len);
2280 }
2281 }
2282
2283 /// Rearranges the internal storage of this deque so it is one contiguous
2284 /// slice, which is then returned.
2285 ///
2286 /// This method does not allocate and does not change the order of the
2287 /// inserted elements. As it returns a mutable slice, this can be used to
2288 /// sort a deque.
2289 ///
2290 /// Once the internal storage is contiguous, the [`as_slices`] and
2291 /// [`as_mut_slices`] methods will return the entire contents of the
2292 /// deque in a single slice.
2293 ///
2294 /// [`as_slices`]: VecDeque::as_slices
2295 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2296 ///
2297 /// # Examples
2298 ///
2299 /// Sorting the content of a deque.
2300 ///
2301 /// ```
2302 /// use std::collections::VecDeque;
2303 ///
2304 /// let mut buf = VecDeque::with_capacity(15);
2305 ///
2306 /// buf.push_back(2);
2307 /// buf.push_back(1);
2308 /// buf.push_front(3);
2309 ///
2310 /// // sorting the deque
2311 /// buf.make_contiguous().sort();
2312 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2313 ///
2314 /// // sorting it in reverse order
2315 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2316 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2317 /// ```
2318 ///
2319 /// Getting immutable access to the contiguous slice.
2320 ///
2321 /// ```rust
2322 /// use std::collections::VecDeque;
2323 ///
2324 /// let mut buf = VecDeque::new();
2325 ///
2326 /// buf.push_back(2);
2327 /// buf.push_back(1);
2328 /// buf.push_front(3);
2329 ///
2330 /// buf.make_contiguous();
2331 /// if let (slice, &[]) = buf.as_slices() {
2332 /// // we can now be sure that `slice` contains all elements of the deque,
2333 /// // while still having immutable access to `buf`.
2334 /// assert_eq!(buf.len(), slice.len());
2335 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2336 /// }
2337 /// ```
2338 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2339 pub fn make_contiguous(&mut self) -> &mut [T] {
2340 if T::IS_ZST {
2341 self.head = 0;
2342 }
2343
2344 if self.is_contiguous() {
2345 unsafe { return slice::from_raw_parts_mut(self.ptr().add(self.head), self.len) }
2346 }
2347
2348 let &mut Self { head, len, .. } = self;
2349 let ptr = self.ptr();
2350 let cap = self.capacity();
2351
2352 let free = cap - len;
2353 let head_len = cap - head;
2354 let tail = len - head_len;
2355 let tail_len = tail;
2356
2357 if free >= head_len {
2358 // there is enough free space to copy the head in one go,
2359 // this means that we first shift the tail backwards, and then
2360 // copy the head to the correct position.
2361 //
2362 // from: DEFGH....ABC
2363 // to: ABCDEFGH....
2364 unsafe {
2365 self.copy(0, head_len, tail_len);
2366 // ...DEFGH.ABC
2367 self.copy_nonoverlapping(head, 0, head_len);
2368 // ABCDEFGH....
2369 }
2370
2371 self.head = 0;
2372 } else if free >= tail_len {
2373 // there is enough free space to copy the tail in one go,
2374 // this means that we first shift the head forwards, and then
2375 // copy the tail to the correct position.
2376 //
2377 // from: FGH....ABCDE
2378 // to: ...ABCDEFGH.
2379 unsafe {
2380 self.copy(head, tail, head_len);
2381 // FGHABCDE....
2382 self.copy_nonoverlapping(0, tail + head_len, tail_len);
2383 // ...ABCDEFGH.
2384 }
2385
2386 self.head = tail;
2387 } else {
2388 // `free` is smaller than both `head_len` and `tail_len`.
2389 // the general algorithm for this first moves the slices
2390 // right next to each other and then uses `slice::rotate`
2391 // to rotate them into place:
2392 //
2393 // initially: HIJK..ABCDEFG
2394 // step 1: ..HIJKABCDEFG
2395 // step 2: ..ABCDEFGHIJK
2396 //
2397 // or:
2398 //
2399 // initially: FGHIJK..ABCDE
2400 // step 1: FGHIJKABCDE..
2401 // step 2: ABCDEFGHIJK..
2402
2403 // pick the shorter of the 2 slices to reduce the amount
2404 // of memory that needs to be moved around.
2405 if head_len > tail_len {
2406 // tail is shorter, so:
2407 // 1. copy tail forwards
2408 // 2. rotate used part of the buffer
2409 // 3. update head to point to the new beginning (which is just `free`)
2410
2411 unsafe {
2412 // if there is no free space in the buffer, then the slices are already
2413 // right next to each other and we don't need to move any memory.
2414 if free != 0 {
2415 // because we only move the tail forward as much as there's free space
2416 // behind it, we don't overwrite any elements of the head slice, and
2417 // the slices end up right next to each other.
2418 self.copy(0, free, tail_len);
2419 }
2420
2421 // We just copied the tail right next to the head slice,
2422 // so all of the elements in the range are initialized
2423 let slice = &mut *self.buffer_range(free..self.capacity());
2424
2425 // because the deque wasn't contiguous, we know that `tail_len < self.len == slice.len()`,
2426 // so this will never panic.
2427 slice.rotate_left(tail_len);
2428
2429 // the used part of the buffer now is `free..self.capacity()`, so set
2430 // `head` to the beginning of that range.
2431 self.head = free;
2432 }
2433 } else {
2434 // head is shorter so:
2435 // 1. copy head backwards
2436 // 2. rotate used part of the buffer
2437 // 3. update head to point to the new beginning (which is the beginning of the buffer)
2438
2439 unsafe {
2440 // if there is no free space in the buffer, then the slices are already
2441 // right next to each other and we don't need to move any memory.
2442 if free != 0 {
2443 // copy the head slice to lie right behind the tail slice.
2444 self.copy(self.head, tail_len, head_len);
2445 }
2446
2447 // because we copied the head slice so that both slices lie right
2448 // next to each other, all the elements in the range are initialized.
2449 let slice = &mut *self.buffer_range(0..self.len);
2450
2451 // because the deque wasn't contiguous, we know that `head_len < self.len == slice.len()`
2452 // so this will never panic.
2453 slice.rotate_right(head_len);
2454
2455 // the used part of the buffer now is `0..self.len`, so set
2456 // `head` to the beginning of that range.
2457 self.head = 0;
2458 }
2459 }
2460 }
2461
2462 unsafe { slice::from_raw_parts_mut(ptr.add(self.head), self.len) }
2463 }
2464
2465 /// Rotates the double-ended queue `n` places to the left.
2466 ///
2467 /// Equivalently,
2468 /// - Rotates item `n` into the first position.
2469 /// - Pops the first `n` items and pushes them to the end.
2470 /// - Rotates `len() - n` places to the right.
2471 ///
2472 /// # Panics
2473 ///
2474 /// If `n` is greater than `len()`. Note that `n == len()`
2475 /// does _not_ panic and is a no-op rotation.
2476 ///
2477 /// # Complexity
2478 ///
2479 /// Takes `*O*(min(n, len() - n))` time and no extra space.
2480 ///
2481 /// # Examples
2482 ///
2483 /// ```
2484 /// use std::collections::VecDeque;
2485 ///
2486 /// let mut buf: VecDeque<_> = (0..10).collect();
2487 ///
2488 /// buf.rotate_left(3);
2489 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2490 ///
2491 /// for i in 1..10 {
2492 /// assert_eq!(i * 3 % 10, buf[0]);
2493 /// buf.rotate_left(3);
2494 /// }
2495 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2496 /// ```
2497 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2498 pub fn rotate_left(&mut self, n: usize) {
2499 assert!(n <= self.len());
2500 let k = self.len - n;
2501 if n <= k {
2502 unsafe { self.rotate_left_inner(n) }
2503 } else {
2504 unsafe { self.rotate_right_inner(k) }
2505 }
2506 }
2507
2508 /// Rotates the double-ended queue `n` places to the right.
2509 ///
2510 /// Equivalently,
2511 /// - Rotates the first item into position `n`.
2512 /// - Pops the last `n` items and pushes them to the front.
2513 /// - Rotates `len() - n` places to the left.
2514 ///
2515 /// # Panics
2516 ///
2517 /// If `n` is greater than `len()`. Note that `n == len()`
2518 /// does _not_ panic and is a no-op rotation.
2519 ///
2520 /// # Complexity
2521 ///
2522 /// Takes `*O*(min(n, len() - n))` time and no extra space.
2523 ///
2524 /// # Examples
2525 ///
2526 /// ```
2527 /// use std::collections::VecDeque;
2528 ///
2529 /// let mut buf: VecDeque<_> = (0..10).collect();
2530 ///
2531 /// buf.rotate_right(3);
2532 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2533 ///
2534 /// for i in 1..10 {
2535 /// assert_eq!(0, buf[i * 3 % 10]);
2536 /// buf.rotate_right(3);
2537 /// }
2538 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2539 /// ```
2540 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2541 pub fn rotate_right(&mut self, n: usize) {
2542 assert!(n <= self.len());
2543 let k = self.len - n;
2544 if n <= k {
2545 unsafe { self.rotate_right_inner(n) }
2546 } else {
2547 unsafe { self.rotate_left_inner(k) }
2548 }
2549 }
2550
2551 // SAFETY: the following two methods require that the rotation amount
2552 // be less than half the length of the deque.
2553 //
2554 // `wrap_copy` requires that `min(x, capacity() - x) + copy_len <= capacity()`,
2555 // but then `min` is never more than half the capacity, regardless of x,
2556 // so it's sound to call here because we're calling with something
2557 // less than half the length, which is never above half the capacity.
2558
2559 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2560 debug_assert!(mid * 2 <= self.len());
2561 unsafe {
2562 self.wrap_copy(self.head, self.to_physical_idx(self.len), mid);
2563 }
2564 self.head = self.to_physical_idx(mid);
2565 }
2566
2567 unsafe fn rotate_right_inner(&mut self, k: usize) {
2568 debug_assert!(k * 2 <= self.len());
2569 self.head = self.wrap_sub(self.head, k);
2570 unsafe {
2571 self.wrap_copy(self.to_physical_idx(self.len), self.head, k);
2572 }
2573 }
2574
2575 /// Binary searches this `VecDeque` for a given element.
2576 /// If the `VecDeque` is not sorted, the returned result is unspecified and
2577 /// meaningless.
2578 ///
2579 /// If the value is found then [`Result::Ok`] is returned, containing the
2580 /// index of the matching element. If there are multiple matches, then any
2581 /// one of the matches could be returned. If the value is not found then
2582 /// [`Result::Err`] is returned, containing the index where a matching
2583 /// element could be inserted while maintaining sorted order.
2584 ///
2585 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2586 ///
2587 /// [`binary_search_by`]: VecDeque::binary_search_by
2588 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2589 /// [`partition_point`]: VecDeque::partition_point
2590 ///
2591 /// # Examples
2592 ///
2593 /// Looks up a series of four elements. The first is found, with a
2594 /// uniquely determined position; the second and third are not
2595 /// found; the fourth could match any position in `[1, 4]`.
2596 ///
2597 /// ```
2598 /// use std::collections::VecDeque;
2599 ///
2600 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2601 ///
2602 /// assert_eq!(deque.binary_search(&13), Ok(9));
2603 /// assert_eq!(deque.binary_search(&4), Err(7));
2604 /// assert_eq!(deque.binary_search(&100), Err(13));
2605 /// let r = deque.binary_search(&1);
2606 /// assert!(matches!(r, Ok(1..=4)));
2607 /// ```
2608 ///
2609 /// If you want to insert an item to a sorted deque, while maintaining
2610 /// sort order, consider using [`partition_point`]:
2611 ///
2612 /// ```
2613 /// use std::collections::VecDeque;
2614 ///
2615 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2616 /// let num = 42;
2617 /// let idx = deque.partition_point(|&x| x <= num);
2618 /// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
2619 /// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` may allow `insert`
2620 /// // to shift less elements.
2621 /// deque.insert(idx, num);
2622 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2623 /// ```
2624 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2625 #[inline]
2626 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2627 where
2628 T: Ord,
2629 {
2630 self.binary_search_by(|e| e.cmp(x))
2631 }
2632
2633 /// Binary searches this `VecDeque` with a comparator function.
2634 ///
2635 /// The comparator function should return an order code that indicates
2636 /// whether its argument is `Less`, `Equal` or `Greater` the desired
2637 /// target.
2638 /// If the `VecDeque` is not sorted or if the comparator function does not
2639 /// implement an order consistent with the sort order of the underlying
2640 /// `VecDeque`, the returned result is unspecified and meaningless.
2641 ///
2642 /// If the value is found then [`Result::Ok`] is returned, containing the
2643 /// index of the matching element. If there are multiple matches, then any
2644 /// one of the matches could be returned. If the value is not found then
2645 /// [`Result::Err`] is returned, containing the index where a matching
2646 /// element could be inserted while maintaining sorted order.
2647 ///
2648 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2649 ///
2650 /// [`binary_search`]: VecDeque::binary_search
2651 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2652 /// [`partition_point`]: VecDeque::partition_point
2653 ///
2654 /// # Examples
2655 ///
2656 /// Looks up a series of four elements. The first is found, with a
2657 /// uniquely determined position; the second and third are not
2658 /// found; the fourth could match any position in `[1, 4]`.
2659 ///
2660 /// ```
2661 /// use std::collections::VecDeque;
2662 ///
2663 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2664 ///
2665 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2666 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2667 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2668 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2669 /// assert!(matches!(r, Ok(1..=4)));
2670 /// ```
2671 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2672 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2673 where
2674 F: FnMut(&'a T) -> Ordering,
2675 {
2676 let (front, back) = self.as_slices();
2677 let cmp_back = back.first().map(|elem| f(elem));
2678
2679 if let Some(Ordering::Equal) = cmp_back {
2680 Ok(front.len())
2681 } else if let Some(Ordering::Less) = cmp_back {
2682 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2683 } else {
2684 front.binary_search_by(f)
2685 }
2686 }
2687
2688 /// Binary searches this `VecDeque` with a key extraction function.
2689 ///
2690 /// Assumes that the deque is sorted by the key, for instance with
2691 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2692 /// If the deque is not sorted by the key, the returned result is
2693 /// unspecified and meaningless.
2694 ///
2695 /// If the value is found then [`Result::Ok`] is returned, containing the
2696 /// index of the matching element. If there are multiple matches, then any
2697 /// one of the matches could be returned. If the value is not found then
2698 /// [`Result::Err`] is returned, containing the index where a matching
2699 /// element could be inserted while maintaining sorted order.
2700 ///
2701 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2702 ///
2703 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2704 /// [`binary_search`]: VecDeque::binary_search
2705 /// [`binary_search_by`]: VecDeque::binary_search_by
2706 /// [`partition_point`]: VecDeque::partition_point
2707 ///
2708 /// # Examples
2709 ///
2710 /// Looks up a series of four elements in a slice of pairs sorted by
2711 /// their second elements. The first is found, with a uniquely
2712 /// determined position; the second and third are not found; the
2713 /// fourth could match any position in `[1, 4]`.
2714 ///
2715 /// ```
2716 /// use std::collections::VecDeque;
2717 ///
2718 /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
2719 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2720 /// (1, 21), (2, 34), (4, 55)].into();
2721 ///
2722 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2723 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2724 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2725 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2726 /// assert!(matches!(r, Ok(1..=4)));
2727 /// ```
2728 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2729 #[inline]
2730 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2731 where
2732 F: FnMut(&'a T) -> B,
2733 B: Ord,
2734 {
2735 self.binary_search_by(|k| f(k).cmp(b))
2736 }
2737
2738 /// Returns the index of the partition point according to the given predicate
2739 /// (the index of the first element of the second partition).
2740 ///
2741 /// The deque is assumed to be partitioned according to the given predicate.
2742 /// This means that all elements for which the predicate returns true are at the start of the deque
2743 /// and all elements for which the predicate returns false are at the end.
2744 /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
2745 /// (all odd numbers are at the start, all even at the end).
2746 ///
2747 /// If the deque is not partitioned, the returned result is unspecified and meaningless,
2748 /// as this method performs a kind of binary search.
2749 ///
2750 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2751 ///
2752 /// [`binary_search`]: VecDeque::binary_search
2753 /// [`binary_search_by`]: VecDeque::binary_search_by
2754 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2755 ///
2756 /// # Examples
2757 ///
2758 /// ```
2759 /// use std::collections::VecDeque;
2760 ///
2761 /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
2762 /// let i = deque.partition_point(|&x| x < 5);
2763 ///
2764 /// assert_eq!(i, 4);
2765 /// assert!(deque.iter().take(i).all(|&x| x < 5));
2766 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2767 /// ```
2768 ///
2769 /// If you want to insert an item to a sorted deque, while maintaining
2770 /// sort order:
2771 ///
2772 /// ```
2773 /// use std::collections::VecDeque;
2774 ///
2775 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2776 /// let num = 42;
2777 /// let idx = deque.partition_point(|&x| x < num);
2778 /// deque.insert(idx, num);
2779 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2780 /// ```
2781 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2782 pub fn partition_point<P>(&self, mut pred: P) -> usize
2783 where
2784 P: FnMut(&T) -> bool,
2785 {
2786 let (front, back) = self.as_slices();
2787
2788 if let Some(true) = back.first().map(|v| pred(v)) {
2789 back.partition_point(pred) + front.len()
2790 } else {
2791 front.partition_point(pred)
2792 }
2793 }
2794}
2795
2796impl<T: Clone, A: Allocator> VecDeque<T, A> {
2797 /// Modifies the deque in-place so that `len()` is equal to new_len,
2798 /// either by removing excess elements from the back or by appending clones of `value`
2799 /// to the back.
2800 ///
2801 /// # Examples
2802 ///
2803 /// ```
2804 /// use std::collections::VecDeque;
2805 ///
2806 /// let mut buf = VecDeque::new();
2807 /// buf.push_back(5);
2808 /// buf.push_back(10);
2809 /// buf.push_back(15);
2810 /// assert_eq!(buf, [5, 10, 15]);
2811 ///
2812 /// buf.resize(2, 0);
2813 /// assert_eq!(buf, [5, 10]);
2814 ///
2815 /// buf.resize(5, 20);
2816 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2817 /// ```
2818 #[stable(feature = "deque_extras", since = "1.16.0")]
2819 #[track_caller]
2820 pub fn resize(&mut self, new_len: usize, value: T) {
2821 if new_len > self.len() {
2822 let extra = new_len - self.len();
2823 self.extend(repeat_n(value, extra))
2824 } else {
2825 self.truncate(new_len);
2826 }
2827 }
2828}
2829
2830/// Returns the index in the underlying buffer for a given logical element index.
2831#[inline]
2832fn wrap_index(logical_index: usize, capacity: usize) -> usize {
2833 debug_assert!(
2834 (logical_index == 0 && capacity == 0)
2835 || logical_index < capacity
2836 || (logical_index - capacity) < capacity
2837 );
2838 if logical_index >= capacity { logical_index - capacity } else { logical_index }
2839}
2840
2841#[stable(feature = "rust1", since = "1.0.0")]
2842impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
2843 fn eq(&self, other: &Self) -> bool {
2844 if self.len != other.len() {
2845 return false;
2846 }
2847 let (sa, sb) = self.as_slices();
2848 let (oa, ob) = other.as_slices();
2849 if sa.len() == oa.len() {
2850 sa == oa && sb == ob
2851 } else if sa.len() < oa.len() {
2852 // Always divisible in three sections, for example:
2853 // self: [a b c|d e f]
2854 // other: [0 1 2 3|4 5]
2855 // front = 3, mid = 1,
2856 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2857 let front = sa.len();
2858 let mid = oa.len() - front;
2859
2860 let (oa_front, oa_mid) = oa.split_at(front);
2861 let (sb_mid, sb_back) = sb.split_at(mid);
2862 debug_assert_eq!(sa.len(), oa_front.len());
2863 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2864 debug_assert_eq!(sb_back.len(), ob.len());
2865 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2866 } else {
2867 let front = oa.len();
2868 let mid = sa.len() - front;
2869
2870 let (sa_front, sa_mid) = sa.split_at(front);
2871 let (ob_mid, ob_back) = ob.split_at(mid);
2872 debug_assert_eq!(sa_front.len(), oa.len());
2873 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2874 debug_assert_eq!(sb.len(), ob_back.len());
2875 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2876 }
2877 }
2878}
2879
2880#[stable(feature = "rust1", since = "1.0.0")]
2881impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
2882
2883__impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2884__impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2885__impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2886__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2887__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2888__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2889
2890#[stable(feature = "rust1", since = "1.0.0")]
2891impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
2892 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2893 self.iter().partial_cmp(other.iter())
2894 }
2895}
2896
2897#[stable(feature = "rust1", since = "1.0.0")]
2898impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
2899 #[inline]
2900 fn cmp(&self, other: &Self) -> Ordering {
2901 self.iter().cmp(other.iter())
2902 }
2903}
2904
2905#[stable(feature = "rust1", since = "1.0.0")]
2906impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
2907 fn hash<H: Hasher>(&self, state: &mut H) {
2908 state.write_length_prefix(self.len);
2909 // It's not possible to use Hash::hash_slice on slices
2910 // returned by as_slices method as their length can vary
2911 // in otherwise identical deques.
2912 //
2913 // Hasher only guarantees equivalence for the exact same
2914 // set of calls to its methods.
2915 self.iter().for_each(|elem| elem.hash(state));
2916 }
2917}
2918
2919#[stable(feature = "rust1", since = "1.0.0")]
2920impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
2921 type Output = T;
2922
2923 #[inline]
2924 fn index(&self, index: usize) -> &T {
2925 self.get(index).expect("Out of bounds access")
2926 }
2927}
2928
2929#[stable(feature = "rust1", since = "1.0.0")]
2930impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
2931 #[inline]
2932 fn index_mut(&mut self, index: usize) -> &mut T {
2933 self.get_mut(index).expect("Out of bounds access")
2934 }
2935}
2936
2937#[stable(feature = "rust1", since = "1.0.0")]
2938impl<T> FromIterator<T> for VecDeque<T> {
2939 #[track_caller]
2940 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
2941 SpecFromIter::spec_from_iter(iter.into_iter())
2942 }
2943}
2944
2945#[stable(feature = "rust1", since = "1.0.0")]
2946impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
2947 type Item = T;
2948 type IntoIter = IntoIter<T, A>;
2949
2950 /// Consumes the deque into a front-to-back iterator yielding elements by
2951 /// value.
2952 fn into_iter(self) -> IntoIter<T, A> {
2953 IntoIter::new(self)
2954 }
2955}
2956
2957#[stable(feature = "rust1", since = "1.0.0")]
2958impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
2959 type Item = &'a T;
2960 type IntoIter = Iter<'a, T>;
2961
2962 fn into_iter(self) -> Iter<'a, T> {
2963 self.iter()
2964 }
2965}
2966
2967#[stable(feature = "rust1", since = "1.0.0")]
2968impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
2969 type Item = &'a mut T;
2970 type IntoIter = IterMut<'a, T>;
2971
2972 fn into_iter(self) -> IterMut<'a, T> {
2973 self.iter_mut()
2974 }
2975}
2976
2977#[stable(feature = "rust1", since = "1.0.0")]
2978impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
2979 #[track_caller]
2980 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2981 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter());
2982 }
2983
2984 #[inline]
2985 #[track_caller]
2986 fn extend_one(&mut self, elem: T) {
2987 self.push_back(elem);
2988 }
2989
2990 #[inline]
2991 #[track_caller]
2992 fn extend_reserve(&mut self, additional: usize) {
2993 self.reserve(additional);
2994 }
2995
2996 #[inline]
2997 unsafe fn extend_one_unchecked(&mut self, item: T) {
2998 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
2999 unsafe {
3000 self.push_unchecked(item);
3001 }
3002 }
3003}
3004
3005#[stable(feature = "extend_ref", since = "1.2.0")]
3006impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
3007 #[track_caller]
3008 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3009 self.spec_extend(iter.into_iter());
3010 }
3011
3012 #[inline]
3013 #[track_caller]
3014 fn extend_one(&mut self, &elem: &'a T) {
3015 self.push_back(elem);
3016 }
3017
3018 #[inline]
3019 #[track_caller]
3020 fn extend_reserve(&mut self, additional: usize) {
3021 self.reserve(additional);
3022 }
3023
3024 #[inline]
3025 unsafe fn extend_one_unchecked(&mut self, &item: &'a T) {
3026 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3027 unsafe {
3028 self.push_unchecked(item);
3029 }
3030 }
3031}
3032
3033#[stable(feature = "rust1", since = "1.0.0")]
3034impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
3035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3036 f.debug_list().entries(self.iter()).finish()
3037 }
3038}
3039
3040#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3041impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
3042 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3043 ///
3044 /// [`Vec<T>`]: crate::vec::Vec
3045 /// [`VecDeque<T>`]: crate::collections::VecDeque
3046 ///
3047 /// This conversion is guaranteed to run in *O*(1) time
3048 /// and to not re-allocate the `Vec`'s buffer or allocate
3049 /// any additional memory.
3050 #[inline]
3051 fn from(other: Vec<T, A>) -> Self {
3052 let (ptr, len, cap, alloc) = other.into_raw_parts_with_alloc();
3053 Self { head: 0, len, buf: unsafe { RawVec::from_raw_parts_in(ptr, cap, alloc) } }
3054 }
3055}
3056
3057#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3058impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
3059 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
3060 ///
3061 /// [`Vec<T>`]: crate::vec::Vec
3062 /// [`VecDeque<T>`]: crate::collections::VecDeque
3063 ///
3064 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
3065 /// the circular buffer doesn't happen to be at the beginning of the allocation.
3066 ///
3067 /// # Examples
3068 ///
3069 /// ```
3070 /// use std::collections::VecDeque;
3071 ///
3072 /// // This one is *O*(1).
3073 /// let deque: VecDeque<_> = (1..5).collect();
3074 /// let ptr = deque.as_slices().0.as_ptr();
3075 /// let vec = Vec::from(deque);
3076 /// assert_eq!(vec, [1, 2, 3, 4]);
3077 /// assert_eq!(vec.as_ptr(), ptr);
3078 ///
3079 /// // This one needs data rearranging.
3080 /// let mut deque: VecDeque<_> = (1..5).collect();
3081 /// deque.push_front(9);
3082 /// deque.push_front(8);
3083 /// let ptr = deque.as_slices().1.as_ptr();
3084 /// let vec = Vec::from(deque);
3085 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
3086 /// assert_eq!(vec.as_ptr(), ptr);
3087 /// ```
3088 fn from(mut other: VecDeque<T, A>) -> Self {
3089 other.make_contiguous();
3090
3091 unsafe {
3092 let other = ManuallyDrop::new(other);
3093 let buf = other.buf.ptr();
3094 let len = other.len();
3095 let cap = other.capacity();
3096 let alloc = ptr::read(other.allocator());
3097
3098 if other.head != 0 {
3099 ptr::copy(buf.add(other.head), buf, len);
3100 }
3101 Vec::from_raw_parts_in(buf, len, cap, alloc)
3102 }
3103 }
3104}
3105
3106#[stable(feature = "std_collections_from_array", since = "1.56.0")]
3107impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
3108 /// Converts a `[T; N]` into a `VecDeque<T>`.
3109 ///
3110 /// ```
3111 /// use std::collections::VecDeque;
3112 ///
3113 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
3114 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
3115 /// assert_eq!(deq1, deq2);
3116 /// ```
3117 #[track_caller]
3118 fn from(arr: [T; N]) -> Self {
3119 let mut deq = VecDeque::with_capacity(N);
3120 let arr = ManuallyDrop::new(arr);
3121 if !<T>::IS_ZST {
3122 // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
3123 unsafe {
3124 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);
3125 }
3126 }
3127 deq.head = 0;
3128 deq.len = N;
3129 deq
3130 }
3131}