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