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