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
10#[cfg(not(no_global_oom_handling))]
11use core::clone::TrivialClone;
12use core::cmp::{self, Ordering};
13use core::hash::{Hash, Hasher};
14use core::iter::{ByRefSized, repeat_n, repeat_with};
15// This is used in a bunch of intra-doc links.
16// FIXME: For some reason, `#[cfg(doc)]` wasn't sufficient, resulting in
17// failures in linkchecker even though rustdoc built the docs just fine.
18#[allow(unused_imports)]
19use core::mem;
20use core::mem::{ManuallyDrop, SizedTypeProperties};
21use core::ops::{Index, IndexMut, Range, RangeBounds};
22use core::{fmt, ptr, slice};
23
24use crate::alloc::{Allocator, AllocatorNightly, Global};
25use crate::collections::retain::retain_raw;
26use crate::collections::{TryReserveError, TryReserveErrorKind};
27use crate::raw_vec::RawVec;
28use crate::vec::Vec;
29
30#[macro_use]
31mod macros;
32
33#[stable(feature = "drain", since = "1.6.0")]
34pub use self::drain::Drain;
35
36mod drain;
37
38#[unstable(feature = "vec_deque_extract_if", issue = "147750")]
39pub use self::extract_if::ExtractIf;
40
41mod extract_if;
42
43#[stable(feature = "rust1", since = "1.0.0")]
44pub use self::iter_mut::IterMut;
45
46mod iter_mut;
47
48#[stable(feature = "rust1", since = "1.0.0")]
49pub use self::into_iter::IntoIter;
50
51mod into_iter;
52
53#[stable(feature = "rust1", since = "1.0.0")]
54pub use self::iter::Iter;
55
56mod iter;
57
58use self::spec_extend::{SpecExtend, SpecExtendFront};
59
60mod spec_extend;
61
62use self::spec_from_iter::SpecFromIter;
63
64mod spec_from_iter;
65
66#[cfg(not(no_global_oom_handling))]
67#[unstable(feature = "deque_extend_front", issue = "146975")]
68pub use self::splice::Splice;
69
70#[cfg(not(no_global_oom_handling))]
71mod splice;
72
73#[cfg(test)]
74mod tests;
75
76/// A double-ended queue implemented with a growable ring buffer.
77///
78/// The "default" usage of this type as a queue is to use [`push_back`] to add to
79/// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
80/// push onto the back in this manner, and iterating over `VecDeque` goes front
81/// to back.
82///
83/// A `VecDeque` with a known list of items can be initialized from an array:
84///
85/// ```
86/// use std::collections::VecDeque;
87///
88/// let deq = VecDeque::from([-1, 0, 1]);
89/// ```
90///
91/// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
92/// in memory. If you want to access the elements as a single slice, such as for
93/// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
94/// so that its elements do not wrap, and returns a mutable slice to the
95/// now-contiguous element sequence.
96///
97/// [`push_back`]: VecDeque::push_back
98/// [`pop_front`]: VecDeque::pop_front
99/// [`extend`]: VecDeque::extend
100/// [`append`]: VecDeque::append
101/// [`make_contiguous`]: VecDeque::make_contiguous
102#[cfg_attr(not(test), rustc_diagnostic_item = "VecDeque")]
103#[stable(feature = "rust1", since = "1.0.0")]
104#[rustc_insignificant_dtor]
105pub struct VecDeque<
106 T,
107 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
108> {
109 // `self[0]`, if it exists, is `buf[head]`.
110 // `head < buf.capacity()`, unless `buf.capacity() == 0` when `head == 0`.
111 head: WrappedIndex,
112 // the number of initialized elements, starting from the one at `head` and potentially wrapping around.
113 // if `len == 0`, the exact value of `head` is unimportant.
114 // if `T` is zero-Sized, then `self.len <= usize::MAX`, otherwise `self.len <= isize::MAX as usize`.
115 len: usize,
116 buf: RawVec<T, A>,
117}
118
119#[stable(feature = "rust1", since = "1.0.0")]
120impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A> {
121 fn clone(&self) -> Self {
122 let mut deq = Self::with_capacity_in(self.len(), self.allocator().clone());
123 deq.extend(self.iter().cloned());
124 deq
125 }
126
127 /// Overwrites the contents of `self` with a clone of the contents of `source`.
128 ///
129 /// This method is preferred over simply assigning `source.clone()` to `self`,
130 /// as it avoids reallocation if possible.
131 fn clone_from(&mut self, source: &Self) {
132 self.clear();
133 self.extend(source.iter().cloned());
134 }
135}
136
137/// Runs the destructor for all items in the slice when it gets dropped (normally or
138/// during unwinding).
139struct Dropper<'a, T>(&'a mut [T]);
140
141impl<T> Drop for Dropper<'_, T> {
142 fn drop(&mut self) {
143 // ignore-tidy-undocumented-unsafe
144 unsafe {
145 ptr::drop_in_place(self.0);
146 }
147 }
148}
149
150#[stable(feature = "rust1", since = "1.0.0")]
151unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
152 fn drop(&mut self) {
153 let (front, back) = self.as_mut_slices();
154 // ignore-tidy-undocumented-unsafe
155 unsafe {
156 let _back_dropper = Dropper(back);
157 // use drop for [T]
158 ptr::drop_in_place(front);
159 }
160 // RawVec handles deallocation
161 }
162}
163
164#[stable(feature = "rust1", since = "1.0.0")]
165impl<T> Default for VecDeque<T> {
166 /// Creates an empty deque.
167 #[inline]
168 fn default() -> VecDeque<T> {
169 VecDeque::new()
170 }
171}
172
173impl<T, A: Allocator> VecDeque<T, A> {
174 /// Marginally more convenient
175 #[inline]
176 fn ptr(&self) -> *mut T {
177 self.buf.ptr()
178 }
179
180 /// Appends an element to the buffer.
181 ///
182 /// # Safety
183 ///
184 /// May only be called if `deque.len() < deque.capacity()`
185 #[inline]
186 unsafe fn push_unchecked(&mut self, element: T) {
187 // SAFETY: Because of the precondition, it's guaranteed that there is space
188 // in the logical array after the last element.
189 unsafe { self.buffer_write(self.to_wrapped_index(self.len), element) };
190 // This can't overflow because `deque.len() < deque.capacity() <= usize::MAX`.
191 self.len += 1;
192 }
193
194 /// Prepends an element to the buffer.
195 ///
196 /// # Safety
197 ///
198 /// May only be called if `deque.len() < deque.capacity()`
199 #[inline]
200 unsafe fn push_front_unchecked(&mut self, element: T) {
201 self.head = self.wrap_sub(self.head, 1);
202 // SAFETY: Because of the precondition, it's guaranteed that there is space
203 // in the logical array before the first element (where self.head is now).
204 unsafe { self.buffer_write(self.head, element) };
205 // This can't overflow because `deque.len() < deque.capacity() <= usize::MAX`.
206 self.len += 1;
207 }
208
209 /// Moves an element out of the buffer
210 #[inline]
211 unsafe fn buffer_read(&mut self, off: WrappedIndex) -> T {
212 // SAFETY: Upheld by caller.
213 unsafe { ptr::read(self.ptr().add(off.as_index())) }
214 }
215
216 /// Writes an element into the buffer, moving it and returning a pointer to it.
217 /// # Safety
218 ///
219 /// May only be called if `off < self.capacity()`.
220 #[inline]
221 unsafe fn buffer_write(&mut self, off: WrappedIndex, value: T) -> &mut T {
222 // SAFETY: Upheld by caller.
223 unsafe {
224 let ptr = self.ptr().add(off.as_index());
225 ptr::write(ptr, value);
226 &mut *ptr
227 }
228 }
229
230 /// Returns a slice pointer into the buffer.
231 /// `range` must lie inside `0..self.capacity()`.
232 #[inline]
233 unsafe fn buffer_range(&self, range: Range<usize>) -> *mut [T] {
234 // SAFETY: Upheld by caller.
235 unsafe { self.ptr().add(range.start).cast_slice(range.end - range.start) }
236 }
237
238 /// Returns `true` if the buffer is at full capacity.
239 #[inline]
240 fn is_full(&self) -> bool {
241 self.len == self.capacity()
242 }
243
244 /// Returns the index in the underlying buffer for a given logical element
245 /// index + addend.
246 #[inline]
247 fn wrap_add(&self, idx: WrappedIndex, addend: usize) -> WrappedIndex {
248 wrap_index(idx.as_index().wrapping_add(addend), self.capacity())
249 }
250
251 #[inline]
252 fn to_wrapped_index(&self, idx: usize) -> WrappedIndex {
253 self.wrap_add(self.head, idx)
254 }
255
256 /// Returns the index in the underlying buffer for a given logical element
257 /// index - subtrahend.
258 #[inline]
259 fn wrap_sub(&self, idx: WrappedIndex, subtrahend: usize) -> WrappedIndex {
260 wrap_index(
261 idx.as_index().wrapping_sub(subtrahend).wrapping_add(self.capacity()),
262 self.capacity(),
263 )
264 }
265
266 /// Get source, destination and count (like the arguments to [`ptr::copy_nonoverlapping`])
267 /// for copying `count` values from index `src` to index `dst`.
268 /// One of the ranges can wrap around the physical buffer, for this reason 2 triples are returned.
269 ///
270 /// Use of the word "ranges" specifically refers to `src..src + count` and `dst..dst + count`.
271 ///
272 /// # Safety
273 ///
274 /// - Ranges must not overlap: `src.abs_diff(dst) >= count`.
275 /// - Ranges must be in bounds of the logical buffer: `src + count <= self.capacity()` and `dst + count <= self.capacity()`.
276 /// - `head` must be in bounds: `head < self.capacity()`, unless `self.capacity() == 0`, in which case `head == 0`.
277 #[cfg(not(no_global_oom_handling))]
278 unsafe fn nonoverlapping_ranges(
279 &mut self,
280 src: usize,
281 dst: usize,
282 count: usize,
283 head: WrappedIndex,
284 ) -> [(*const T, *mut T, usize); 2] {
285 // "`src` and `dst` must be at least as far apart as `count`"
286 debug_assert!(
287 src.abs_diff(dst) >= count,
288 "`src` and `dst` must not overlap. src={src} dst={dst} count={count}",
289 );
290 debug_assert!(
291 src.max(dst) + count <= self.capacity(),
292 "ranges must be in bounds. src={src} dst={dst} count={count} cap={}",
293 self.capacity(),
294 );
295
296 let wrapped_src = self.wrap_add(head, src);
297 let wrapped_dst = self.wrap_add(head, dst);
298
299 let room_after_src = self.capacity() - wrapped_src.as_index();
300 let room_after_dst = self.capacity() - wrapped_dst.as_index();
301
302 let src_wraps = room_after_src < count;
303 let dst_wraps = room_after_dst < count;
304
305 // Wrapping occurs if `capacity` is contained within `wrapped_src..wrapped_src + count` or `wrapped_dst..wrapped_dst + count`.
306 // Since these two ranges must not overlap as per the safety invariants of this function, only one range can wrap.
307 debug_assert!(
308 !(src_wraps && dst_wraps),
309 "BUG: at most one of src and dst can wrap. src={src} dst={dst} count={count} cap={}",
310 self.capacity(),
311 );
312
313 // ignore-tidy-undocumented-unsafe
314 unsafe {
315 let ptr = self.ptr();
316 let src_ptr = ptr.add(wrapped_src.as_index());
317 let dst_ptr = ptr.add(wrapped_dst.as_index());
318
319 if src_wraps {
320 [
321 (src_ptr, dst_ptr, room_after_src),
322 (ptr, dst_ptr.add(room_after_src), count - room_after_src),
323 ]
324 } else if dst_wraps {
325 [
326 (src_ptr, dst_ptr, room_after_dst),
327 (src_ptr.add(room_after_dst), ptr, count - room_after_dst),
328 ]
329 } else {
330 [
331 (src_ptr, dst_ptr, count),
332 // null pointers are fine as long as the count is 0
333 (ptr::null(), ptr::null_mut(), 0),
334 ]
335 }
336 }
337 }
338
339 /// Copies a contiguous block of memory len long from src to dst
340 #[inline]
341 unsafe fn copy(&mut self, src: WrappedIndex, dst: WrappedIndex, len: usize) {
342 debug_assert!(
343 dst + len <= self.capacity(),
344 "cpy dst={} src={} len={} cap={}",
345 dst,
346 src,
347 len,
348 self.capacity()
349 );
350 debug_assert!(
351 src + len <= self.capacity(),
352 "cpy dst={} src={} len={} cap={}",
353 dst,
354 src,
355 len,
356 self.capacity()
357 );
358 // SAFETY: Upheld by caller.
359 unsafe {
360 ptr::copy(self.ptr().add(src.as_index()), self.ptr().add(dst.as_index()), len);
361 }
362 }
363
364 /// Copies a contiguous block of memory len long from src to dst
365 #[inline]
366 unsafe fn copy_nonoverlapping(&mut self, src: WrappedIndex, dst: WrappedIndex, len: usize) {
367 debug_assert!(
368 dst + len <= self.capacity(),
369 "cno dst={} src={} len={} cap={}",
370 dst,
371 src,
372 len,
373 self.capacity()
374 );
375 debug_assert!(
376 src + len <= self.capacity(),
377 "cno dst={} src={} len={} cap={}",
378 dst,
379 src,
380 len,
381 self.capacity()
382 );
383 // SAFETY: Upheld by caller.
384 unsafe {
385 ptr::copy_nonoverlapping(
386 self.ptr().add(src.as_index()),
387 self.ptr().add(dst.as_index()),
388 len,
389 );
390 }
391 }
392
393 /// Copies a potentially wrapping block of memory len long from src to dest.
394 /// (abs(dst - src) + len) must be no larger than capacity() (There must be at
395 /// most one continuous overlapping region between src and dest).
396 unsafe fn wrap_copy(&mut self, src: WrappedIndex, dst: WrappedIndex, len: usize) {
397 debug_assert!(
398 cmp::min(src.abs_diff(dst), self.capacity() - src.abs_diff(dst)) + len
399 <= self.capacity(),
400 "wrc dst={} src={} len={} cap={}",
401 dst,
402 src,
403 len,
404 self.capacity()
405 );
406
407 // If T is a ZST, don't do any copying.
408 if T::IS_ZST || src == dst || len == 0 {
409 return;
410 }
411
412 let dst_after_src = self.wrap_sub(dst, src.as_index()) < len;
413
414 let src_pre_wrap_len = self.capacity() - src.as_index();
415 let dst_pre_wrap_len = self.capacity() - dst.as_index();
416 let src_wraps = src_pre_wrap_len < len;
417 let dst_wraps = dst_pre_wrap_len < len;
418
419 match (dst_after_src, src_wraps, dst_wraps) {
420 (_, false, false) => {
421 // src doesn't wrap, dst doesn't wrap
422 //
423 // S . . .
424 // 1 [_ _ A A B B C C _]
425 // 2 [_ _ A A A A B B _]
426 // D . . .
427 //
428 // ignore-tidy-undocumented-unsafe
429 unsafe {
430 self.copy(src, dst, len);
431 }
432 }
433 (false, false, true) => {
434 // dst before src, src doesn't wrap, dst wraps
435 //
436 // S . . .
437 // 1 [A A B B _ _ _ C C]
438 // 2 [A A B B _ _ _ A A]
439 // 3 [B B B B _ _ _ A A]
440 // . . D .
441 //
442 // ignore-tidy-undocumented-unsafe
443 unsafe {
444 self.copy(src, dst, dst_pre_wrap_len);
445 self.copy(
446 src.add(dst_pre_wrap_len),
447 WrappedIndex::zero(),
448 len - dst_pre_wrap_len,
449 );
450 }
451 }
452 (true, false, true) => {
453 // src before dst, src doesn't wrap, dst wraps
454 //
455 // S . . .
456 // 1 [C C _ _ _ A A B B]
457 // 2 [B B _ _ _ A A B B]
458 // 3 [B B _ _ _ A A A A]
459 // . . D .
460 //
461 // ignore-tidy-undocumented-unsafe
462 unsafe {
463 self.copy(
464 src.add(dst_pre_wrap_len),
465 WrappedIndex::zero(),
466 len - dst_pre_wrap_len,
467 );
468 self.copy(src, dst, dst_pre_wrap_len);
469 }
470 }
471 (false, true, false) => {
472 // dst before src, src wraps, dst doesn't wrap
473 //
474 // . . S .
475 // 1 [C C _ _ _ A A B B]
476 // 2 [C C _ _ _ B B B B]
477 // 3 [C C _ _ _ B B C C]
478 // D . . .
479 //
480 // ignore-tidy-undocumented-unsafe
481 unsafe {
482 self.copy(src, dst, src_pre_wrap_len);
483 self.copy(
484 WrappedIndex::zero(),
485 dst.add(src_pre_wrap_len),
486 len - src_pre_wrap_len,
487 );
488 }
489 }
490 (true, true, false) => {
491 // src before dst, src wraps, dst doesn't wrap
492 //
493 // . . S .
494 // 1 [A A B B _ _ _ C C]
495 // 2 [A A A A _ _ _ C C]
496 // 3 [C C A A _ _ _ C C]
497 // D . . .
498 //
499 // ignore-tidy-undocumented-unsafe
500 unsafe {
501 self.copy(
502 WrappedIndex::zero(),
503 dst.add(src_pre_wrap_len),
504 len - src_pre_wrap_len,
505 );
506 self.copy(src, dst, src_pre_wrap_len);
507 }
508 }
509 (false, true, true) => {
510 // dst before src, src wraps, dst wraps
511 //
512 // . . . S .
513 // 1 [A B C D _ E F G H]
514 // 2 [A B C D _ E G H H]
515 // 3 [A B C D _ E G H A]
516 // 4 [B C C D _ E G H A]
517 // . . D . .
518 //
519 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
520 let delta = dst_pre_wrap_len - src_pre_wrap_len;
521 // ignore-tidy-undocumented-unsafe
522 unsafe {
523 self.copy(src, dst, src_pre_wrap_len);
524 self.copy(WrappedIndex::zero(), dst.add(src_pre_wrap_len), delta);
525 self.copy(
526 WrappedIndex::from_arbitrary_number(delta),
527 WrappedIndex::zero(),
528 len - dst_pre_wrap_len,
529 );
530 }
531 }
532 (true, true, true) => {
533 // src before dst, src wraps, dst wraps
534 //
535 // . . S . .
536 // 1 [A B C D _ E F G H]
537 // 2 [A A B D _ E F G H]
538 // 3 [H A B D _ E F G H]
539 // 4 [H A B D _ E F F G]
540 // . . . D .
541 //
542 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
543 let delta = src_pre_wrap_len - dst_pre_wrap_len;
544 // ignore-tidy-undocumented-unsafe
545 unsafe {
546 self.copy(
547 WrappedIndex::zero(),
548 WrappedIndex::from_arbitrary_number(delta),
549 len - src_pre_wrap_len,
550 );
551 self.copy(
552 WrappedIndex::from_arbitrary_number(self.capacity() - delta),
553 WrappedIndex::zero(),
554 delta,
555 );
556 self.copy(src, dst, dst_pre_wrap_len);
557 }
558 }
559 }
560 }
561
562 /// Copies all values from `src` to `dst`, wrapping around if needed.
563 /// Assumes capacity is sufficient.
564 #[inline]
565 unsafe fn copy_slice(&mut self, dst: WrappedIndex, src: &[T]) {
566 debug_assert!(src.len() <= self.capacity());
567 let head_room = self.capacity() - dst.as_index();
568 if src.len() <= head_room {
569 // ignore-tidy-undocumented-unsafe
570 unsafe {
571 ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst.as_index()), src.len());
572 }
573 } else {
574 let (left, right) = src.split_at(head_room);
575 // ignore-tidy-undocumented-unsafe
576 unsafe {
577 ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst.as_index()), left.len());
578 ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
579 }
580 }
581 }
582
583 /// Copies all values from `src` to `dst` in reversed order, wrapping around if needed.
584 /// Assumes capacity is sufficient.
585 /// Equivalent to calling [`VecDeque::copy_slice`] with a [reversed](https://doc.rust-lang.org/std/primitive.slice.html#method.reverse) slice.
586 #[inline]
587 unsafe fn copy_slice_reversed(&mut self, dst: WrappedIndex, src: &[T]) {
588 /// # Safety
589 ///
590 /// See [`ptr::copy_nonoverlapping`].
591 unsafe fn copy_nonoverlapping_reversed<T>(src: *const T, dst: *mut T, count: usize) {
592 for i in 0..count {
593 // SAFETY: Upheld by caller.
594 unsafe { ptr::copy_nonoverlapping(src.add(count - 1 - i), dst.add(i), 1) };
595 }
596 }
597
598 debug_assert!(src.len() <= self.capacity());
599 let head_room = self.capacity() - dst.as_index();
600 if src.len() <= head_room {
601 // ignore-tidy-undocumented-unsafe
602 unsafe {
603 copy_nonoverlapping_reversed(
604 src.as_ptr(),
605 self.ptr().add(dst.as_index()),
606 src.len(),
607 );
608 }
609 } else {
610 let (left, right) = src.split_at(src.len() - head_room);
611 // ignore-tidy-undocumented-unsafe
612 unsafe {
613 copy_nonoverlapping_reversed(
614 right.as_ptr(),
615 self.ptr().add(dst.as_index()),
616 right.len(),
617 );
618 copy_nonoverlapping_reversed(left.as_ptr(), self.ptr(), left.len());
619 }
620 }
621 }
622
623 /// Writes all values from `iter` to `dst`.
624 ///
625 /// # Safety
626 ///
627 /// Assumes no wrapping around happens.
628 /// Assumes capacity is sufficient.
629 #[inline]
630 unsafe fn write_iter(
631 &mut self,
632 dst: WrappedIndex,
633 iter: impl Iterator<Item = T>,
634 written: &mut usize,
635 ) {
636 // ignore-tidy-undocumented-unsafe
637 iter.enumerate().for_each(|(i, element)| unsafe {
638 self.buffer_write(dst.add(i), element);
639 *written += 1;
640 });
641 }
642
643 /// Writes all values from `iter` to `dst`, wrapping
644 /// at the end of the buffer and returns the number
645 /// of written values.
646 ///
647 /// # Safety
648 ///
649 /// Assumes that `iter` yields at most `len` items.
650 /// Assumes capacity is sufficient.
651 unsafe fn write_iter_wrapping(
652 &mut self,
653 dst: WrappedIndex,
654 mut iter: impl Iterator<Item = T>,
655 len: usize,
656 ) -> usize {
657 struct Guard<'a, T, A: Allocator> {
658 deque: &'a mut VecDeque<T, A>,
659 written: usize,
660 }
661
662 impl<'a, T, A: Allocator> Drop for Guard<'a, T, A> {
663 fn drop(&mut self) {
664 self.deque.len += self.written;
665 }
666 }
667
668 let head_room = self.capacity() - dst.as_index();
669
670 let mut guard = Guard { deque: self, written: 0 };
671
672 if head_room >= len {
673 // ignore-tidy-undocumented-unsafe
674 unsafe { guard.deque.write_iter(dst, iter, &mut guard.written) };
675 } else {
676 // ignore-tidy-undocumented-unsafe
677 unsafe {
678 guard.deque.write_iter(
679 dst,
680 ByRefSized(&mut iter).take(head_room),
681 &mut guard.written,
682 );
683 guard.deque.write_iter(WrappedIndex::zero(), iter, &mut guard.written)
684 };
685 }
686
687 guard.written
688 }
689
690 /// Frobs the head and tail sections around to handle the fact that we
691 /// just reallocated. Unsafe because it trusts old_capacity.
692 #[inline]
693 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
694 let new_capacity = self.capacity();
695 debug_assert!(new_capacity >= old_capacity);
696
697 // Move the shortest contiguous section of the ring buffer
698 //
699 // H := head
700 // L := last element (`self.to_physical_idx(self.len - 1)`)
701 //
702 // H L
703 // [o o o o o o o o ]
704 // H L
705 // A [o o o o o o o o . . . . . . . . ]
706 // L H
707 // [o o o o o o o o ]
708 // H L
709 // B [. . . o o o o o o o o . . . . . ]
710 // L H
711 // [o o o o o o o o ]
712 // L H
713 // C [o o o o o o . . . . . . . . o o ]
714
715 // can't use is_contiguous() because the capacity is already updated.
716 if self.head <= old_capacity - self.len {
717 // A
718 // Nop
719 } else {
720 let head_len = old_capacity - self.head.as_index();
721 let tail_len = self.len - head_len;
722 if head_len > tail_len && new_capacity - old_capacity >= tail_len {
723 // B
724 // ignore-tidy-undocumented-unsafe
725 unsafe {
726 self.copy_nonoverlapping(
727 WrappedIndex::zero(),
728 WrappedIndex::from_arbitrary_number(old_capacity),
729 tail_len,
730 );
731 }
732 } else {
733 // C
734 let new_head = WrappedIndex::from_arbitrary_number(new_capacity - head_len);
735 // ignore-tidy-undocumented-unsafe
736 unsafe {
737 // can't use copy_nonoverlapping here, because if e.g. head_len = 2
738 // and new_capacity = old_capacity + 1, then the heads overlap.
739 self.copy(self.head, new_head, head_len);
740 }
741 self.head = new_head;
742 }
743 }
744 debug_assert!(self.head < self.capacity() || self.capacity() == 0);
745 }
746
747 /// Creates an iterator which uses a closure to determine if an element in the range should be removed.
748 ///
749 /// If the closure returns `true`, the element is removed from the deque and yielded. If the closure
750 /// returns `false`, or panics, the element remains in the deque and will not be yielded.
751 ///
752 /// Only elements that fall in the provided range are considered for extraction, but any elements
753 /// after the range will still have to be moved if any element has been extracted.
754 ///
755 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
756 /// or the iteration short-circuits, then the remaining elements will be retained.
757 /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
758 /// or [`retain_mut`] with a negated predicate if you also do not need to restrict the range.
759 ///
760 /// [`retain_mut`]: VecDeque::retain_mut
761 ///
762 /// Using this method is equivalent to the following code:
763 ///
764 /// ```
765 /// #![feature(vec_deque_extract_if)]
766 /// # use std::collections::VecDeque;
767 /// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
768 /// # let mut deq: VecDeque<_> = (0..10).collect();
769 /// # let mut deq2 = deq.clone();
770 /// # let range = 1..5;
771 /// let mut i = range.start;
772 /// let end_items = deq.len() - range.end;
773 /// # let mut extracted = vec![];
774 ///
775 /// while i < deq.len() - end_items {
776 /// if some_predicate(&mut deq[i]) {
777 /// let val = deq.remove(i).unwrap();
778 /// // your code here
779 /// # extracted.push(val);
780 /// } else {
781 /// i += 1;
782 /// }
783 /// }
784 ///
785 /// # let extracted2: Vec<_> = deq2.extract_if(range, some_predicate).collect();
786 /// # assert_eq!(deq, deq2);
787 /// # assert_eq!(extracted, extracted2);
788 /// ```
789 ///
790 /// But `extract_if` is easier to use. `extract_if` is also more efficient,
791 /// because it can backshift the elements of the array in bulk.
792 ///
793 /// The iterator also lets you mutate the value of each element in the
794 /// closure, regardless of whether you choose to keep or remove it.
795 ///
796 /// # Panics
797 ///
798 /// If `range` is out of bounds.
799 ///
800 /// # Examples
801 ///
802 /// Splitting a deque into even and odd values, reusing the original deque:
803 ///
804 /// ```
805 /// #![feature(vec_deque_extract_if)]
806 /// use std::collections::VecDeque;
807 ///
808 /// let mut numbers = VecDeque::from([1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
809 ///
810 /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<VecDeque<_>>();
811 /// let odds = numbers;
812 ///
813 /// assert_eq!(evens, VecDeque::from([2, 4, 6, 8, 14]));
814 /// assert_eq!(odds, VecDeque::from([1, 3, 5, 9, 11, 13, 15]));
815 /// ```
816 ///
817 /// Using the range argument to only process a part of the deque:
818 ///
819 /// ```
820 /// #![feature(vec_deque_extract_if)]
821 /// use std::collections::VecDeque;
822 ///
823 /// let mut items = VecDeque::from([0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]);
824 /// let ones = items.extract_if(7.., |x| *x == 1).collect::<VecDeque<_>>();
825 /// assert_eq!(items, VecDeque::from([0, 0, 0, 0, 0, 0, 0, 2, 2, 2]));
826 /// assert_eq!(ones.len(), 3);
827 /// ```
828 #[unstable(feature = "vec_deque_extract_if", issue = "147750")]
829 pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A>
830 where
831 F: FnMut(&mut T) -> bool,
832 R: RangeBounds<usize>,
833 {
834 ExtractIf::new(self, filter, range)
835 }
836}
837
838impl<T> VecDeque<T> {
839 /// Creates an empty deque.
840 ///
841 /// # Examples
842 ///
843 /// ```
844 /// use std::collections::VecDeque;
845 ///
846 /// let deque: VecDeque<u32> = VecDeque::new();
847 /// ```
848 #[inline]
849 #[stable(feature = "rust1", since = "1.0.0")]
850 #[rustc_const_stable(feature = "const_vec_deque_new", since = "1.68.0")]
851 #[must_use]
852 pub const fn new() -> VecDeque<T> {
853 // FIXME(const-hack): This should just be `VecDeque::new_in(Global)` once that hits stable.
854 VecDeque { head: WrappedIndex::zero(), len: 0, buf: RawVec::new() }
855 }
856
857 /// Creates an empty deque with space for at least `capacity` elements.
858 ///
859 /// # Examples
860 ///
861 /// ```
862 /// use std::collections::VecDeque;
863 ///
864 /// let deque: VecDeque<i32> = VecDeque::with_capacity(10);
865 /// ```
866 #[inline]
867 #[stable(feature = "rust1", since = "1.0.0")]
868 #[must_use]
869 pub fn with_capacity(capacity: usize) -> VecDeque<T> {
870 Self::with_capacity_in(capacity, Global)
871 }
872
873 /// Creates an empty deque with space for at least `capacity` elements.
874 ///
875 /// # Errors
876 ///
877 /// Returns an error if the capacity exceeds `isize::MAX` _bytes_,
878 /// or if the allocator reports allocation failure.
879 ///
880 /// # Examples
881 ///
882 /// ```
883 /// # #![feature(try_with_capacity)]
884 /// # #[allow(unused)]
885 /// # fn example() -> Result<(), std::collections::TryReserveError> {
886 /// use std::collections::VecDeque;
887 ///
888 /// let deque: VecDeque<u32> = VecDeque::try_with_capacity(10)?;
889 /// # Ok(()) }
890 /// ```
891 #[inline]
892 #[unstable(feature = "try_with_capacity", issue = "91913")]
893 pub fn try_with_capacity(capacity: usize) -> Result<VecDeque<T>, TryReserveError> {
894 Ok(VecDeque {
895 head: WrappedIndex::zero(),
896 len: 0,
897 buf: RawVec::try_with_capacity_in(capacity, Global)?,
898 })
899 }
900}
901
902impl<T, A: Allocator> VecDeque<T, A> {
903 /// Creates an empty deque.
904 ///
905 /// # Examples
906 ///
907 /// ```
908 /// # #![feature(allocator_ext)]
909 ///
910 /// use std::collections::VecDeque;
911 /// use std::alloc::Global;
912 ///
913 /// let deque: VecDeque<i32> = VecDeque::new_in(Global);
914 /// ```
915 #[inline]
916 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
917 pub const fn new_in(alloc: A) -> VecDeque<T, A> {
918 VecDeque { head: WrappedIndex::zero(), len: 0, buf: RawVec::new_in(alloc) }
919 }
920
921 /// Creates an empty deque with space for at least `capacity` elements.
922 ///
923 /// # Examples
924 ///
925 /// ```
926 /// # #![feature(allocator_ext)]
927 ///
928 /// use std::collections::VecDeque;
929 /// use std::alloc::Global;
930 ///
931 /// let deque: VecDeque<i32> = VecDeque::with_capacity_in(10, Global);
932 /// ```
933 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
934 pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
935 VecDeque {
936 head: WrappedIndex::zero(),
937 len: 0,
938 buf: RawVec::with_capacity_in(capacity, alloc),
939 }
940 }
941
942 /// Creates a `VecDeque` from a raw allocation, when the initialized
943 /// part of that allocation forms a *contiguous* subslice thereof.
944 ///
945 /// For use by `vec::IntoIter::into_vecdeque`
946 ///
947 /// # Safety
948 ///
949 /// All the usual requirements on the allocated memory like in
950 /// `Vec::from_raw_parts_in`, but takes a *range* of elements that are
951 /// initialized rather than only supporting `0..len`. Requires that
952 /// `initialized.start` ≤ `initialized.end` ≤ `capacity`.
953 /// Also, `initialized.start` < `capacity`, unless both are 0.
954 #[inline]
955 #[cfg(not(test))]
956 pub(crate) unsafe fn from_contiguous_raw_parts_in(
957 ptr: *mut T,
958 initialized: Range<usize>,
959 capacity: usize,
960 alloc: A,
961 ) -> Self {
962 debug_assert!(initialized.start <= initialized.end);
963 debug_assert!(initialized.end <= capacity);
964 debug_assert!(initialized.start == 0 && capacity == 0 || initialized.start < capacity);
965
966 // SAFETY: Our safety precondition guarantees the range length won't wrap,
967 // that the allocation is valid for use in `RawVec` with `alloc`,
968 // and that the range contains valid elements.
969 // We have `head`, `len` ≤ `cap`, since `start`, `end` ≤ `cap`.
970 // Also, `head` < `cap` unless `head` = `cap` = `0`.
971 unsafe {
972 VecDeque {
973 head: WrappedIndex::from_arbitrary_number(initialized.start),
974 len: initialized.end.unchecked_sub(initialized.start),
975 buf: RawVec::from_raw_parts_in(ptr, capacity, alloc),
976 }
977 }
978 }
979
980 /// Provides a reference to the element at the given index.
981 ///
982 /// Element at index 0 is the front of the queue.
983 ///
984 /// # Examples
985 ///
986 /// ```
987 /// use std::collections::VecDeque;
988 ///
989 /// let mut buf = VecDeque::new();
990 /// buf.push_back(3);
991 /// buf.push_back(4);
992 /// buf.push_back(5);
993 /// buf.push_back(6);
994 /// assert_eq!(buf.get(1), Some(&4));
995 /// ```
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn get(&self, index: usize) -> Option<&T> {
998 if index < self.len {
999 let idx = self.to_wrapped_index(index);
1000 // ignore-tidy-undocumented-unsafe
1001 unsafe { Some(&*self.ptr().add(idx.as_index())) }
1002 } else {
1003 None
1004 }
1005 }
1006
1007 /// Provides a mutable reference to the element at the given index.
1008 ///
1009 /// Element at index 0 is the front of the queue.
1010 ///
1011 /// # Examples
1012 ///
1013 /// ```
1014 /// use std::collections::VecDeque;
1015 ///
1016 /// let mut buf = VecDeque::new();
1017 /// buf.push_back(3);
1018 /// buf.push_back(4);
1019 /// buf.push_back(5);
1020 /// buf.push_back(6);
1021 /// assert_eq!(buf[1], 4);
1022 /// if let Some(elem) = buf.get_mut(1) {
1023 /// *elem = 7;
1024 /// }
1025 /// assert_eq!(buf[1], 7);
1026 /// ```
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
1029 if index < self.len {
1030 let idx = self.to_wrapped_index(index);
1031 // ignore-tidy-undocumented-unsafe
1032 unsafe { Some(&mut *self.ptr().add(idx.as_index())) }
1033 } else {
1034 None
1035 }
1036 }
1037
1038 /// Swaps elements at indices `i` and `j`.
1039 ///
1040 /// `i` and `j` may be equal.
1041 ///
1042 /// Element at index 0 is the front of the queue.
1043 ///
1044 /// # Panics
1045 ///
1046 /// Panics if either index is out of bounds.
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```
1051 /// use std::collections::VecDeque;
1052 ///
1053 /// let mut buf = VecDeque::new();
1054 /// buf.push_back(3);
1055 /// buf.push_back(4);
1056 /// buf.push_back(5);
1057 /// assert_eq!(buf, [3, 4, 5]);
1058 /// buf.swap(0, 2);
1059 /// assert_eq!(buf, [5, 4, 3]);
1060 /// ```
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 pub fn swap(&mut self, i: usize, j: usize) {
1063 assert!(i < self.len());
1064 assert!(j < self.len());
1065 let ri = self.to_wrapped_index(i);
1066 let rj = self.to_wrapped_index(j);
1067 // ignore-tidy-undocumented-unsafe
1068 unsafe { ptr::swap(self.ptr().add(ri.as_index()), self.ptr().add(rj.as_index())) }
1069 }
1070
1071 /// Returns the number of elements the deque can hold without
1072 /// reallocating.
1073 ///
1074 /// # Examples
1075 ///
1076 /// ```
1077 /// use std::collections::VecDeque;
1078 ///
1079 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
1080 /// assert!(buf.capacity() >= 10);
1081 /// ```
1082 #[inline]
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 pub fn capacity(&self) -> usize {
1085 if T::IS_ZST { usize::MAX } else { self.buf.capacity() }
1086 }
1087
1088 /// Reserves the minimum capacity for at least `additional` more elements to be inserted in the
1089 /// given deque. Does nothing if the capacity is already sufficient.
1090 ///
1091 /// Note that the allocator may give the collection more space than it requests. Therefore
1092 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
1093 /// insertions are expected.
1094 ///
1095 /// # Panics
1096 ///
1097 /// Panics if the new capacity overflows `usize`.
1098 ///
1099 /// # Examples
1100 ///
1101 /// ```
1102 /// use std::collections::VecDeque;
1103 ///
1104 /// let mut buf: VecDeque<i32> = [1].into();
1105 /// buf.reserve_exact(10);
1106 /// assert!(buf.capacity() >= 11);
1107 /// ```
1108 ///
1109 /// [`reserve`]: VecDeque::reserve
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 pub fn reserve_exact(&mut self, additional: usize) {
1112 let new_cap = self.len.checked_add(additional).expect("capacity overflow");
1113 let old_cap = self.capacity();
1114
1115 if new_cap > old_cap {
1116 self.buf.reserve_exact(self.len, additional);
1117 // ignore-tidy-undocumented-unsafe
1118 unsafe {
1119 self.handle_capacity_increase(old_cap);
1120 }
1121 }
1122 }
1123
1124 /// Reserves capacity for at least `additional` more elements to be inserted in the given
1125 /// deque. The collection may reserve more space to speculatively avoid frequent reallocations.
1126 ///
1127 /// # Panics
1128 ///
1129 /// Panics if the new capacity overflows `usize`.
1130 ///
1131 /// # Examples
1132 ///
1133 /// ```
1134 /// use std::collections::VecDeque;
1135 ///
1136 /// let mut buf: VecDeque<i32> = [1].into();
1137 /// buf.reserve(10);
1138 /// assert!(buf.capacity() >= 11);
1139 /// ```
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_reserve")]
1142 pub fn reserve(&mut self, additional: usize) {
1143 let new_cap = self.len.checked_add(additional).expect("capacity overflow");
1144 let old_cap = self.capacity();
1145
1146 if new_cap > old_cap {
1147 // we don't need to reserve_exact(), as the size doesn't have
1148 // to be a power of 2.
1149 self.buf.reserve(self.len, additional);
1150 // ignore-tidy-undocumented-unsafe
1151 unsafe {
1152 self.handle_capacity_increase(old_cap);
1153 }
1154 }
1155 }
1156
1157 /// Tries to reserve the minimum capacity for at least `additional` more elements to
1158 /// be inserted in the given deque. After calling `try_reserve_exact`,
1159 /// capacity will be greater than or equal to `self.len() + additional` if
1160 /// it returns `Ok(())`. Does nothing if the capacity is already sufficient.
1161 ///
1162 /// Note that the allocator may give the collection more space than it
1163 /// requests. Therefore, capacity can not be relied upon to be precisely
1164 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1165 ///
1166 /// [`try_reserve`]: VecDeque::try_reserve
1167 ///
1168 /// # Errors
1169 ///
1170 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
1171 /// is returned.
1172 ///
1173 /// # Examples
1174 ///
1175 /// ```
1176 /// use std::collections::TryReserveError;
1177 /// use std::collections::VecDeque;
1178 ///
1179 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
1180 /// let mut output = VecDeque::new();
1181 ///
1182 /// // Pre-reserve the memory, exiting if we can't
1183 /// output.try_reserve_exact(data.len())?;
1184 ///
1185 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
1186 /// output.extend(data.iter().map(|&val| {
1187 /// val * 2 + 5 // very complicated
1188 /// }));
1189 ///
1190 /// Ok(output)
1191 /// }
1192 /// # process_data(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1193 /// ```
1194 #[stable(feature = "try_reserve", since = "1.57.0")]
1195 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1196 let new_cap =
1197 self.len.checked_add(additional).ok_or(TryReserveErrorKind::CapacityOverflow)?;
1198 let old_cap = self.capacity();
1199
1200 if new_cap > old_cap {
1201 self.buf.try_reserve_exact(self.len, additional)?;
1202 // ignore-tidy-undocumented-unsafe
1203 unsafe {
1204 self.handle_capacity_increase(old_cap);
1205 }
1206 }
1207 Ok(())
1208 }
1209
1210 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1211 /// in the given deque. The collection may reserve more space to speculatively avoid
1212 /// frequent reallocations. After calling `try_reserve`, capacity will be
1213 /// greater than or equal to `self.len() + additional` if it returns
1214 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1215 /// preserves the contents even if an error occurs.
1216 ///
1217 /// # Errors
1218 ///
1219 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
1220 /// is returned.
1221 ///
1222 /// # Examples
1223 ///
1224 /// ```
1225 /// use std::collections::TryReserveError;
1226 /// use std::collections::VecDeque;
1227 ///
1228 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
1229 /// let mut output = VecDeque::new();
1230 ///
1231 /// // Pre-reserve the memory, exiting if we can't
1232 /// output.try_reserve(data.len())?;
1233 ///
1234 /// // Now we know this can't OOM in the middle of our complex work
1235 /// output.extend(data.iter().map(|&val| {
1236 /// val * 2 + 5 // very complicated
1237 /// }));
1238 ///
1239 /// Ok(output)
1240 /// }
1241 /// # process_data(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1242 /// ```
1243 #[stable(feature = "try_reserve", since = "1.57.0")]
1244 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1245 let new_cap =
1246 self.len.checked_add(additional).ok_or(TryReserveErrorKind::CapacityOverflow)?;
1247 let old_cap = self.capacity();
1248
1249 if new_cap > old_cap {
1250 self.buf.try_reserve(self.len, additional)?;
1251 // ignore-tidy-undocumented-unsafe
1252 unsafe {
1253 self.handle_capacity_increase(old_cap);
1254 }
1255 }
1256 Ok(())
1257 }
1258
1259 /// Shrinks the capacity of the deque as much as possible.
1260 ///
1261 /// It will drop down as close as possible to the length but the allocator may still inform the
1262 /// deque that there is space for a few more elements.
1263 ///
1264 /// # Examples
1265 ///
1266 /// ```
1267 /// use std::collections::VecDeque;
1268 ///
1269 /// let mut buf = VecDeque::with_capacity(15);
1270 /// buf.extend(0..4);
1271 /// assert_eq!(buf.capacity(), 15);
1272 /// buf.shrink_to_fit();
1273 /// assert!(buf.capacity() >= 4);
1274 /// ```
1275 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1276 pub fn shrink_to_fit(&mut self) {
1277 self.shrink_to(0);
1278 }
1279
1280 /// Shrinks the capacity of the deque with a lower bound.
1281 ///
1282 /// The capacity will remain at least as large as both the length
1283 /// and the supplied value.
1284 ///
1285 /// If the current capacity is less than the lower limit, this is a no-op.
1286 ///
1287 /// # Examples
1288 ///
1289 /// ```
1290 /// use std::collections::VecDeque;
1291 ///
1292 /// let mut buf = VecDeque::with_capacity(15);
1293 /// buf.extend(0..4);
1294 /// assert_eq!(buf.capacity(), 15);
1295 /// buf.shrink_to(6);
1296 /// assert!(buf.capacity() >= 6);
1297 /// buf.shrink_to(0);
1298 /// assert!(buf.capacity() >= 4);
1299 /// ```
1300 #[stable(feature = "shrink_to", since = "1.56.0")]
1301 pub fn shrink_to(&mut self, min_capacity: usize) {
1302 let target_cap = min_capacity.max(self.len);
1303
1304 // never shrink ZSTs
1305 if T::IS_ZST || self.capacity() <= target_cap {
1306 return;
1307 }
1308
1309 // There are three cases of interest:
1310 // All elements are out of desired bounds
1311 // Elements are contiguous, and tail is out of desired bounds
1312 // Elements are discontiguous
1313 //
1314 // At all other times, element positions are unaffected.
1315
1316 // `head` and `len` are at most `isize::MAX` and `target_cap < self.capacity()`, so nothing can
1317 // overflow.
1318 let tail_outside = (target_cap + 1..=self.capacity()).contains(&(self.head + self.len));
1319 // Used in the drop guard below.
1320 let old_head = self.head;
1321
1322 if self.len == 0 {
1323 self.head = WrappedIndex::zero();
1324 } else if self.head.as_index() >= target_cap && tail_outside {
1325 // Head and tail are both out of bounds, so copy all of them to the front.
1326 //
1327 // H := head
1328 // L := last element
1329 // H L
1330 // [. . . . . . . . o o o o o o o . ]
1331 // H L
1332 // [o o o o o o o . ]
1333 //
1334 // SAFETY: `self.head >= target_cap >= self.len`, therefore these accesses
1335 // do not overlap.
1336 unsafe {
1337 self.copy_nonoverlapping(self.head, WrappedIndex::zero(), self.len);
1338 }
1339 self.head = WrappedIndex::zero();
1340 } else if self.head < target_cap && tail_outside {
1341 // Head is in bounds, tail is out of bounds.
1342 // Copy the overflowing part to the beginning of the
1343 // buffer. This won't overlap because `target_cap >= self.len`.
1344 //
1345 // H := head
1346 // L := last element
1347 // H L
1348 // [. . . o o o o o o o . . . . . . ]
1349 // L H
1350 // [o o . o o o o o ]
1351 let len = self.head + self.len - target_cap;
1352 // SAFETY: head is < target_cap, so the index is wrapped
1353 unsafe {
1354 self.copy_nonoverlapping(
1355 WrappedIndex::from_arbitrary_number(target_cap),
1356 WrappedIndex::zero(),
1357 len,
1358 );
1359 }
1360 } else if !self.is_contiguous() {
1361 // The head slice is at least partially out of bounds, tail is in bounds.
1362 // Copy the head backwards so it lines up with the target capacity.
1363 // This won't overlap because `target_cap >= self.len`.
1364 //
1365 // H := head
1366 // L := last element
1367 // L H
1368 // [o o o o o . . . . . . . . . o o ]
1369 // L H
1370 // [o o o o o . o o ]
1371 let head_len = self.capacity() - self.head.as_index();
1372
1373 // head_len is at least one, so new_head will be < target_cap
1374 let new_head = WrappedIndex::from_arbitrary_number(target_cap - head_len);
1375 // ignore-tidy-undocumented-unsafe
1376 unsafe {
1377 // can't use `copy_nonoverlapping()` here because the new and old
1378 // regions for the head might overlap.
1379 self.copy(self.head, new_head, head_len);
1380 }
1381 self.head = new_head;
1382 }
1383
1384 struct Guard<'a, T, A: Allocator> {
1385 deque: &'a mut VecDeque<T, A>,
1386 old_head: WrappedIndex,
1387 target_cap: usize,
1388 }
1389
1390 impl<T, A: Allocator> Drop for Guard<'_, T, A> {
1391 #[cold]
1392 fn drop(&mut self) {
1393 // SAFETY: This is only called if `buf.shrink_to_fit` unwinds,
1394 // which is the only time it's safe to call `abort_shrink`.
1395 unsafe { self.deque.abort_shrink(self.old_head, self.target_cap) }
1396 }
1397 }
1398
1399 let guard = Guard { deque: self, old_head, target_cap };
1400
1401 guard.deque.buf.shrink_to_fit(target_cap);
1402
1403 // Don't drop the guard if we didn't unwind.
1404 mem::forget(guard);
1405
1406 debug_assert!(self.head < self.capacity() || self.capacity() == 0);
1407 debug_assert!(self.len <= self.capacity());
1408 }
1409
1410 /// Reverts the deque back into a consistent state in case `shrink_to` failed.
1411 /// This is necessary to prevent UB if the backing allocator returns an error
1412 /// from `shrink` and `handle_alloc_error` subsequently unwinds (see #123369).
1413 ///
1414 /// `old_head` refers to the head index before `shrink_to` was called. `target_cap`
1415 /// is the capacity that it was trying to shrink to.
1416 unsafe fn abort_shrink(&mut self, old_head: WrappedIndex, target_cap: usize) {
1417 // Moral equivalent of self.head + self.len <= target_cap. Won't overflow
1418 // because `self.len <= target_cap`.
1419 if self.head <= target_cap - self.len {
1420 // The deque's buffer is contiguous, so no need to copy anything around.
1421 return;
1422 }
1423
1424 // `shrink_to` already copied the head to fit into the new capacity, so this won't overflow.
1425 let head_len = target_cap - self.head.as_index();
1426 // `self.head > target_cap - self.len` => `self.len > target_cap - self.head =: head_len` so this must be positive.
1427 let tail_len = self.len - head_len;
1428
1429 if tail_len <= cmp::min(head_len, self.capacity() - target_cap) {
1430 // There's enough spare capacity to copy the tail to the back (because `tail_len < self.capacity() - target_cap`),
1431 // and copying the tail should be cheaper than copying the head (because `tail_len <= head_len`).
1432
1433 // SAFETY: The old tail and the new tail can't overlap because the head slice lies
1434 // between them. The head slice ends at `target_cap`, so that's where we copy to.
1435 unsafe {
1436 self.copy_nonoverlapping(
1437 WrappedIndex::zero(),
1438 WrappedIndex::from_arbitrary_number(target_cap),
1439 tail_len,
1440 );
1441 }
1442 } else {
1443 // Either there's not enough spare capacity to make the deque contiguous, or the head is shorter than the tail
1444 // (and therefore hopefully cheaper to copy).
1445 // ignore-tidy-undocumented-unsafe
1446 unsafe {
1447 // The old and the new head slice can overlap, so we can't use `copy_nonoverlapping` here.
1448 self.copy(self.head, old_head, head_len);
1449 self.head = old_head;
1450 }
1451 }
1452 }
1453
1454 /// Shortens the deque, keeping the first `len` elements and dropping
1455 /// the rest.
1456 ///
1457 /// If `len` is greater or equal to the deque's current length, this has
1458 /// no effect.
1459 ///
1460 /// # Examples
1461 ///
1462 /// ```
1463 /// use std::collections::VecDeque;
1464 ///
1465 /// let mut buf = VecDeque::new();
1466 /// buf.push_back(5);
1467 /// buf.push_back(10);
1468 /// buf.push_back(15);
1469 /// assert_eq!(buf, [5, 10, 15]);
1470 /// buf.truncate(1);
1471 /// assert_eq!(buf, [5]);
1472 /// ```
1473 #[doc(alias = "retain_front")]
1474 #[stable(feature = "deque_extras", since = "1.16.0")]
1475 pub fn truncate(&mut self, len: usize) {
1476 if len >= self.len {
1477 return;
1478 }
1479
1480 let (front, back) = self.as_mut_slices();
1481
1482 // SAFETY:
1483 // * Any slice passed to `drop_in_place` is valid; the second case has
1484 // `len <= front.len()` and returning on `len >= self.len()` ensures
1485 // `begin < back.len()` in the first case
1486 // * The head of the VecDeque is moved before calling `drop_in_place`,
1487 // so no value is dropped twice if `drop_in_place` panics
1488 unsafe {
1489 if len > front.len() {
1490 let begin = len - front.len();
1491 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
1492 self.len = len;
1493 ptr::drop_in_place(drop_back);
1494 } else {
1495 let drop_back = back as *mut _;
1496 let drop_front = front.get_unchecked_mut(len..) as *mut _;
1497 self.len = len;
1498
1499 // Make sure the second half is dropped even when a destructor
1500 // in the first one panics.
1501 let _back_dropper = Dropper(&mut *drop_back);
1502 ptr::drop_in_place(drop_front);
1503 }
1504 }
1505 }
1506
1507 /// Shortens the deque, keeping the last `len` elements and dropping
1508 /// the rest.
1509 ///
1510 /// If `len` is greater or equal to the deque's current length, this has
1511 /// no effect.
1512 ///
1513 /// # Examples
1514 ///
1515 /// ```
1516 /// use std::collections::VecDeque;
1517 ///
1518 /// let mut buf = VecDeque::new();
1519 /// buf.push_front(5);
1520 /// buf.push_front(10);
1521 /// buf.push_front(15);
1522 /// assert_eq!(buf, [15, 10, 5]);
1523 /// assert_eq!(buf.as_slices(), (&[15, 10, 5][..], &[][..]));
1524 /// buf.retain_back(1);
1525 /// assert_eq!(buf.as_slices(), (&[5][..], &[][..]));
1526 /// ```
1527 #[doc(alias = "truncate_front")]
1528 #[stable(feature = "vec_deque_truncate_front", since = "1.99.0")]
1529 pub fn retain_back(&mut self, len: usize) {
1530 if len >= self.len {
1531 // No action is taken
1532 return;
1533 }
1534
1535 let (front, back) = self.as_mut_slices();
1536
1537 // ignore-tidy-undocumented-unsafe
1538 unsafe {
1539 if len > back.len() {
1540 // The 'back' slice remains unchanged.
1541 // front.len() + back.len() == self.len, so 'end' is non-negative
1542 // and end < front.len()
1543 let end = front.len() - (len - back.len());
1544 let drop_front = front.get_unchecked_mut(..end) as *mut _;
1545 self.head = self.head.add(end);
1546 self.len = len;
1547 ptr::drop_in_place(drop_front);
1548 } else {
1549 let drop_front = front as *mut _;
1550 // 'end' is non-negative by the condition above
1551 let end = back.len() - len;
1552 let drop_back = back.get_unchecked_mut(..end) as *mut _;
1553 self.head = self.to_wrapped_index(self.len - len);
1554 self.len = len;
1555
1556 // Make sure the second half is dropped even when a destructor
1557 // in the first one panics.
1558 let _back_dropper = Dropper(&mut *drop_back);
1559 ptr::drop_in_place(drop_front);
1560 }
1561 }
1562 }
1563
1564 /// Shortens the deque to the elements within `range`, dropping the rest.
1565 ///
1566 /// # Panics
1567 ///
1568 /// Panics if the starting point is greater than the end point or if
1569 /// the end point is greater than the length of the deque.
1570 ///
1571 /// # Examples
1572 ///
1573 /// ```
1574 /// # #![feature(vec_deque_retain_range)]
1575 /// use std::collections::VecDeque;
1576 ///
1577 /// let mut buf: VecDeque<_> = (0..6).collect();
1578 /// buf.truncate_to_range(2..5);
1579 /// assert_eq!(buf, [2, 3, 4]);
1580 /// ```
1581 #[unstable(feature = "vec_deque_retain_range", issue = "156215")]
1582 pub fn truncate_to_range<R>(&mut self, range: R)
1583 where
1584 R: RangeBounds<usize>,
1585 {
1586 let Range { start, end } = slice::range(range, ..self.len);
1587
1588 if start == 0 && end == self.len {
1589 return;
1590 } else if start == end {
1591 self.clear();
1592 return;
1593 } else if start == 0 {
1594 self.truncate(end);
1595 return;
1596 } else if end == self.len {
1597 self.retain_back(self.len - start);
1598 return;
1599 }
1600
1601 // Both the dropped prefix [0..start) and the dropped suffix [end..self.len) are
1602 // non-empty. Plan up to three physical slices to drop, then update head/len, then
1603 // drop. Only one of the dropped prefix or dropped suffix can cross between slices.
1604 let (front, back) = self.as_mut_slices();
1605 let flen = front.len();
1606 let blen = back.len();
1607 let fptr = front.as_mut_ptr();
1608 let bptr = back.as_mut_ptr();
1609
1610 // ignore-tidy-undocumented-unsafe
1611 unsafe {
1612 let (drop_a, drop_b, drop_c) = if end <= flen {
1613 // Kept range lies in `front`. The dropped suffix is the rest of `front`
1614 // plus all of `back`.
1615 let pre = ptr::slice_from_raw_parts_mut(fptr, start);
1616 let mid = ptr::slice_from_raw_parts_mut(fptr.add(end), flen - end);
1617 (pre, mid, Some(back as *mut [T]))
1618 } else if start >= flen {
1619 // Kept range lies in `back`. The dropped prefix is all of `front` plus the
1620 // start of `back`.
1621 let mid = ptr::slice_from_raw_parts_mut(bptr, start - flen);
1622 let suf = ptr::slice_from_raw_parts_mut(bptr.add(end - flen), blen - (end - flen));
1623 (front as *mut [T], mid, Some(suf))
1624 } else {
1625 // Kept range straddles the boundary. The dropped prefix is in `front`, the
1626 // dropped suffix is in `back`. Only two regions to drop.
1627 let pre = ptr::slice_from_raw_parts_mut(fptr, start);
1628 let suf = ptr::slice_from_raw_parts_mut(bptr.add(end - flen), blen - (end - flen));
1629 (pre, suf, None)
1630 };
1631
1632 // Set these once only, then drop. If we called truncate + retain_back, a panic in
1633 // a destructor could leave this truncation in a half completed state.
1634 self.head = self.to_wrapped_index(start);
1635 self.len = end - start;
1636
1637 match drop_c {
1638 Some(c) => {
1639 let _g_a = Dropper(&mut *drop_a);
1640 let _g_b = Dropper(&mut *drop_b);
1641 ptr::drop_in_place(c);
1642 }
1643 None => {
1644 let _g_a = Dropper(&mut *drop_a);
1645 ptr::drop_in_place(drop_b);
1646 }
1647 }
1648 }
1649 }
1650
1651 /// Returns a reference to the underlying allocator.
1652 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1653 #[inline]
1654 pub fn allocator(&self) -> &A {
1655 self.buf.allocator()
1656 }
1657
1658 /// Returns a front-to-back iterator.
1659 ///
1660 /// # Examples
1661 ///
1662 /// ```
1663 /// use std::collections::VecDeque;
1664 ///
1665 /// let mut buf = VecDeque::new();
1666 /// buf.push_back(5);
1667 /// buf.push_back(3);
1668 /// buf.push_back(4);
1669 /// let b: &[_] = &[&5, &3, &4];
1670 /// let c: Vec<&i32> = buf.iter().collect();
1671 /// assert_eq!(&c[..], b);
1672 /// ```
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_iter")]
1675 pub fn iter(&self) -> Iter<'_, T> {
1676 let (a, b) = self.as_slices();
1677 Iter::new(a.iter(), b.iter())
1678 }
1679
1680 /// Returns a front-to-back iterator that returns mutable references.
1681 ///
1682 /// # Examples
1683 ///
1684 /// ```
1685 /// use std::collections::VecDeque;
1686 ///
1687 /// let mut buf = VecDeque::new();
1688 /// buf.push_back(5);
1689 /// buf.push_back(3);
1690 /// buf.push_back(4);
1691 /// for num in buf.iter_mut() {
1692 /// *num = *num - 2;
1693 /// }
1694 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1695 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1696 /// ```
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1699 let (a, b) = self.as_mut_slices();
1700 IterMut::new(a.iter_mut(), b.iter_mut())
1701 }
1702
1703 /// Returns a pair of slices which contain, in order, the contents of the
1704 /// deque.
1705 ///
1706 /// If [`make_contiguous`] was previously called, all elements of the
1707 /// deque will be in the first slice and the second slice will be empty.
1708 /// Otherwise, the exact split point depends on implementation details
1709 /// and is not guaranteed.
1710 ///
1711 /// [`make_contiguous`]: VecDeque::make_contiguous
1712 ///
1713 /// # Examples
1714 ///
1715 /// ```
1716 /// use std::collections::VecDeque;
1717 ///
1718 /// let mut deque = VecDeque::new();
1719 ///
1720 /// deque.push_back(0);
1721 /// deque.push_back(1);
1722 /// deque.push_back(2);
1723 ///
1724 /// let expected = [0, 1, 2];
1725 /// let (front, back) = deque.as_slices();
1726 /// assert_eq!(&expected[..front.len()], front);
1727 /// assert_eq!(&expected[front.len()..], back);
1728 ///
1729 /// deque.push_front(10);
1730 /// deque.push_front(9);
1731 ///
1732 /// let expected = [9, 10, 0, 1, 2];
1733 /// let (front, back) = deque.as_slices();
1734 /// assert_eq!(&expected[..front.len()], front);
1735 /// assert_eq!(&expected[front.len()..], back);
1736 /// ```
1737 #[inline]
1738 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1739 pub fn as_slices(&self) -> (&[T], &[T]) {
1740 let (a_range, b_range) = self.slice_ranges(.., self.len);
1741 // SAFETY: `slice_ranges` always returns valid ranges into
1742 // the physical buffer.
1743 unsafe { (&*self.buffer_range(a_range), &*self.buffer_range(b_range)) }
1744 }
1745
1746 /// Returns a pair of slices which contain, in order, the contents of the
1747 /// deque.
1748 ///
1749 /// If [`make_contiguous`] was previously called, all elements of the
1750 /// deque will be in the first slice and the second slice will be empty.
1751 /// Otherwise, the exact split point depends on implementation details
1752 /// and is not guaranteed.
1753 ///
1754 /// [`make_contiguous`]: VecDeque::make_contiguous
1755 ///
1756 /// # Examples
1757 ///
1758 /// ```
1759 /// use std::collections::VecDeque;
1760 ///
1761 /// let mut deque = VecDeque::new();
1762 ///
1763 /// deque.push_back(0);
1764 /// deque.push_back(1);
1765 ///
1766 /// deque.push_front(10);
1767 /// deque.push_front(9);
1768 ///
1769 /// // Since the split point is not guaranteed, we may need to update
1770 /// // either slice.
1771 /// let mut update_nth = |index: usize, val: u32| {
1772 /// let (front, back) = deque.as_mut_slices();
1773 /// if index > front.len() - 1 {
1774 /// back[index - front.len()] = val;
1775 /// } else {
1776 /// front[index] = val;
1777 /// }
1778 /// };
1779 ///
1780 /// update_nth(0, 42);
1781 /// update_nth(2, 24);
1782 ///
1783 /// let v: Vec<_> = deque.into();
1784 /// assert_eq!(v, [42, 10, 24, 1]);
1785 /// ```
1786 #[inline]
1787 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1788 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1789 let (a_range, b_range) = self.slice_ranges(.., self.len);
1790 // SAFETY: `slice_ranges` always returns valid ranges into
1791 // the physical buffer.
1792 unsafe { (&mut *self.buffer_range(a_range), &mut *self.buffer_range(b_range)) }
1793 }
1794
1795 /// Returns the number of elements in the deque.
1796 ///
1797 /// # Examples
1798 ///
1799 /// ```
1800 /// use std::collections::VecDeque;
1801 ///
1802 /// let mut deque = VecDeque::new();
1803 /// assert_eq!(deque.len(), 0);
1804 /// deque.push_back(1);
1805 /// assert_eq!(deque.len(), 1);
1806 /// ```
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 #[rustc_const_stable(feature = "const_vec_deque_len", since = "1.101.0")]
1809 #[rustc_confusables("length", "size")]
1810 pub const fn len(&self) -> usize {
1811 self.len
1812 }
1813
1814 /// Returns `true` if the deque is empty.
1815 ///
1816 /// # Examples
1817 ///
1818 /// ```
1819 /// use std::collections::VecDeque;
1820 ///
1821 /// let mut deque = VecDeque::new();
1822 /// assert!(deque.is_empty());
1823 /// deque.push_front(1);
1824 /// assert!(!deque.is_empty());
1825 /// ```
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 #[rustc_const_stable(feature = "const_vec_deque_len", since = "1.101.0")]
1828 pub const fn is_empty(&self) -> bool {
1829 self.len == 0
1830 }
1831
1832 /// Given a range into the logical buffer of the deque, this function
1833 /// return two ranges into the physical buffer that correspond to
1834 /// the given range. The `len` parameter should usually just be `self.len`;
1835 /// the reason it's passed explicitly is that if the deque is wrapped in
1836 /// a `Drain`, then `self.len` is not actually the length of the deque.
1837 ///
1838 /// # Safety
1839 ///
1840 /// This function is always safe to call. For the resulting ranges to be valid
1841 /// ranges into the physical buffer, the caller must ensure that the result of
1842 /// calling `slice::range(range, ..len)` represents a valid range into the
1843 /// logical buffer, and that all elements in that range are initialized.
1844 fn slice_ranges<R>(&self, range: R, len: usize) -> (Range<usize>, Range<usize>)
1845 where
1846 R: RangeBounds<usize>,
1847 {
1848 let Range { start, end } = slice::range(range, ..len);
1849 let len = end - start;
1850
1851 if len == 0 {
1852 (0..0, 0..0)
1853 } else {
1854 // `slice::range` guarantees that `start <= end <= len`.
1855 // because `len != 0`, we know that `start < end`, so `start < len`
1856 // and the indexing is valid.
1857 let wrapped_start = self.to_wrapped_index(start);
1858
1859 // this subtraction can never overflow because `wrapped_start` is
1860 // at most `self.capacity()` (and if `self.capacity != 0`, then `wrapped_start` is strictly less
1861 // than `self.capacity`).
1862 let head_len = self.capacity() - wrapped_start.as_index();
1863
1864 if head_len >= len {
1865 // we know that `len + wrapped_start <= self.capacity <= usize::MAX`, so this addition can't overflow
1866 (wrapped_start.as_index()..wrapped_start + len, 0..0)
1867 } else {
1868 // can't overflow because of the if condition
1869 let tail_len = len - head_len;
1870 (wrapped_start.as_index()..self.capacity(), 0..tail_len)
1871 }
1872 }
1873 }
1874
1875 /// Creates an iterator that covers the specified range in the deque.
1876 ///
1877 /// # Panics
1878 ///
1879 /// Panics if the range has `start_bound > end_bound`, or, if the range is
1880 /// bounded on either end and past the length of the deque.
1881 ///
1882 /// # Examples
1883 ///
1884 /// ```
1885 /// use std::collections::VecDeque;
1886 ///
1887 /// let deque: VecDeque<_> = [1, 2, 3].into();
1888 /// let range = deque.range(2..).copied().collect::<VecDeque<_>>();
1889 /// assert_eq!(range, [3]);
1890 ///
1891 /// // A full range covers all contents
1892 /// let all = deque.range(..);
1893 /// assert_eq!(all.len(), 3);
1894 /// ```
1895 #[inline]
1896 #[stable(feature = "deque_range", since = "1.51.0")]
1897 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1898 where
1899 R: RangeBounds<usize>,
1900 {
1901 let (a_range, b_range) = self.slice_ranges(range, self.len);
1902 // SAFETY: The ranges returned by `slice_ranges`
1903 // are valid ranges into the physical buffer, so
1904 // it's ok to pass them to `buffer_range` and
1905 // dereference the result.
1906 let (a, b) = unsafe { (&*self.buffer_range(a_range), &*self.buffer_range(b_range)) };
1907
1908 Iter::new(a.iter(), b.iter())
1909 }
1910
1911 /// Creates an iterator that covers the specified mutable range in the deque.
1912 ///
1913 /// # Panics
1914 ///
1915 /// Panics if the range has `start_bound > end_bound`, or, if the range is
1916 /// bounded on either end and past the length of the deque.
1917 ///
1918 /// # Examples
1919 ///
1920 /// ```
1921 /// use std::collections::VecDeque;
1922 ///
1923 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1924 /// for v in deque.range_mut(2..) {
1925 /// *v *= 2;
1926 /// }
1927 /// assert_eq!(deque, [1, 2, 6]);
1928 ///
1929 /// // A full range covers all contents
1930 /// for v in deque.range_mut(..) {
1931 /// *v *= 2;
1932 /// }
1933 /// assert_eq!(deque, [2, 4, 12]);
1934 /// ```
1935 #[inline]
1936 #[stable(feature = "deque_range", since = "1.51.0")]
1937 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1938 where
1939 R: RangeBounds<usize>,
1940 {
1941 let (a_range, b_range) = self.slice_ranges(range, self.len);
1942 let (a, b) =
1943 // SAFETY: The ranges returned by `slice_ranges`
1944 // are valid ranges into the physical buffer, so
1945 // it's ok to pass them to `buffer_range` and
1946 // dereference the result.
1947 unsafe { (&mut *self.buffer_range(a_range), &mut *self.buffer_range(b_range)) };
1948
1949 IterMut::new(a.iter_mut(), b.iter_mut())
1950 }
1951
1952 /// Removes the specified range from the deque in bulk, returning all
1953 /// removed elements as an iterator. If the iterator is dropped before
1954 /// being fully consumed, it drops the remaining removed elements.
1955 ///
1956 /// The returned iterator keeps a mutable borrow on the queue to optimize
1957 /// its implementation.
1958 ///
1959 ///
1960 /// # Panics
1961 ///
1962 /// Panics if the range has `start_bound > end_bound`, or, if the range is
1963 /// bounded on either end and past the length of the deque.
1964 ///
1965 /// # Leaking
1966 ///
1967 /// If the returned iterator goes out of scope without being dropped (due to
1968 /// [`mem::forget`], for example), the deque may have lost and leaked
1969 /// elements arbitrarily, including elements outside the range.
1970 ///
1971 /// # Examples
1972 ///
1973 /// ```
1974 /// use std::collections::VecDeque;
1975 ///
1976 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1977 /// let drained = deque.drain(2..).collect::<VecDeque<_>>();
1978 /// assert_eq!(drained, [3]);
1979 /// assert_eq!(deque, [1, 2]);
1980 ///
1981 /// // A full range clears all contents, like `clear()` does
1982 /// deque.drain(..);
1983 /// assert!(deque.is_empty());
1984 /// ```
1985 #[inline]
1986 #[stable(feature = "drain", since = "1.6.0")]
1987 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1988 where
1989 R: RangeBounds<usize>,
1990 {
1991 // Memory safety
1992 //
1993 // When the Drain is first created, the source deque is shortened to
1994 // make sure no uninitialized or moved-from elements are accessible at
1995 // all if the Drain's destructor never gets to run.
1996 //
1997 // Drain will ptr::read out the values to remove.
1998 // When finished, the remaining data will be copied back to cover the hole,
1999 // and the head/tail values will be restored correctly.
2000 //
2001 let Range { start, end } = slice::range(range, ..self.len);
2002 let drain_start = start;
2003 let drain_len = end - start;
2004
2005 // The deque's elements are parted into three segments:
2006 // * 0 -> drain_start
2007 // * drain_start -> drain_start+drain_len
2008 // * drain_start+drain_len -> self.len
2009 //
2010 // H = self.head; T = self.head+self.len; t = drain_start+drain_len; h = drain_head
2011 //
2012 // We store drain_start as self.len, and drain_len and self.len as
2013 // drain_len and orig_len respectively on the Drain. This also
2014 // truncates the effective array such that if the Drain is leaked, we
2015 // have forgotten about the potentially moved values after the start of
2016 // the drain.
2017 //
2018 // H h t T
2019 // [. . . o o x x o o . . .]
2020 //
2021 // "forget" about the values after the start of the drain until after
2022 // the drain is complete and the Drain destructor is run.
2023
2024 // ignore-tidy-undocumented-unsafe
2025 unsafe { Drain::new(self, drain_start, drain_len) }
2026 }
2027
2028 /// Creates a splicing iterator that replaces the specified range in the deque with the given
2029 /// `replace_with` iterator and yields the removed items. `replace_with` does not need to be the
2030 /// same length as `range`.
2031 ///
2032 /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped.
2033 ///
2034 /// It is unspecified how many elements are removed from the deque if the `Splice` value is
2035 /// leaked.
2036 ///
2037 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2038 ///
2039 /// This is optimal if:
2040 ///
2041 /// * The tail (elements in the deque after `range`) is empty,
2042 /// * or `replace_with` yields fewer or equal elements than `range`'s length
2043 /// * or the lower bound of its `size_hint()` is exact.
2044 ///
2045 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2046 ///
2047 /// # Panics
2048 ///
2049 /// Panics if the range has `start_bound > end_bound`, or, if the range is
2050 /// bounded on either end and past the length of the deque.
2051 ///
2052 /// # Examples
2053 ///
2054 /// ```
2055 /// # #![feature(deque_extend_front)]
2056 /// # use std::collections::VecDeque;
2057 ///
2058 /// let mut v = VecDeque::from(vec![1, 2, 3, 4]);
2059 /// let new = [7, 8, 9];
2060 /// let u: Vec<_> = v.splice(1..3, new).collect();
2061 /// assert_eq!(v, [1, 7, 8, 9, 4]);
2062 /// assert_eq!(u, [2, 3]);
2063 /// ```
2064 ///
2065 /// Using `splice` to insert new items into a vector efficiently at a specific position
2066 /// indicated by an empty range:
2067 ///
2068 /// ```
2069 /// # #![feature(deque_extend_front)]
2070 /// # use std::collections::VecDeque;
2071 ///
2072 /// let mut v = VecDeque::from(vec![1, 5]);
2073 /// let new = [2, 3, 4];
2074 /// v.splice(1..1, new);
2075 /// assert_eq!(v, [1, 2, 3, 4, 5]);
2076 /// ```
2077 #[unstable(feature = "deque_extend_front", issue = "146975")]
2078 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2079 where
2080 R: RangeBounds<usize>,
2081 I: IntoIterator<Item = T>,
2082 {
2083 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2084 }
2085
2086 /// Clears the deque, removing all values.
2087 ///
2088 /// # Examples
2089 ///
2090 /// ```
2091 /// use std::collections::VecDeque;
2092 ///
2093 /// let mut deque = VecDeque::new();
2094 /// deque.push_back(1);
2095 /// deque.clear();
2096 /// assert!(deque.is_empty());
2097 /// ```
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 #[expect(clippy::manual_clear, reason = "implements clear")]
2100 #[inline]
2101 pub fn clear(&mut self) {
2102 self.truncate(0);
2103 // Not strictly necessary, but leaves things in a more consistent/predictable state.
2104 self.head = WrappedIndex::zero();
2105 }
2106
2107 /// Returns `true` if the deque contains an element equal to the
2108 /// given value.
2109 ///
2110 /// This operation is *O*(*n*).
2111 ///
2112 /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
2113 ///
2114 /// [`binary_search`]: VecDeque::binary_search
2115 ///
2116 /// # Examples
2117 ///
2118 /// ```
2119 /// use std::collections::VecDeque;
2120 ///
2121 /// let mut deque: VecDeque<u32> = VecDeque::new();
2122 ///
2123 /// deque.push_back(0);
2124 /// deque.push_back(1);
2125 ///
2126 /// assert_eq!(deque.contains(&1), true);
2127 /// assert_eq!(deque.contains(&10), false);
2128 /// ```
2129 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
2130 pub fn contains(&self, x: &T) -> bool
2131 where
2132 T: PartialEq<T>,
2133 {
2134 let (a, b) = self.as_slices();
2135 a.contains(x) || b.contains(x)
2136 }
2137
2138 /// Provides a reference to the front element, or `None` if the deque is
2139 /// empty.
2140 ///
2141 /// # Examples
2142 ///
2143 /// ```
2144 /// use std::collections::VecDeque;
2145 ///
2146 /// let mut d = VecDeque::new();
2147 /// assert_eq!(d.front(), None);
2148 ///
2149 /// d.push_back(1);
2150 /// d.push_back(2);
2151 /// assert_eq!(d.front(), Some(&1));
2152 /// ```
2153 #[stable(feature = "rust1", since = "1.0.0")]
2154 #[rustc_confusables("first")]
2155 pub fn front(&self) -> Option<&T> {
2156 self.get(0)
2157 }
2158
2159 /// Provides a mutable reference to the front element, or `None` if the
2160 /// deque is empty.
2161 ///
2162 /// # Examples
2163 ///
2164 /// ```
2165 /// use std::collections::VecDeque;
2166 ///
2167 /// let mut d = VecDeque::new();
2168 /// assert_eq!(d.front_mut(), None);
2169 ///
2170 /// d.push_back(1);
2171 /// d.push_back(2);
2172 /// match d.front_mut() {
2173 /// Some(x) => *x = 9,
2174 /// None => (),
2175 /// }
2176 /// assert_eq!(d.front(), Some(&9));
2177 /// ```
2178 #[stable(feature = "rust1", since = "1.0.0")]
2179 pub fn front_mut(&mut self) -> Option<&mut T> {
2180 self.get_mut(0)
2181 }
2182
2183 /// Provides a reference to the back element, or `None` if the deque is
2184 /// empty.
2185 ///
2186 /// # Examples
2187 ///
2188 /// ```
2189 /// use std::collections::VecDeque;
2190 ///
2191 /// let mut d = VecDeque::new();
2192 /// assert_eq!(d.back(), None);
2193 ///
2194 /// d.push_back(1);
2195 /// d.push_back(2);
2196 /// assert_eq!(d.back(), Some(&2));
2197 /// ```
2198 #[stable(feature = "rust1", since = "1.0.0")]
2199 #[rustc_confusables("last")]
2200 pub fn back(&self) -> Option<&T> {
2201 self.get(self.len.wrapping_sub(1))
2202 }
2203
2204 /// Provides a mutable reference to the back element, or `None` if the
2205 /// deque is empty.
2206 ///
2207 /// # Examples
2208 ///
2209 /// ```
2210 /// use std::collections::VecDeque;
2211 ///
2212 /// let mut d = VecDeque::new();
2213 /// assert_eq!(d.back(), None);
2214 ///
2215 /// d.push_back(1);
2216 /// d.push_back(2);
2217 /// match d.back_mut() {
2218 /// Some(x) => *x = 9,
2219 /// None => (),
2220 /// }
2221 /// assert_eq!(d.back(), Some(&9));
2222 /// ```
2223 #[stable(feature = "rust1", since = "1.0.0")]
2224 pub fn back_mut(&mut self) -> Option<&mut T> {
2225 self.get_mut(self.len.wrapping_sub(1))
2226 }
2227
2228 /// Removes the first element and returns it, or `None` if the deque is
2229 /// empty.
2230 ///
2231 /// # Examples
2232 ///
2233 /// ```
2234 /// use std::collections::VecDeque;
2235 ///
2236 /// let mut d = VecDeque::new();
2237 /// d.push_back(1);
2238 /// d.push_back(2);
2239 ///
2240 /// assert_eq!(d.pop_front(), Some(1));
2241 /// assert_eq!(d.pop_front(), Some(2));
2242 /// assert_eq!(d.pop_front(), None);
2243 /// ```
2244 #[stable(feature = "rust1", since = "1.0.0")]
2245 pub fn pop_front(&mut self) -> Option<T> {
2246 if self.is_empty() {
2247 None
2248 } else {
2249 let old_head = self.head;
2250 self.head = self.to_wrapped_index(1);
2251 self.len -= 1;
2252 // ignore-tidy-undocumented-unsafe
2253 unsafe {
2254 core::hint::assert_unchecked(self.len < self.capacity());
2255 Some(self.buffer_read(old_head))
2256 }
2257 }
2258 }
2259
2260 /// Removes the last element from the deque and returns it, or `None` if
2261 /// it is empty.
2262 ///
2263 /// # Examples
2264 ///
2265 /// ```
2266 /// use std::collections::VecDeque;
2267 ///
2268 /// let mut buf = VecDeque::new();
2269 /// assert_eq!(buf.pop_back(), None);
2270 /// buf.push_back(1);
2271 /// buf.push_back(3);
2272 /// assert_eq!(buf.pop_back(), Some(3));
2273 /// ```
2274 #[stable(feature = "rust1", since = "1.0.0")]
2275 pub fn pop_back(&mut self) -> Option<T> {
2276 if self.is_empty() {
2277 None
2278 } else {
2279 self.len -= 1;
2280 // ignore-tidy-undocumented-unsafe
2281 unsafe {
2282 core::hint::assert_unchecked(self.len < self.capacity());
2283 Some(self.buffer_read(self.to_wrapped_index(self.len)))
2284 }
2285 }
2286 }
2287
2288 /// Removes and returns the first element from the deque if the predicate
2289 /// returns `true`, or [`None`] if the predicate returns false or the deque
2290 /// is empty (the predicate will not be called in that case).
2291 ///
2292 /// # Examples
2293 ///
2294 /// ```
2295 /// use std::collections::VecDeque;
2296 ///
2297 /// let mut deque: VecDeque<i32> = vec![0, 1, 2, 3, 4].into();
2298 /// let pred = |x: &mut i32| *x % 2 == 0;
2299 ///
2300 /// assert_eq!(deque.pop_front_if(pred), Some(0));
2301 /// assert_eq!(deque, [1, 2, 3, 4]);
2302 /// assert_eq!(deque.pop_front_if(pred), None);
2303 /// ```
2304 #[stable(feature = "vec_deque_pop_if", since = "1.93.0")]
2305 pub fn pop_front_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2306 let first = self.front_mut()?;
2307 if predicate(first) { self.pop_front() } else { None }
2308 }
2309
2310 /// Removes and returns the last element from the deque if the predicate
2311 /// returns `true`, or [`None`] if the predicate returns false or the deque
2312 /// is empty (the predicate will not be called in that case).
2313 ///
2314 /// # Examples
2315 ///
2316 /// ```
2317 /// use std::collections::VecDeque;
2318 ///
2319 /// let mut deque: VecDeque<i32> = vec![0, 1, 2, 3, 4].into();
2320 /// let pred = |x: &mut i32| *x % 2 == 0;
2321 ///
2322 /// assert_eq!(deque.pop_back_if(pred), Some(4));
2323 /// assert_eq!(deque, [0, 1, 2, 3]);
2324 /// assert_eq!(deque.pop_back_if(pred), None);
2325 /// ```
2326 #[stable(feature = "vec_deque_pop_if", since = "1.93.0")]
2327 pub fn pop_back_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2328 let last = self.back_mut()?;
2329 if predicate(last) { self.pop_back() } else { None }
2330 }
2331
2332 /// Prepends an element to the deque.
2333 ///
2334 /// # Examples
2335 ///
2336 /// ```
2337 /// use std::collections::VecDeque;
2338 ///
2339 /// let mut d = VecDeque::new();
2340 /// d.push_front(1);
2341 /// d.push_front(2);
2342 /// assert_eq!(d.front(), Some(&2));
2343 /// ```
2344 #[stable(feature = "rust1", since = "1.0.0")]
2345 pub fn push_front(&mut self, value: T) {
2346 let _ = self.push_front_mut(value);
2347 }
2348
2349 /// Prepends an element to the deque, returning a reference to it.
2350 ///
2351 /// # Examples
2352 ///
2353 /// ```
2354 /// use std::collections::VecDeque;
2355 ///
2356 /// let mut d = VecDeque::from([1, 2, 3]);
2357 /// let x = d.push_front_mut(8);
2358 /// *x -= 1;
2359 /// assert_eq!(d.front(), Some(&7));
2360 /// ```
2361 #[stable(feature = "push_mut", since = "1.95.0")]
2362 #[must_use = "if you don't need a reference to the value, use `VecDeque::push_front` instead"]
2363 pub fn push_front_mut(&mut self, value: T) -> &mut T {
2364 if self.is_full() {
2365 self.grow();
2366 }
2367
2368 self.head = self.wrap_sub(self.head, 1);
2369 self.len += 1;
2370 // SAFETY: We know that self.head is within range of the deque.
2371 unsafe { self.buffer_write(self.head, value) }
2372 }
2373
2374 /// Appends an element to the back of the deque.
2375 ///
2376 /// # Examples
2377 ///
2378 /// ```
2379 /// use std::collections::VecDeque;
2380 ///
2381 /// let mut buf = VecDeque::new();
2382 /// buf.push_back(1);
2383 /// buf.push_back(3);
2384 /// assert_eq!(3, *buf.back().unwrap());
2385 /// ```
2386 #[stable(feature = "rust1", since = "1.0.0")]
2387 #[rustc_confusables("push", "put", "append")]
2388 pub fn push_back(&mut self, value: T) {
2389 let _ = self.push_back_mut(value);
2390 }
2391
2392 /// Appends an element to the back of the deque, returning a reference to it.
2393 ///
2394 /// # Examples
2395 ///
2396 /// ```
2397 /// use std::collections::VecDeque;
2398 ///
2399 /// let mut d = VecDeque::from([1, 2, 3]);
2400 /// let x = d.push_back_mut(9);
2401 /// *x += 1;
2402 /// assert_eq!(d.back(), Some(&10));
2403 /// ```
2404 #[stable(feature = "push_mut", since = "1.95.0")]
2405 #[must_use = "if you don't need a reference to the value, use `VecDeque::push_back` instead"]
2406 pub fn push_back_mut(&mut self, value: T) -> &mut T {
2407 if self.is_full() {
2408 self.grow();
2409 }
2410
2411 let len = self.len;
2412 self.len += 1;
2413 // ignore-tidy-undocumented-unsafe
2414 unsafe { self.buffer_write(self.to_wrapped_index(len), value) }
2415 }
2416
2417 /// Prepends all contents of the iterator to the front of the deque.
2418 /// The order of the contents is preserved.
2419 ///
2420 /// To get behavior like [`append`][VecDeque::append] where elements are moved
2421 /// from the other collection to this one, use `self.prepend(other.drain(..))`.
2422 ///
2423 /// # Examples
2424 ///
2425 /// ```
2426 /// #![feature(deque_extend_front)]
2427 /// use std::collections::VecDeque;
2428 ///
2429 /// let mut deque = VecDeque::from([4, 5, 6]);
2430 /// deque.prepend([1, 2, 3]);
2431 /// assert_eq!(deque, [1, 2, 3, 4, 5, 6]);
2432 /// ```
2433 ///
2434 /// Move values between collections like [`append`][VecDeque::append] does but prepend to the front:
2435 ///
2436 /// ```
2437 /// #![feature(deque_extend_front)]
2438 /// use std::collections::VecDeque;
2439 ///
2440 /// let mut deque1 = VecDeque::from([4, 5, 6]);
2441 /// let mut deque2 = VecDeque::from([1, 2, 3]);
2442 /// deque1.prepend(deque2.drain(..));
2443 /// assert_eq!(deque1, [1, 2, 3, 4, 5, 6]);
2444 /// assert!(deque2.is_empty());
2445 /// ```
2446 #[unstable(feature = "deque_extend_front", issue = "146975")]
2447 #[track_caller]
2448 pub fn prepend<I: IntoIterator<Item = T, IntoIter: DoubleEndedIterator>>(&mut self, other: I) {
2449 self.extend_front(other.into_iter().rev())
2450 }
2451
2452 /// Prepends all contents of the iterator to the front of the deque,
2453 /// as if [`push_front`][VecDeque::push_front] was called repeatedly with
2454 /// the values yielded by the iterator.
2455 ///
2456 /// # Examples
2457 ///
2458 /// ```
2459 /// #![feature(deque_extend_front)]
2460 /// use std::collections::VecDeque;
2461 ///
2462 /// let mut deque = VecDeque::from([4, 5, 6]);
2463 /// deque.extend_front([3, 2, 1]);
2464 /// assert_eq!(deque, [1, 2, 3, 4, 5, 6]);
2465 /// ```
2466 ///
2467 /// This behaves like [`push_front`][VecDeque::push_front] was called repeatedly:
2468 ///
2469 /// ```
2470 /// use std::collections::VecDeque;
2471 ///
2472 /// let mut deque = VecDeque::from([4, 5, 6]);
2473 /// for v in [3, 2, 1] {
2474 /// deque.push_front(v);
2475 /// }
2476 /// assert_eq!(deque, [1, 2, 3, 4, 5, 6]);
2477 /// ```
2478 #[unstable(feature = "deque_extend_front", issue = "146975")]
2479 #[track_caller]
2480 pub fn extend_front<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2481 <Self as SpecExtendFront<T, I::IntoIter>>::spec_extend_front(self, iter.into_iter());
2482 }
2483
2484 #[inline]
2485 fn is_contiguous(&self) -> bool {
2486 // Do the calculation like this to avoid overflowing if len + head > usize::MAX
2487 self.head <= self.capacity() - self.len
2488 }
2489
2490 /// Removes an element from anywhere in the deque and returns it,
2491 /// replacing it with the first element.
2492 ///
2493 /// This does not preserve ordering, but is *O*(1).
2494 ///
2495 /// Returns `None` if `index` is out of bounds.
2496 ///
2497 /// Element at index 0 is the front of the queue.
2498 ///
2499 /// # Examples
2500 ///
2501 /// ```
2502 /// use std::collections::VecDeque;
2503 ///
2504 /// let mut buf = VecDeque::new();
2505 /// assert_eq!(buf.swap_remove_front(0), None);
2506 /// buf.push_back(1);
2507 /// buf.push_back(2);
2508 /// buf.push_back(3);
2509 /// assert_eq!(buf, [1, 2, 3]);
2510 ///
2511 /// assert_eq!(buf.swap_remove_front(2), Some(3));
2512 /// assert_eq!(buf, [2, 1]);
2513 /// ```
2514 #[stable(feature = "deque_extras_15", since = "1.5.0")]
2515 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
2516 let length = self.len;
2517 if index < length && index != 0 {
2518 self.swap(index, 0);
2519 } else if index >= length {
2520 return None;
2521 }
2522 self.pop_front()
2523 }
2524
2525 /// Removes an element from anywhere in the deque and returns it,
2526 /// replacing it with the last element.
2527 ///
2528 /// This does not preserve ordering, but is *O*(1).
2529 ///
2530 /// Returns `None` if `index` is out of bounds.
2531 ///
2532 /// Element at index 0 is the front of the queue.
2533 ///
2534 /// # Examples
2535 ///
2536 /// ```
2537 /// use std::collections::VecDeque;
2538 ///
2539 /// let mut buf = VecDeque::new();
2540 /// assert_eq!(buf.swap_remove_back(0), None);
2541 /// buf.push_back(1);
2542 /// buf.push_back(2);
2543 /// buf.push_back(3);
2544 /// assert_eq!(buf, [1, 2, 3]);
2545 ///
2546 /// assert_eq!(buf.swap_remove_back(0), Some(1));
2547 /// assert_eq!(buf, [3, 2]);
2548 /// ```
2549 #[stable(feature = "deque_extras_15", since = "1.5.0")]
2550 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
2551 let length = self.len;
2552 if length > 0 && index < length - 1 {
2553 self.swap(index, length - 1);
2554 } else if index >= length {
2555 return None;
2556 }
2557 self.pop_back()
2558 }
2559
2560 /// Inserts an element at `index` within the deque, shifting all elements
2561 /// with indices greater than or equal to `index` towards the back.
2562 ///
2563 /// Element at index 0 is the front of the queue.
2564 ///
2565 /// # Panics
2566 ///
2567 /// Panics if `index` is strictly greater than the deque's length.
2568 ///
2569 /// # Examples
2570 ///
2571 /// ```
2572 /// use std::collections::VecDeque;
2573 ///
2574 /// let mut vec_deque = VecDeque::new();
2575 /// vec_deque.push_back('a');
2576 /// vec_deque.push_back('b');
2577 /// vec_deque.push_back('c');
2578 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
2579 ///
2580 /// vec_deque.insert(1, 'd');
2581 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
2582 ///
2583 /// vec_deque.insert(4, 'e');
2584 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c', 'e']);
2585 /// ```
2586 #[stable(feature = "deque_extras_15", since = "1.5.0")]
2587 pub fn insert(&mut self, index: usize, value: T) {
2588 let _ = self.insert_mut(index, value);
2589 }
2590
2591 /// Inserts an element at `index` within the deque, shifting all elements
2592 /// with indices greater than or equal to `index` towards the back, and
2593 /// returning a reference to it.
2594 ///
2595 /// Element at index 0 is the front of the queue.
2596 ///
2597 /// # Panics
2598 ///
2599 /// Panics if `index` is strictly greater than the deque's length.
2600 ///
2601 /// # Examples
2602 ///
2603 /// ```
2604 /// use std::collections::VecDeque;
2605 ///
2606 /// let mut vec_deque = VecDeque::from([1, 2, 3]);
2607 ///
2608 /// let x = vec_deque.insert_mut(1, 5);
2609 /// *x += 7;
2610 /// assert_eq!(vec_deque, &[1, 12, 2, 3]);
2611 /// ```
2612 #[stable(feature = "push_mut", since = "1.95.0")]
2613 #[must_use = "if you don't need a reference to the value, use `VecDeque::insert` instead"]
2614 pub fn insert_mut(&mut self, index: usize, value: T) -> &mut T {
2615 assert!(index <= self.len(), "index out of bounds");
2616
2617 if self.is_full() {
2618 self.grow();
2619 }
2620
2621 let k = self.len - index;
2622 if k < index {
2623 // `index + 1` can't overflow, because if index was usize::MAX, then either the
2624 // assert would've failed, or the deque would've tried to grow past usize::MAX
2625 // and panicked.
2626 // ignore-tidy-undocumented-unsafe
2627 unsafe {
2628 // see `remove()` for explanation why this wrap_copy() call is safe.
2629 self.wrap_copy(self.to_wrapped_index(index), self.to_wrapped_index(index + 1), k);
2630 self.len += 1;
2631 self.buffer_write(self.to_wrapped_index(index), value)
2632 }
2633 } else {
2634 let old_head = self.head;
2635 self.head = self.wrap_sub(self.head, 1);
2636 // ignore-tidy-undocumented-unsafe
2637 unsafe {
2638 self.wrap_copy(old_head, self.head, index);
2639 self.len += 1;
2640 self.buffer_write(self.to_wrapped_index(index), value)
2641 }
2642 }
2643 }
2644
2645 /// Removes and returns the element at `index` from the deque.
2646 /// Whichever end is closer to the removal point will be moved to make
2647 /// room, and all the affected elements will be moved to new positions.
2648 /// Returns `None` if `index` is out of bounds.
2649 ///
2650 /// Element at index 0 is the front of the queue.
2651 ///
2652 /// # Examples
2653 ///
2654 /// ```
2655 /// use std::collections::VecDeque;
2656 ///
2657 /// let mut buf = VecDeque::new();
2658 /// buf.push_back('a');
2659 /// buf.push_back('b');
2660 /// buf.push_back('c');
2661 /// assert_eq!(buf, ['a', 'b', 'c']);
2662 ///
2663 /// assert_eq!(buf.remove(1), Some('b'));
2664 /// assert_eq!(buf, ['a', 'c']);
2665 /// ```
2666 #[stable(feature = "rust1", since = "1.0.0")]
2667 #[rustc_confusables("delete", "take")]
2668 pub fn remove(&mut self, index: usize) -> Option<T> {
2669 if self.len <= index {
2670 return None;
2671 }
2672
2673 let wrapped_idx = self.to_wrapped_index(index);
2674
2675 // ignore-tidy-undocumented-unsafe
2676 let elem = unsafe { Some(self.buffer_read(wrapped_idx)) };
2677
2678 let k = self.len - index - 1;
2679 if k < index {
2680 // SAFETY: due to the nature of the if-condition, whichever wrap_copy gets called,
2681 // its length argument will be at most `self.len / 2`, so there can't be more than
2682 // one overlapping area.
2683 unsafe { self.wrap_copy(self.wrap_add(wrapped_idx, 1), wrapped_idx, k) };
2684 self.len -= 1;
2685 } else {
2686 let old_head = self.head;
2687 self.head = self.to_wrapped_index(1);
2688 // ignore-tidy-undocumented-unsafe
2689 unsafe { self.wrap_copy(old_head, self.head, index) };
2690 self.len -= 1;
2691 }
2692
2693 elem
2694 }
2695
2696 /// Splits the deque into two at the given index.
2697 ///
2698 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2699 /// and the returned deque contains elements `[at, len)`.
2700 ///
2701 /// Note that the capacity of `self` does not change.
2702 ///
2703 /// Element at index 0 is the front of the queue.
2704 ///
2705 /// # Panics
2706 ///
2707 /// Panics if `at > len`.
2708 ///
2709 /// # Examples
2710 ///
2711 /// ```
2712 /// use std::collections::VecDeque;
2713 ///
2714 /// let mut buf: VecDeque<_> = ['a', 'b', 'c'].into();
2715 /// let buf2 = buf.split_off(1);
2716 /// assert_eq!(buf, ['a']);
2717 /// assert_eq!(buf2, ['b', 'c']);
2718 /// ```
2719 #[inline]
2720 #[must_use = "use `.truncate()` if you don't need the other half"]
2721 #[stable(feature = "split_off", since = "1.4.0")]
2722 pub fn split_off(&mut self, at: usize) -> Self
2723 where
2724 A: Clone,
2725 {
2726 let len = self.len;
2727 assert!(at <= len, "`at` out of bounds");
2728
2729 let other_len = len - at;
2730 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2731
2732 let (first_half, second_half) = self.as_slices();
2733 let first_len = first_half.len();
2734 let second_len = second_half.len();
2735
2736 // ignore-tidy-undocumented-unsafe
2737 unsafe {
2738 if at < first_len {
2739 // `at` lies in the first half.
2740 let amount_in_first = first_len - at;
2741
2742 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2743
2744 // just take all of the second half.
2745 ptr::copy_nonoverlapping(
2746 second_half.as_ptr(),
2747 other.ptr().add(amount_in_first),
2748 second_len,
2749 );
2750 } else {
2751 // `at` lies in the second half, need to factor in the elements we skipped
2752 // in the first half.
2753 let offset = at - first_len;
2754 let amount_in_second = second_len - offset;
2755 ptr::copy_nonoverlapping(
2756 second_half.as_ptr().add(offset),
2757 other.ptr(),
2758 amount_in_second,
2759 );
2760 }
2761 }
2762
2763 // Cleanup where the ends of the buffers are
2764 self.len = at;
2765 other.len = other_len;
2766
2767 other
2768 }
2769
2770 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2771 ///
2772 /// # Panics
2773 ///
2774 /// Panics if the new number of elements in self overflows a `usize`.
2775 ///
2776 /// # Examples
2777 ///
2778 /// ```
2779 /// use std::collections::VecDeque;
2780 ///
2781 /// let mut buf: VecDeque<_> = [1, 2].into();
2782 /// let mut buf2: VecDeque<_> = [3, 4].into();
2783 /// buf.append(&mut buf2);
2784 /// assert_eq!(buf, [1, 2, 3, 4]);
2785 /// assert_eq!(buf2, []);
2786 /// ```
2787 #[inline]
2788 #[stable(feature = "append", since = "1.4.0")]
2789 pub fn append(&mut self, other: &mut Self) {
2790 if T::IS_ZST {
2791 self.len = self.len.checked_add(other.len).expect("capacity overflow");
2792 other.len = 0;
2793 other.head = WrappedIndex::zero();
2794 return;
2795 }
2796
2797 self.reserve(other.len);
2798 let (left, right) = other.as_slices();
2799 // ignore-tidy-undocumented-unsafe
2800 unsafe {
2801 self.copy_slice(self.to_wrapped_index(self.len), left);
2802 // no overflow, because self.capacity() >= old_cap + left.len() >= self.len + left.len()
2803 self.copy_slice(self.to_wrapped_index(self.len + left.len()), right);
2804 }
2805 // SAFETY: Update pointers after copying to avoid leaving doppelganger
2806 // in case of panics.
2807 self.len += other.len;
2808 // Now that we own its values, forget everything in `other`.
2809 other.len = 0;
2810 other.head = WrappedIndex::zero();
2811 }
2812
2813 /// Retains only the elements specified by the predicate.
2814 ///
2815 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2816 /// This method operates in place, visiting each element exactly once in the
2817 /// original order, and preserves the order of the retained elements.
2818 ///
2819 /// # Examples
2820 ///
2821 /// ```
2822 /// use std::collections::VecDeque;
2823 ///
2824 /// let mut buf = VecDeque::new();
2825 /// buf.extend(1..5);
2826 /// buf.retain(|&x| x % 2 == 0);
2827 /// assert_eq!(buf, [2, 4]);
2828 /// ```
2829 ///
2830 /// Because the elements are visited exactly once in the original order,
2831 /// external state may be used to decide which elements to keep.
2832 ///
2833 /// ```
2834 /// use std::collections::VecDeque;
2835 ///
2836 /// let mut buf = VecDeque::new();
2837 /// buf.extend(1..6);
2838 ///
2839 /// let keep = [false, true, true, false, true];
2840 /// let mut iter = keep.iter();
2841 /// buf.retain(|_| *iter.next().unwrap());
2842 /// assert_eq!(buf, [2, 3, 5]);
2843 /// ```
2844 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2845 pub fn retain<F>(&mut self, mut f: F)
2846 where
2847 F: FnMut(&T) -> bool,
2848 {
2849 self.retain_mut(|elem| f(elem));
2850 }
2851
2852 /// Retains only the elements specified by the predicate.
2853 ///
2854 /// In other words, remove all elements `e` for which `f(&mut e)` returns false.
2855 /// This method operates in place, visiting each element exactly once in the
2856 /// original order, and preserves the order of the retained elements.
2857 ///
2858 /// # Examples
2859 ///
2860 /// ```
2861 /// use std::collections::VecDeque;
2862 ///
2863 /// let mut buf = VecDeque::new();
2864 /// buf.extend(1..5);
2865 /// buf.retain_mut(|x| if *x % 2 == 0 {
2866 /// *x += 1;
2867 /// true
2868 /// } else {
2869 /// false
2870 /// });
2871 /// assert_eq!(buf, [3, 5]);
2872 /// ```
2873 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2874 pub fn retain_mut<F>(&mut self, f: F)
2875 where
2876 F: FnMut(&mut T) -> bool,
2877 {
2878 let (buf, head, cap) = (self.ptr(), self.head.as_index(), self.capacity());
2879 let front_len = cmp::min(cap - head, self.len());
2880 // SAFETY: Initialized elements are splitted into two regions,
2881 // `head..head + front_len` and `0..self.len - front_len`.
2882 // Specify `SINGLE_REGION` false because `front_len` might not equal `self.len`.
2883 unsafe { retain_raw::<false, _, _>(buf.add(head), front_len, buf, &mut self.len, f) }
2884 }
2885
2886 // Double the buffer size. This method is inline(never), so we expect it to only
2887 // be called in cold paths.
2888 // This may panic or abort
2889 #[inline(never)]
2890 fn grow(&mut self) {
2891 // Extend or possibly remove this assertion when valid use-cases for growing the
2892 // buffer without it being full emerge
2893 debug_assert!(self.is_full());
2894 let old_cap = self.capacity();
2895 self.buf.grow_one();
2896 // ignore-tidy-undocumented-unsafe
2897 unsafe {
2898 self.handle_capacity_increase(old_cap);
2899 }
2900 debug_assert!(!self.is_full());
2901 }
2902
2903 /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2904 /// either by removing excess elements from the back or by appending
2905 /// elements generated by calling `generator` to the back.
2906 ///
2907 /// # Examples
2908 ///
2909 /// ```
2910 /// use std::collections::VecDeque;
2911 ///
2912 /// let mut buf = VecDeque::new();
2913 /// buf.push_back(5);
2914 /// buf.push_back(10);
2915 /// buf.push_back(15);
2916 /// assert_eq!(buf, [5, 10, 15]);
2917 ///
2918 /// buf.resize_with(5, Default::default);
2919 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2920 ///
2921 /// buf.resize_with(2, || unreachable!());
2922 /// assert_eq!(buf, [5, 10]);
2923 ///
2924 /// let mut state = 100;
2925 /// buf.resize_with(5, || { state += 1; state });
2926 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2927 /// ```
2928 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2929 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2930 let len = self.len;
2931
2932 if new_len > len {
2933 self.extend(repeat_with(generator).take(new_len - len))
2934 } else {
2935 self.truncate(new_len);
2936 }
2937 }
2938
2939 /// Rearranges the internal storage of this deque so it is one contiguous
2940 /// slice, which is then returned.
2941 ///
2942 /// This method does not allocate and does not change the order of the
2943 /// inserted elements. As it returns a mutable slice, this can be used to
2944 /// sort a deque.
2945 ///
2946 /// Once the internal storage is contiguous, the [`as_slices`] and
2947 /// [`as_mut_slices`] methods will return the entire contents of the
2948 /// deque in a single slice.
2949 ///
2950 /// [`as_slices`]: VecDeque::as_slices
2951 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2952 ///
2953 /// # Examples
2954 ///
2955 /// Sorting the content of a deque.
2956 ///
2957 /// ```
2958 /// use std::collections::VecDeque;
2959 ///
2960 /// let mut buf = VecDeque::with_capacity(15);
2961 ///
2962 /// buf.push_back(2);
2963 /// buf.push_back(1);
2964 /// buf.push_front(3);
2965 ///
2966 /// // sorting the deque
2967 /// buf.make_contiguous().sort();
2968 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2969 ///
2970 /// // sorting it in reverse order
2971 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2972 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2973 /// ```
2974 ///
2975 /// Getting immutable access to the contiguous slice.
2976 ///
2977 /// ```rust
2978 /// use std::collections::VecDeque;
2979 ///
2980 /// let mut buf = VecDeque::new();
2981 ///
2982 /// buf.push_back(2);
2983 /// buf.push_back(1);
2984 /// buf.push_front(3);
2985 ///
2986 /// buf.make_contiguous();
2987 /// if let (slice, &[]) = buf.as_slices() {
2988 /// // we can now be sure that `slice` contains all elements of the deque,
2989 /// // while still having immutable access to `buf`.
2990 /// assert_eq!(buf.len(), slice.len());
2991 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2992 /// }
2993 /// ```
2994 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2995 pub fn make_contiguous(&mut self) -> &mut [T] {
2996 if T::IS_ZST {
2997 self.head = WrappedIndex::zero();
2998 }
2999
3000 if self.is_contiguous() {
3001 // ignore-tidy-undocumented-unsafe
3002 unsafe {
3003 return slice::from_raw_parts_mut(self.ptr().add(self.head.as_index()), self.len);
3004 }
3005 }
3006
3007 let &mut Self { head, len, .. } = self;
3008 let ptr = self.ptr();
3009 let cap = self.capacity();
3010
3011 let free = cap - len;
3012 let head_len = cap - head.as_index();
3013
3014 // tail <= head < capacity
3015 // head cannot be >= capacity, because we know that VecDeque is non-empty, since it is not
3016 // contiguous at this point
3017 let tail = WrappedIndex::from_arbitrary_number(len - head_len);
3018 let tail_len = tail.as_index();
3019
3020 if free >= head_len {
3021 // there is enough free space to copy the head in one go,
3022 // this means that we first shift the tail backwards, and then
3023 // copy the head to the correct position.
3024 //
3025 // from: DEFGH....ABC
3026 // to: ABCDEFGH....
3027 // ignore-tidy-undocumented-unsafe
3028 unsafe {
3029 self.copy(
3030 WrappedIndex::zero(),
3031 WrappedIndex::from_arbitrary_number(head_len),
3032 tail_len,
3033 );
3034 // ...DEFGH.ABC
3035 self.copy_nonoverlapping(head, WrappedIndex::zero(), head_len);
3036 // ABCDEFGH....
3037 }
3038
3039 self.head = WrappedIndex::zero();
3040 } else if free >= tail_len {
3041 // there is enough free space to copy the tail in one go,
3042 // this means that we first shift the head forwards, and then
3043 // copy the tail to the correct position.
3044 //
3045 // from: FGH....ABCDE
3046 // to: ...ABCDEFGH.
3047 // ignore-tidy-undocumented-unsafe
3048 unsafe {
3049 self.copy(head, tail, head_len);
3050 // FGHABCDE....
3051 self.copy_nonoverlapping(WrappedIndex::zero(), tail.add(head_len), tail_len);
3052 // ...ABCDEFGH.
3053 }
3054
3055 self.head = tail;
3056 } else {
3057 // `free` is smaller than both `head_len` and `tail_len`.
3058 // the general algorithm for this first moves the slices
3059 // right next to each other and then uses `slice::rotate`
3060 // to rotate them into place:
3061 //
3062 // initially: HIJK..ABCDEFG
3063 // step 1: ..HIJKABCDEFG
3064 // step 2: ..ABCDEFGHIJK
3065 //
3066 // or:
3067 //
3068 // initially: FGHIJK..ABCDE
3069 // step 1: FGHIJKABCDE..
3070 // step 2: ABCDEFGHIJK..
3071
3072 // pick the shorter of the 2 slices to reduce the amount
3073 // of memory that needs to be moved around.
3074 if head_len > tail_len {
3075 // tail is shorter, so:
3076 // 1. copy tail forwards
3077 // 2. rotate used part of the buffer
3078 // 3. update head to point to the new beginning (which is just `free`)
3079
3080 // ignore-tidy-undocumented-unsafe
3081 unsafe {
3082 // if there is no free space in the buffer, then the slices are already
3083 // right next to each other and we don't need to move any memory.
3084 if free != 0 {
3085 // because we only move the tail forward as much as there's free space
3086 // behind it, we don't overwrite any elements of the head slice, and
3087 // the slices end up right next to each other.
3088 self.copy(
3089 WrappedIndex::zero(),
3090 WrappedIndex::from_arbitrary_number(free),
3091 tail_len,
3092 );
3093 }
3094
3095 // We just copied the tail right next to the head slice,
3096 // so all of the elements in the range are initialized
3097 let slice = &mut *self.buffer_range(free..self.capacity());
3098
3099 // because the deque wasn't contiguous, we know that `tail_len < self.len == slice.len()`,
3100 // so this will never panic.
3101 slice.rotate_left(tail_len);
3102
3103 // the used part of the buffer now is `free..self.capacity()`, so set
3104 // `head` to the beginning of that range.
3105 self.head = WrappedIndex::from_arbitrary_number(free);
3106 }
3107 } else {
3108 // head is shorter so:
3109 // 1. copy head backwards
3110 // 2. rotate used part of the buffer
3111 // 3. update head to point to the new beginning (which is the beginning of the buffer)
3112
3113 // ignore-tidy-undocumented-unsafe
3114 unsafe {
3115 // if there is no free space in the buffer, then the slices are already
3116 // right next to each other and we don't need to move any memory.
3117 if free != 0 {
3118 // copy the head slice to lie right behind the tail slice.
3119 self.copy(
3120 self.head,
3121 WrappedIndex::from_arbitrary_number(tail_len),
3122 head_len,
3123 );
3124 }
3125
3126 // because we copied the head slice so that both slices lie right
3127 // next to each other, all the elements in the range are initialized.
3128 let slice = &mut *self.buffer_range(0..self.len);
3129
3130 // because the deque wasn't contiguous, we know that `head_len < self.len == slice.len()`
3131 // so this will never panic.
3132 slice.rotate_right(head_len);
3133
3134 // the used part of the buffer now is `0..self.len`, so set
3135 // `head` to the beginning of that range.
3136 self.head = WrappedIndex::zero();
3137 }
3138 }
3139 }
3140
3141 // ignore-tidy-undocumented-unsafe
3142 unsafe { slice::from_raw_parts_mut(ptr.add(self.head.as_index()), self.len) }
3143 }
3144
3145 /// Rotates the double-ended queue `n` places to the left.
3146 ///
3147 /// Equivalently,
3148 /// - Rotates item `n` into the first position.
3149 /// - Pops the first `n` items and pushes them to the end.
3150 /// - Rotates `len() - n` places to the right.
3151 ///
3152 /// # Panics
3153 ///
3154 /// If `n` is greater than `len()`. Note that `n == len()`
3155 /// does _not_ panic and is a no-op rotation.
3156 ///
3157 /// # Complexity
3158 ///
3159 /// Takes `*O*(min(n, len() - n))` time and no extra space.
3160 ///
3161 /// # Examples
3162 ///
3163 /// ```
3164 /// use std::collections::VecDeque;
3165 ///
3166 /// let mut buf: VecDeque<_> = (0..10).collect();
3167 ///
3168 /// buf.rotate_left(3);
3169 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
3170 ///
3171 /// for i in 1..10 {
3172 /// assert_eq!(i * 3 % 10, buf[0]);
3173 /// buf.rotate_left(3);
3174 /// }
3175 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
3176 /// ```
3177 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
3178 pub fn rotate_left(&mut self, n: usize) {
3179 assert!(n <= self.len());
3180 let k = self.len - n;
3181 if n <= k {
3182 // SAFETY: Ensured by check.
3183 unsafe { self.rotate_left_inner(n) }
3184 } else {
3185 // SAFETY: Ensured by check.
3186 unsafe { self.rotate_right_inner(k) }
3187 }
3188 }
3189
3190 /// Rotates the double-ended queue `n` places to the right.
3191 ///
3192 /// Equivalently,
3193 /// - Rotates the first item into position `n`.
3194 /// - Pops the last `n` items and pushes them to the front.
3195 /// - Rotates `len() - n` places to the left.
3196 ///
3197 /// # Panics
3198 ///
3199 /// If `n` is greater than `len()`. Note that `n == len()`
3200 /// does _not_ panic and is a no-op rotation.
3201 ///
3202 /// # Complexity
3203 ///
3204 /// Takes `*O*(min(n, len() - n))` time and no extra space.
3205 ///
3206 /// # Examples
3207 ///
3208 /// ```
3209 /// use std::collections::VecDeque;
3210 ///
3211 /// let mut buf: VecDeque<_> = (0..10).collect();
3212 ///
3213 /// buf.rotate_right(3);
3214 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
3215 ///
3216 /// for i in 1..10 {
3217 /// assert_eq!(0, buf[i * 3 % 10]);
3218 /// buf.rotate_right(3);
3219 /// }
3220 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
3221 /// ```
3222 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
3223 pub fn rotate_right(&mut self, n: usize) {
3224 assert!(n <= self.len());
3225 let k = self.len - n;
3226 if n <= k {
3227 // SAFETY: Ensured by check.
3228 unsafe { self.rotate_right_inner(n) }
3229 } else {
3230 // SAFETY: Ensured by check.
3231 unsafe { self.rotate_left_inner(k) }
3232 }
3233 }
3234
3235 // SAFETY: the following two methods require that the rotation amount
3236 // be less than half the length of the deque.
3237 //
3238 // `wrap_copy` requires that `min(x, capacity() - x) + copy_len <= capacity()`,
3239 // but then `min` is never more than half the capacity, regardless of x,
3240 // so it's sound to call here because we're calling with something
3241 // less than half the length, which is never above half the capacity.
3242
3243 unsafe fn rotate_left_inner(&mut self, mid: usize) {
3244 debug_assert!(mid * 2 <= self.len());
3245 // SAFETY: Upheld by caller.
3246 unsafe {
3247 self.wrap_copy(self.head, self.to_wrapped_index(self.len), mid);
3248 }
3249 self.head = self.to_wrapped_index(mid);
3250 }
3251
3252 unsafe fn rotate_right_inner(&mut self, k: usize) {
3253 debug_assert!(k * 2 <= self.len());
3254 self.head = self.wrap_sub(self.head, k);
3255 // SAFETY: Upheld by caller.
3256 unsafe {
3257 self.wrap_copy(self.to_wrapped_index(self.len), self.head, k);
3258 }
3259 }
3260
3261 /// Binary searches this `VecDeque` for a given element.
3262 /// If the `VecDeque` is not sorted, the returned result is unspecified and
3263 /// meaningless.
3264 ///
3265 /// If the value is found then [`Result::Ok`] is returned, containing the
3266 /// index of the matching element. If there are multiple matches, then any
3267 /// one of the matches could be returned. If the value is not found then
3268 /// [`Result::Err`] is returned, containing the index where a matching
3269 /// element could be inserted while maintaining sorted order.
3270 ///
3271 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
3272 ///
3273 /// [`binary_search_by`]: VecDeque::binary_search_by
3274 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
3275 /// [`partition_point`]: VecDeque::partition_point
3276 ///
3277 /// # Examples
3278 ///
3279 /// Looks up a series of four elements. The first is found, with a
3280 /// uniquely determined position; the second and third are not
3281 /// found; the fourth could match any position in `[1, 4]`.
3282 ///
3283 /// ```
3284 /// use std::collections::VecDeque;
3285 ///
3286 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3287 ///
3288 /// assert_eq!(deque.binary_search(&13), Ok(9));
3289 /// assert_eq!(deque.binary_search(&4), Err(7));
3290 /// assert_eq!(deque.binary_search(&100), Err(13));
3291 /// let r = deque.binary_search(&1);
3292 /// assert!(matches!(r, Ok(1..=4)));
3293 /// ```
3294 ///
3295 /// If you want to insert an item to a sorted deque, while maintaining
3296 /// sort order, consider using [`partition_point`]:
3297 ///
3298 /// ```
3299 /// use std::collections::VecDeque;
3300 ///
3301 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3302 /// let num = 42;
3303 /// let idx = deque.partition_point(|&x| x <= num);
3304 /// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
3305 /// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` may allow `insert`
3306 /// // to shift less elements.
3307 /// deque.insert(idx, num);
3308 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
3309 /// ```
3310 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3311 #[inline]
3312 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
3313 where
3314 T: Ord,
3315 {
3316 self.binary_search_by(|e| e.cmp(x))
3317 }
3318
3319 /// Binary searches this `VecDeque` with a comparator function.
3320 ///
3321 /// The comparator function should return an order code that indicates
3322 /// whether its argument is `Less`, `Equal` or `Greater` the desired
3323 /// target.
3324 /// If the `VecDeque` is not sorted or if the comparator function does not
3325 /// implement an order consistent with the sort order of the underlying
3326 /// `VecDeque`, the returned result is unspecified and meaningless.
3327 ///
3328 /// If the value is found then [`Result::Ok`] is returned, containing the
3329 /// index of the matching element. If there are multiple matches, then any
3330 /// one of the matches could be returned. If the value is not found then
3331 /// [`Result::Err`] is returned, containing the index where a matching
3332 /// element could be inserted while maintaining sorted order.
3333 ///
3334 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
3335 ///
3336 /// [`binary_search`]: VecDeque::binary_search
3337 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
3338 /// [`partition_point`]: VecDeque::partition_point
3339 ///
3340 /// # Examples
3341 ///
3342 /// Looks up a series of four elements. The first is found, with a
3343 /// uniquely determined position; the second and third are not
3344 /// found; the fourth could match any position in `[1, 4]`.
3345 ///
3346 /// ```
3347 /// use std::collections::VecDeque;
3348 ///
3349 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3350 ///
3351 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
3352 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
3353 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
3354 /// let r = deque.binary_search_by(|x| x.cmp(&1));
3355 /// assert!(matches!(r, Ok(1..=4)));
3356 /// ```
3357 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3358 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
3359 where
3360 F: FnMut(&'a T) -> Ordering,
3361 {
3362 let (front, back) = self.as_slices();
3363 let cmp_back = back.first().map(&mut f);
3364
3365 if let Some(Ordering::Equal) = cmp_back {
3366 Ok(front.len())
3367 } else if let Some(Ordering::Less) = cmp_back {
3368 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
3369 } else {
3370 front.binary_search_by(f)
3371 }
3372 }
3373
3374 /// Binary searches this `VecDeque` with a key extraction function.
3375 ///
3376 /// Assumes that the deque is sorted by the key, for instance with
3377 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
3378 /// If the deque is not sorted by the key, the returned result is
3379 /// unspecified and meaningless.
3380 ///
3381 /// If the value is found then [`Result::Ok`] is returned, containing the
3382 /// index of the matching element. If there are multiple matches, then any
3383 /// one of the matches could be returned. If the value is not found then
3384 /// [`Result::Err`] is returned, containing the index where a matching
3385 /// element could be inserted while maintaining sorted order.
3386 ///
3387 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
3388 ///
3389 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
3390 /// [`binary_search`]: VecDeque::binary_search
3391 /// [`binary_search_by`]: VecDeque::binary_search_by
3392 /// [`partition_point`]: VecDeque::partition_point
3393 ///
3394 /// # Examples
3395 ///
3396 /// Looks up a series of four elements in a slice of pairs sorted by
3397 /// their second elements. The first is found, with a uniquely
3398 /// determined position; the second and third are not found; the
3399 /// fourth could match any position in `[1, 4]`.
3400 ///
3401 /// ```
3402 /// use std::collections::VecDeque;
3403 ///
3404 /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
3405 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
3406 /// (1, 21), (2, 34), (4, 55)].into();
3407 ///
3408 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
3409 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
3410 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
3411 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
3412 /// assert!(matches!(r, Ok(1..=4)));
3413 /// ```
3414 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3415 #[inline]
3416 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
3417 where
3418 F: FnMut(&'a T) -> B,
3419 B: Ord,
3420 {
3421 self.binary_search_by(|k| f(k).cmp(b))
3422 }
3423
3424 /// Returns the index of the partition point according to the given predicate
3425 /// (the index of the first element of the second partition).
3426 ///
3427 /// The deque is assumed to be partitioned according to the given predicate.
3428 /// This means that all elements for which the predicate returns true are at the start of the deque
3429 /// and all elements for which the predicate returns false are at the end.
3430 /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
3431 /// (all odd numbers are at the start, all even at the end).
3432 ///
3433 /// If the deque is not partitioned, the returned result is unspecified and meaningless,
3434 /// as this method performs a kind of binary search.
3435 ///
3436 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
3437 ///
3438 /// [`binary_search`]: VecDeque::binary_search
3439 /// [`binary_search_by`]: VecDeque::binary_search_by
3440 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
3441 ///
3442 /// # Examples
3443 ///
3444 /// ```
3445 /// use std::collections::VecDeque;
3446 ///
3447 /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
3448 /// let i = deque.partition_point(|&x| x < 5);
3449 ///
3450 /// assert_eq!(i, 4);
3451 /// assert!(deque.iter().take(i).all(|&x| x < 5));
3452 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
3453 /// ```
3454 ///
3455 /// If you want to insert an item to a sorted deque, while maintaining
3456 /// sort order:
3457 ///
3458 /// ```
3459 /// use std::collections::VecDeque;
3460 ///
3461 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3462 /// let num = 42;
3463 /// let idx = deque.partition_point(|&x| x < num);
3464 /// deque.insert(idx, num);
3465 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
3466 /// ```
3467 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3468 pub fn partition_point<P>(&self, mut pred: P) -> usize
3469 where
3470 P: FnMut(&T) -> bool,
3471 {
3472 let (front, back) = self.as_slices();
3473
3474 if let Some(true) = back.first().map(&mut pred) {
3475 back.partition_point(pred) + front.len()
3476 } else {
3477 front.partition_point(pred)
3478 }
3479 }
3480}
3481
3482impl<T: Clone, A: Allocator> VecDeque<T, A> {
3483 /// Modifies the deque in-place so that `len()` is equal to new_len,
3484 /// either by removing excess elements from the back or by appending clones of `value`
3485 /// to the back.
3486 ///
3487 /// # Examples
3488 ///
3489 /// ```
3490 /// use std::collections::VecDeque;
3491 ///
3492 /// let mut buf = VecDeque::new();
3493 /// buf.push_back(5);
3494 /// buf.push_back(10);
3495 /// buf.push_back(15);
3496 /// assert_eq!(buf, [5, 10, 15]);
3497 ///
3498 /// buf.resize(2, 0);
3499 /// assert_eq!(buf, [5, 10]);
3500 ///
3501 /// buf.resize(5, 20);
3502 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
3503 /// ```
3504 #[stable(feature = "deque_extras", since = "1.16.0")]
3505 pub fn resize(&mut self, new_len: usize, value: T) {
3506 if new_len > self.len() {
3507 let extra = new_len - self.len();
3508 self.extend(repeat_n(value, extra))
3509 } else {
3510 self.truncate(new_len);
3511 }
3512 }
3513
3514 /// Clones the elements at the range `src` and appends them to the end.
3515 ///
3516 /// # Panics
3517 ///
3518 /// Panics if the starting index is greater than the end index
3519 /// or if either index is greater than the length of the vector.
3520 ///
3521 /// # Examples
3522 ///
3523 /// ```
3524 /// #![feature(deque_extend_front)]
3525 /// use std::collections::VecDeque;
3526 ///
3527 /// let mut characters = VecDeque::from(['a', 'b', 'c', 'd', 'e']);
3528 /// characters.extend_from_within(2..);
3529 /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
3530 ///
3531 /// let mut numbers = VecDeque::from([0, 1, 2, 3, 4]);
3532 /// numbers.extend_from_within(..2);
3533 /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
3534 ///
3535 /// let mut strings = VecDeque::from([String::from("hello"), String::from("world"), String::from("!")]);
3536 /// strings.extend_from_within(1..=2);
3537 /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
3538 /// ```
3539 #[cfg(not(no_global_oom_handling))]
3540 #[unstable(feature = "deque_extend_front", issue = "146975")]
3541 pub fn extend_from_within<R>(&mut self, src: R)
3542 where
3543 R: RangeBounds<usize>,
3544 {
3545 let range = slice::range(src, ..self.len());
3546 self.reserve(range.len());
3547
3548 // SAFETY:
3549 // - `slice::range` guarantees that the given range is valid for indexing self
3550 // - at least `range.len()` additional space is available
3551 unsafe {
3552 self.spec_extend_from_within(range);
3553 }
3554 }
3555
3556 /// Clones the elements at the range `src` and prepends them to the front.
3557 ///
3558 /// # Panics
3559 ///
3560 /// Panics if the starting index is greater than the end index
3561 /// or if either index is greater than the length of the vector.
3562 ///
3563 /// # Examples
3564 ///
3565 /// ```
3566 /// #![feature(deque_extend_front)]
3567 /// use std::collections::VecDeque;
3568 ///
3569 /// let mut characters = VecDeque::from(['a', 'b', 'c', 'd', 'e']);
3570 /// characters.prepend_from_within(2..);
3571 /// assert_eq!(characters, ['c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']);
3572 ///
3573 /// let mut numbers = VecDeque::from([0, 1, 2, 3, 4]);
3574 /// numbers.prepend_from_within(..2);
3575 /// assert_eq!(numbers, [0, 1, 0, 1, 2, 3, 4]);
3576 ///
3577 /// let mut strings = VecDeque::from([String::from("hello"), String::from("world"), String::from("!")]);
3578 /// strings.prepend_from_within(1..=2);
3579 /// assert_eq!(strings, ["world", "!", "hello", "world", "!"]);
3580 /// ```
3581 #[cfg(not(no_global_oom_handling))]
3582 #[unstable(feature = "deque_extend_front", issue = "146975")]
3583 pub fn prepend_from_within<R>(&mut self, src: R)
3584 where
3585 R: RangeBounds<usize>,
3586 {
3587 let range = slice::range(src, ..self.len());
3588 self.reserve(range.len());
3589
3590 // SAFETY:
3591 // - `slice::range` guarantees that the given range is valid for indexing self
3592 // - at least `range.len()` additional space is available
3593 unsafe {
3594 self.spec_prepend_from_within(range);
3595 }
3596 }
3597}
3598
3599/// Associated functions have the following preconditions:
3600///
3601/// - `src` needs to be a valid range: `src.start <= src.end <= self.len()`.
3602/// - The buffer must have enough spare capacity: `self.capacity() - self.len() >= src.len()`.
3603#[cfg(not(no_global_oom_handling))]
3604trait SpecExtendFromWithin {
3605 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
3606
3607 unsafe fn spec_prepend_from_within(&mut self, src: Range<usize>);
3608}
3609
3610#[cfg(not(no_global_oom_handling))]
3611impl<T: Clone, A: Allocator> SpecExtendFromWithin for VecDeque<T, A> {
3612 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3613 let dst = self.len();
3614 let count = src.end - src.start;
3615 let src = src.start;
3616
3617 // SAFETY:
3618 // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3619 // - Ranges are in bounds: guaranteed by the caller.
3620 let ranges = unsafe { self.nonoverlapping_ranges(src, dst, count, self.head) };
3621
3622 // `len` is updated after every clone to prevent leaking and
3623 // leave the deque in the right state when a clone implementation panics
3624
3625 for (src, dst, count) in ranges {
3626 for offset in 0..count {
3627 // SAFETY: The allocations of `dst` and `src` go up to `count` elems,
3628 // and `nonoverlapping_ranges` ensures `dst` and `src` are valid
3629 // for writes and reads respectively.
3630 unsafe { dst.add(offset).write((*src.add(offset)).clone()) };
3631 self.len += 1;
3632 }
3633 }
3634 }
3635
3636 default unsafe fn spec_prepend_from_within(&mut self, src: Range<usize>) {
3637 let dst = 0;
3638 let count = src.end - src.start;
3639 let src = src.start + count;
3640
3641 let new_head = self.wrap_sub(self.head, count);
3642 let cap = self.capacity();
3643
3644 // SAFETY:
3645 // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3646 // - Ranges are in bounds: guaranteed by the caller.
3647 let ranges = unsafe { self.nonoverlapping_ranges(src, dst, count, new_head) };
3648
3649 // Cloning is done in reverse because we prepend to the front of the deque,
3650 // we can't get holes in the *logical* buffer.
3651 // `head` and `len` are updated after every clone to prevent leaking and
3652 // leave the deque in the right state when a clone implementation panics
3653
3654 // Clone the first range
3655 let (src, dst, count) = ranges[1];
3656 for offset in (0..count).rev() {
3657 // ignore-tidy-undocumented-unsafe
3658 unsafe { dst.add(offset).write((*src.add(offset)).clone()) };
3659 // ignore-tidy-undocumented-unsafe
3660 self.head = unsafe { self.head.sub(1) };
3661 self.len += 1;
3662 }
3663
3664 // Clone the second range
3665 let (src, dst, count) = ranges[0];
3666 let mut iter = (0..count).rev();
3667 if let Some(offset) = iter.next() {
3668 // ignore-tidy-undocumented-unsafe
3669 unsafe { dst.add(offset).write((*src.add(offset)).clone()) };
3670 // After the first clone of the second range, wrap `head` around
3671 if self.head.is_zero() {
3672 // SAFETY: the wrapped index may be temporarily equal to the capacity even if it
3673 // is not zero, because we subtract it one line below.
3674 // FIXME: should `from_arbitrary_number` be unsafe? its docs imply so...
3675 self.head = WrappedIndex::from_arbitrary_number(cap);
3676 }
3677 // ignore-tidy-undocumented-unsafe
3678 self.head = unsafe { self.head.sub(1) };
3679 self.len += 1;
3680
3681 // Continue like normal
3682 for offset in iter {
3683 // ignore-tidy-undocumented-unsafe
3684 unsafe { dst.add(offset).write((*src.add(offset)).clone()) };
3685 // ignore-tidy-undocumented-unsafe
3686 self.head = unsafe { self.head.sub(1) };
3687 self.len += 1;
3688 }
3689 }
3690 }
3691}
3692
3693#[cfg(not(no_global_oom_handling))]
3694impl<T: TrivialClone, A: Allocator> SpecExtendFromWithin for VecDeque<T, A> {
3695 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3696 let dst = self.len();
3697 let count = src.end - src.start;
3698 let src = src.start;
3699
3700 // SAFETY:
3701 // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3702 // - Ranges are in bounds: guaranteed by the caller.
3703 let ranges = unsafe { self.nonoverlapping_ranges(src, dst, count, self.head) };
3704 for (src, dst, count) in ranges {
3705 // SAFETY: Ditto.
3706 unsafe { ptr::copy_nonoverlapping(src, dst, count) };
3707 }
3708
3709 // SAFETY:
3710 // - The elements were just initialized by `copy_nonoverlapping`
3711 self.len += count;
3712 }
3713
3714 unsafe fn spec_prepend_from_within(&mut self, src: Range<usize>) {
3715 let dst = 0;
3716 let count = src.end - src.start;
3717 let src = src.start + count;
3718
3719 let new_head = self.wrap_sub(self.head, count);
3720
3721 // SAFETY:
3722 // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3723 // - Ranges are in bounds: guaranteed by the caller.
3724 let ranges = unsafe { self.nonoverlapping_ranges(src, dst, count, new_head) };
3725 for (src, dst, count) in ranges {
3726 // SAFETY: Ditto.
3727 unsafe { ptr::copy_nonoverlapping(src, dst, count) };
3728 }
3729
3730 // SAFETY:
3731 // - The elements were just initialized by `copy_nonoverlapping`
3732 self.head = new_head;
3733 self.len += count;
3734 }
3735}
3736
3737use index::{WrappedIndex, wrap_index};
3738
3739// The code is separated into a module to make it harder to construct a BufferIndex without
3740// going through wrapping.
3741mod index {
3742 use core::cmp::Ordering;
3743
3744 /// Returns the index in the underlying buffer for a given logical element index.
3745 #[inline]
3746 pub(super) fn wrap_index(logical_index: usize, capacity: usize) -> WrappedIndex {
3747 debug_assert!(
3748 (logical_index == 0 && capacity == 0)
3749 || logical_index < capacity
3750 || (logical_index - capacity) < capacity
3751 );
3752 if logical_index >= capacity {
3753 WrappedIndex(logical_index - capacity)
3754 } else {
3755 WrappedIndex(logical_index)
3756 }
3757 }
3758
3759 /// Represents an index that can be safely used to index the VecDeque buffer.
3760 /// It exists as a separate type to avoid passing logical (unwrapped) indices to various
3761 /// VecDeque functions by accident.
3762 ///
3763 /// The invariant of this index is that it is always < VecDeque capacity, unless the VecDeque
3764 /// is empty (in that case the index can be 0 when the capacity is 0).
3765 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
3766 #[repr(transparent)]
3767 pub(super) struct WrappedIndex(usize);
3768
3769 impl WrappedIndex {
3770 /// The newly constructed index has to be in-bounds for the VecDeque
3771 /// that uses the index.
3772 #[inline(always)]
3773 pub(super) fn from_arbitrary_number(index: usize) -> Self {
3774 Self(index)
3775 }
3776
3777 /// Safety invariant: the newly constructed index must still be in-bounds for the VecDeque
3778 #[inline(always)]
3779 pub(super) unsafe fn add(self, offset: usize) -> Self {
3780 Self(self.0 + offset)
3781 }
3782
3783 /// Safety invariant: the newly constructed index must still be in-bounds for the VecDeque
3784 #[inline(always)]
3785 pub(super) unsafe fn sub(self, offset: usize) -> Self {
3786 debug_assert!(self.0 >= offset);
3787 Self(self.0 - offset)
3788 }
3789
3790 #[inline(always)]
3791 pub(super) const fn zero() -> Self {
3792 Self(0)
3793 }
3794
3795 #[inline(always)]
3796 pub(super) fn abs_diff(self, other: Self) -> usize {
3797 self.0.abs_diff(other.0)
3798 }
3799
3800 #[inline(always)]
3801 pub(super) fn as_index(self) -> usize {
3802 self.0
3803 }
3804
3805 #[inline(always)]
3806 pub(super) fn is_zero(self) -> bool {
3807 self.0 == 0
3808 }
3809 }
3810
3811 impl core::ops::Add<usize> for WrappedIndex {
3812 // The output might not be wrapped anymore
3813 type Output = usize;
3814
3815 #[inline(always)]
3816 fn add(self, rhs: usize) -> Self::Output {
3817 self.0 + rhs
3818 }
3819 }
3820
3821 impl core::fmt::Display for WrappedIndex {
3822 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3823 self.0.fmt(f)
3824 }
3825 }
3826
3827 impl core::cmp::PartialEq<usize> for WrappedIndex {
3828 #[inline(always)]
3829 fn eq(&self, other: &usize) -> bool {
3830 self.0.eq(other)
3831 }
3832 }
3833
3834 impl core::cmp::PartialOrd<usize> for WrappedIndex {
3835 #[inline(always)]
3836 fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
3837 self.0.partial_cmp(other)
3838 }
3839 }
3840}
3841
3842#[stable(feature = "rust1", since = "1.0.0")]
3843impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
3844 fn eq(&self, other: &Self) -> bool {
3845 if self.len != other.len() {
3846 return false;
3847 }
3848 let (sa, sb) = self.as_slices();
3849 let (oa, ob) = other.as_slices();
3850 if sa.len() == oa.len() {
3851 sa == oa && sb == ob
3852 } else if sa.len() < oa.len() {
3853 // Always divisible in three sections, for example:
3854 // self: [a b c|d e f]
3855 // other: [0 1 2 3|4 5]
3856 // front = 3, mid = 1,
3857 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
3858 let front = sa.len();
3859 let mid = oa.len() - front;
3860
3861 let (oa_front, oa_mid) = oa.split_at(front);
3862 let (sb_mid, sb_back) = sb.split_at(mid);
3863 debug_assert_eq!(sa.len(), oa_front.len());
3864 debug_assert_eq!(sb_mid.len(), oa_mid.len());
3865 debug_assert_eq!(sb_back.len(), ob.len());
3866 sa == oa_front && sb_mid == oa_mid && sb_back == ob
3867 } else {
3868 let front = oa.len();
3869 let mid = sa.len() - front;
3870
3871 let (sa_front, sa_mid) = sa.split_at(front);
3872 let (ob_mid, ob_back) = ob.split_at(mid);
3873 debug_assert_eq!(sa_front.len(), oa.len());
3874 debug_assert_eq!(sa_mid.len(), ob_mid.len());
3875 debug_assert_eq!(sb.len(), ob_back.len());
3876 sa_front == oa && sa_mid == ob_mid && sb == ob_back
3877 }
3878 }
3879}
3880
3881#[stable(feature = "rust1", since = "1.0.0")]
3882impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
3883
3884__impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
3885__impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
3886__impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
3887__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
3888__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
3889__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
3890
3891#[stable(feature = "rust1", since = "1.0.0")]
3892impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
3893 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3894 self.iter().partial_cmp(other.iter())
3895 }
3896}
3897
3898#[stable(feature = "rust1", since = "1.0.0")]
3899impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
3900 #[inline]
3901 fn cmp(&self, other: &Self) -> Ordering {
3902 self.iter().cmp(other.iter())
3903 }
3904}
3905
3906#[stable(feature = "rust1", since = "1.0.0")]
3907impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
3908 fn hash<H: Hasher>(&self, state: &mut H) {
3909 state.write_length_prefix(self.len);
3910 // It's not possible to use Hash::hash_slice on slices
3911 // returned by as_slices method as their length can vary
3912 // in otherwise identical deques.
3913 //
3914 // Hasher only guarantees equivalence for the exact same
3915 // set of calls to its methods.
3916 self.iter().for_each(|elem| elem.hash(state));
3917 }
3918}
3919
3920#[stable(feature = "rust1", since = "1.0.0")]
3921impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
3922 type Output = T;
3923
3924 #[inline]
3925 fn index(&self, index: usize) -> &T {
3926 self.get(index).expect("out of bounds access")
3927 }
3928}
3929
3930#[stable(feature = "rust1", since = "1.0.0")]
3931impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
3932 #[inline]
3933 fn index_mut(&mut self, index: usize) -> &mut T {
3934 self.get_mut(index).expect("out of bounds access")
3935 }
3936}
3937
3938#[stable(feature = "rust1", since = "1.0.0")]
3939impl<T> FromIterator<T> for VecDeque<T> {
3940 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
3941 SpecFromIter::spec_from_iter(iter.into_iter())
3942 }
3943}
3944
3945#[stable(feature = "rust1", since = "1.0.0")]
3946impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
3947 type Item = T;
3948 type IntoIter = IntoIter<T, A>;
3949
3950 /// Consumes the deque into a front-to-back iterator yielding elements by
3951 /// value.
3952 fn into_iter(self) -> IntoIter<T, A> {
3953 IntoIter::new(self)
3954 }
3955}
3956
3957#[stable(feature = "rust1", since = "1.0.0")]
3958impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
3959 type Item = &'a T;
3960 type IntoIter = Iter<'a, T>;
3961
3962 fn into_iter(self) -> Iter<'a, T> {
3963 self.iter()
3964 }
3965}
3966
3967#[stable(feature = "rust1", since = "1.0.0")]
3968impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
3969 type Item = &'a mut T;
3970 type IntoIter = IterMut<'a, T>;
3971
3972 fn into_iter(self) -> IterMut<'a, T> {
3973 self.iter_mut()
3974 }
3975}
3976
3977#[stable(feature = "rust1", since = "1.0.0")]
3978impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
3979 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
3980 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter());
3981 }
3982
3983 #[inline]
3984 fn extend_one(&mut self, elem: T) {
3985 self.push_back(elem);
3986 }
3987
3988 #[inline]
3989 fn extend_reserve(&mut self, additional: usize) {
3990 self.reserve(additional);
3991 }
3992
3993 #[inline]
3994 unsafe fn extend_one_unchecked(&mut self, item: T) {
3995 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3996 unsafe {
3997 self.push_unchecked(item);
3998 }
3999 }
4000}
4001
4002#[stable(feature = "extend_ref", since = "1.2.0")]
4003impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
4004 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
4005 self.spec_extend(iter.into_iter());
4006 }
4007
4008 #[inline]
4009 fn extend_one(&mut self, &elem: &'a T) {
4010 self.push_back(elem);
4011 }
4012
4013 #[inline]
4014 fn extend_reserve(&mut self, additional: usize) {
4015 self.reserve(additional);
4016 }
4017
4018 #[inline]
4019 unsafe fn extend_one_unchecked(&mut self, &item: &'a T) {
4020 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
4021 unsafe {
4022 self.push_unchecked(item);
4023 }
4024 }
4025}
4026
4027#[stable(feature = "rust1", since = "1.0.0")]
4028impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
4029 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4030 f.debug_list().entries(self.iter()).finish()
4031 }
4032}
4033
4034#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
4035impl<T, A: AllocatorNightly> From<Vec<T, A>> for VecDeque<T, A> {
4036 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
4037 ///
4038 /// [`Vec<T>`]: crate::vec::Vec
4039 /// [`VecDeque<T>`]: crate::collections::VecDeque
4040 ///
4041 /// This conversion is guaranteed to run in *O*(1) time
4042 /// and to not re-allocate the `Vec`'s buffer or allocate
4043 /// any additional memory.
4044 #[inline]
4045 fn from(other: Vec<T, A>) -> Self {
4046 let (ptr, len, cap, alloc) = other.into_raw_parts_with_allocator();
4047 Self {
4048 head: WrappedIndex::zero(),
4049 len,
4050 // ignore-tidy-undocumented-unsafe
4051 buf: unsafe { RawVec::from_raw_parts_in(ptr, cap, alloc) },
4052 }
4053 }
4054}
4055
4056#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
4057impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
4058 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
4059 ///
4060 /// [`Vec<T>`]: crate::vec::Vec
4061 /// [`VecDeque<T>`]: crate::collections::VecDeque
4062 ///
4063 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
4064 /// the circular buffer doesn't happen to be at the beginning of the allocation.
4065 ///
4066 /// # Examples
4067 ///
4068 /// ```
4069 /// use std::collections::VecDeque;
4070 ///
4071 /// // This one is *O*(1).
4072 /// let deque: VecDeque<_> = (1..5).collect();
4073 /// let ptr = deque.as_slices().0.as_ptr();
4074 /// let vec = Vec::from(deque);
4075 /// assert_eq!(vec, [1, 2, 3, 4]);
4076 /// assert_eq!(vec.as_ptr(), ptr);
4077 ///
4078 /// // This one needs data rearranging.
4079 /// let mut deque: VecDeque<_> = (1..5).collect();
4080 /// deque.push_front(9);
4081 /// deque.push_front(8);
4082 /// let ptr = deque.as_slices().1.as_ptr();
4083 /// let vec = Vec::from(deque);
4084 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
4085 /// assert_eq!(vec.as_ptr(), ptr);
4086 /// ```
4087 fn from(mut other: VecDeque<T, A>) -> Self {
4088 other.make_contiguous();
4089
4090 // ignore-tidy-undocumented-unsafe
4091 unsafe {
4092 let other = ManuallyDrop::new(other);
4093 let buf = other.buf.ptr();
4094 let len = other.len();
4095 let cap = other.capacity();
4096 let alloc = ptr::read(other.allocator());
4097
4098 if !other.head.is_zero() {
4099 ptr::copy(buf.add(other.head.as_index()), buf, len);
4100 }
4101 Vec::from_raw_parts_in(buf, len, cap, alloc)
4102 }
4103 }
4104}
4105
4106#[stable(feature = "std_collections_from_array", since = "1.56.0")]
4107impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
4108 /// Converts a `[T; N]` into a `VecDeque<T>`.
4109 ///
4110 /// ```
4111 /// use std::collections::VecDeque;
4112 ///
4113 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
4114 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
4115 /// assert_eq!(deq1, deq2);
4116 /// ```
4117 fn from(arr: [T; N]) -> Self {
4118 let mut deq = VecDeque::with_capacity(N);
4119 let arr = ManuallyDrop::new(arr);
4120 if !<T>::IS_ZST {
4121 // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
4122 unsafe {
4123 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);
4124 }
4125 }
4126 deq.head = WrappedIndex::zero();
4127 deq.len = N;
4128 deq
4129 }
4130}