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