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