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