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()`.
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 #[stable(feature = "deque_extras", since = "1.16.0")]
1434 pub fn truncate(&mut self, len: usize) {
1435 /// Runs the destructor for all items in the slice when it gets dropped (normally or
1436 /// during unwinding).
1437 struct Dropper<'a, T>(&'a mut [T]);
1438
1439 impl<'a, T> Drop for Dropper<'a, T> {
1440 fn drop(&mut self) {
1441 unsafe {
1442 ptr::drop_in_place(self.0);
1443 }
1444 }
1445 }
1446
1447 // Safe because:
1448 //
1449 // * Any slice passed to `drop_in_place` is valid; the second case has
1450 // `len <= front.len()` and returning on `len > self.len()` ensures
1451 // `begin <= back.len()` in the first case
1452 // * The head of the VecDeque is moved before calling `drop_in_place`,
1453 // so no value is dropped twice if `drop_in_place` panics
1454 unsafe {
1455 if len >= self.len {
1456 return;
1457 }
1458
1459 let (front, back) = self.as_mut_slices();
1460 if len > front.len() {
1461 let begin = len - front.len();
1462 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
1463 self.len = len;
1464 ptr::drop_in_place(drop_back);
1465 } else {
1466 let drop_back = back as *mut _;
1467 let drop_front = front.get_unchecked_mut(len..) as *mut _;
1468 self.len = len;
1469
1470 // Make sure the second half is dropped even when a destructor
1471 // in the first one panics.
1472 let _back_dropper = Dropper(&mut *drop_back);
1473 ptr::drop_in_place(drop_front);
1474 }
1475 }
1476 }
1477
1478 /// Shortens the deque, keeping the last `len` elements and dropping
1479 /// the rest.
1480 ///
1481 /// If `len` is greater or equal to the deque's current length, this has
1482 /// no effect.
1483 ///
1484 /// # Examples
1485 ///
1486 /// ```
1487 /// # #![feature(vec_deque_truncate_front)]
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.truncate_front(1);
1497 /// assert_eq!(buf.as_slices(), (&[5][..], &[][..]));
1498 /// ```
1499 #[unstable(feature = "vec_deque_truncate_front", issue = "140667")]
1500 pub fn truncate_front(&mut self, len: usize) {
1501 /// Runs the destructor for all items in the slice when it gets dropped (normally or
1502 /// during unwinding).
1503 struct Dropper<'a, T>(&'a mut [T]);
1504
1505 impl<'a, T> Drop for Dropper<'a, T> {
1506 fn drop(&mut self) {
1507 unsafe {
1508 ptr::drop_in_place(self.0);
1509 }
1510 }
1511 }
1512
1513 unsafe {
1514 if len >= self.len {
1515 // No action is taken
1516 return;
1517 }
1518
1519 let (front, back) = self.as_mut_slices();
1520 if len > back.len() {
1521 // The 'back' slice remains unchanged.
1522 // front.len() + back.len() == self.len, so 'end' is non-negative
1523 // and end < front.len()
1524 let end = front.len() - (len - back.len());
1525 let drop_front = front.get_unchecked_mut(..end) as *mut _;
1526 self.head = self.head.add(end);
1527 self.len = len;
1528 ptr::drop_in_place(drop_front);
1529 } else {
1530 let drop_front = front as *mut _;
1531 // 'end' is non-negative by the condition above
1532 let end = back.len() - len;
1533 let drop_back = back.get_unchecked_mut(..end) as *mut _;
1534 self.head = self.to_wrapped_index(self.len - len);
1535 self.len = len;
1536
1537 // Make sure the second half is dropped even when a destructor
1538 // in the first one panics.
1539 let _back_dropper = Dropper(&mut *drop_back);
1540 ptr::drop_in_place(drop_front);
1541 }
1542 }
1543 }
1544
1545 /// Returns a reference to the underlying allocator.
1546 #[unstable(feature = "allocator_api", issue = "32838")]
1547 #[inline]
1548 pub fn allocator(&self) -> &A {
1549 self.buf.allocator()
1550 }
1551
1552 /// Returns a front-to-back iterator.
1553 ///
1554 /// # Examples
1555 ///
1556 /// ```
1557 /// use std::collections::VecDeque;
1558 ///
1559 /// let mut buf = VecDeque::new();
1560 /// buf.push_back(5);
1561 /// buf.push_back(3);
1562 /// buf.push_back(4);
1563 /// let b: &[_] = &[&5, &3, &4];
1564 /// let c: Vec<&i32> = buf.iter().collect();
1565 /// assert_eq!(&c[..], b);
1566 /// ```
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 #[cfg_attr(not(test), rustc_diagnostic_item = "vecdeque_iter")]
1569 pub fn iter(&self) -> Iter<'_, T> {
1570 let (a, b) = self.as_slices();
1571 Iter::new(a.iter(), b.iter())
1572 }
1573
1574 /// Returns a front-to-back iterator that returns mutable references.
1575 ///
1576 /// # Examples
1577 ///
1578 /// ```
1579 /// use std::collections::VecDeque;
1580 ///
1581 /// let mut buf = VecDeque::new();
1582 /// buf.push_back(5);
1583 /// buf.push_back(3);
1584 /// buf.push_back(4);
1585 /// for num in buf.iter_mut() {
1586 /// *num = *num - 2;
1587 /// }
1588 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1589 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1590 /// ```
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1593 let (a, b) = self.as_mut_slices();
1594 IterMut::new(a.iter_mut(), b.iter_mut())
1595 }
1596
1597 /// Returns a pair of slices which contain, in order, the contents of the
1598 /// deque.
1599 ///
1600 /// If [`make_contiguous`] was previously called, all elements of the
1601 /// deque will be in the first slice and the second slice will be empty.
1602 /// Otherwise, the exact split point depends on implementation details
1603 /// and is not guaranteed.
1604 ///
1605 /// [`make_contiguous`]: VecDeque::make_contiguous
1606 ///
1607 /// # Examples
1608 ///
1609 /// ```
1610 /// use std::collections::VecDeque;
1611 ///
1612 /// let mut deque = VecDeque::new();
1613 ///
1614 /// deque.push_back(0);
1615 /// deque.push_back(1);
1616 /// deque.push_back(2);
1617 ///
1618 /// let expected = [0, 1, 2];
1619 /// let (front, back) = deque.as_slices();
1620 /// assert_eq!(&expected[..front.len()], front);
1621 /// assert_eq!(&expected[front.len()..], back);
1622 ///
1623 /// deque.push_front(10);
1624 /// deque.push_front(9);
1625 ///
1626 /// let expected = [9, 10, 0, 1, 2];
1627 /// let (front, back) = deque.as_slices();
1628 /// assert_eq!(&expected[..front.len()], front);
1629 /// assert_eq!(&expected[front.len()..], back);
1630 /// ```
1631 #[inline]
1632 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1633 pub fn as_slices(&self) -> (&[T], &[T]) {
1634 let (a_range, b_range) = self.slice_ranges(.., self.len);
1635 // SAFETY: `slice_ranges` always returns valid ranges into
1636 // the physical buffer.
1637 unsafe { (&*self.buffer_range(a_range), &*self.buffer_range(b_range)) }
1638 }
1639
1640 /// Returns a pair of slices which contain, in order, the contents of the
1641 /// deque.
1642 ///
1643 /// If [`make_contiguous`] was previously called, all elements of the
1644 /// deque will be in the first slice and the second slice will be empty.
1645 /// Otherwise, the exact split point depends on implementation details
1646 /// and is not guaranteed.
1647 ///
1648 /// [`make_contiguous`]: VecDeque::make_contiguous
1649 ///
1650 /// # Examples
1651 ///
1652 /// ```
1653 /// use std::collections::VecDeque;
1654 ///
1655 /// let mut deque = VecDeque::new();
1656 ///
1657 /// deque.push_back(0);
1658 /// deque.push_back(1);
1659 ///
1660 /// deque.push_front(10);
1661 /// deque.push_front(9);
1662 ///
1663 /// // Since the split point is not guaranteed, we may need to update
1664 /// // either slice.
1665 /// let mut update_nth = |index: usize, val: u32| {
1666 /// let (front, back) = deque.as_mut_slices();
1667 /// if index > front.len() - 1 {
1668 /// back[index - front.len()] = val;
1669 /// } else {
1670 /// front[index] = val;
1671 /// }
1672 /// };
1673 ///
1674 /// update_nth(0, 42);
1675 /// update_nth(2, 24);
1676 ///
1677 /// let v: Vec<_> = deque.into();
1678 /// assert_eq!(v, [42, 10, 24, 1]);
1679 /// ```
1680 #[inline]
1681 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1682 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1683 let (a_range, b_range) = self.slice_ranges(.., self.len);
1684 // SAFETY: `slice_ranges` always returns valid ranges into
1685 // the physical buffer.
1686 unsafe { (&mut *self.buffer_range(a_range), &mut *self.buffer_range(b_range)) }
1687 }
1688
1689 /// Returns the number of elements in the deque.
1690 ///
1691 /// # Examples
1692 ///
1693 /// ```
1694 /// use std::collections::VecDeque;
1695 ///
1696 /// let mut deque = VecDeque::new();
1697 /// assert_eq!(deque.len(), 0);
1698 /// deque.push_back(1);
1699 /// assert_eq!(deque.len(), 1);
1700 /// ```
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 #[rustc_confusables("length", "size")]
1703 pub fn len(&self) -> usize {
1704 self.len
1705 }
1706
1707 /// Returns `true` if the deque is empty.
1708 ///
1709 /// # Examples
1710 ///
1711 /// ```
1712 /// use std::collections::VecDeque;
1713 ///
1714 /// let mut deque = VecDeque::new();
1715 /// assert!(deque.is_empty());
1716 /// deque.push_front(1);
1717 /// assert!(!deque.is_empty());
1718 /// ```
1719 #[stable(feature = "rust1", since = "1.0.0")]
1720 pub fn is_empty(&self) -> bool {
1721 self.len == 0
1722 }
1723
1724 /// Given a range into the logical buffer of the deque, this function
1725 /// return two ranges into the physical buffer that correspond to
1726 /// the given range. The `len` parameter should usually just be `self.len`;
1727 /// the reason it's passed explicitly is that if the deque is wrapped in
1728 /// a `Drain`, then `self.len` is not actually the length of the deque.
1729 ///
1730 /// # Safety
1731 ///
1732 /// This function is always safe to call. For the resulting ranges to be valid
1733 /// ranges into the physical buffer, the caller must ensure that the result of
1734 /// calling `slice::range(range, ..len)` represents a valid range into the
1735 /// logical buffer, and that all elements in that range are initialized.
1736 fn slice_ranges<R>(&self, range: R, len: usize) -> (Range<usize>, Range<usize>)
1737 where
1738 R: RangeBounds<usize>,
1739 {
1740 let Range { start, end } = slice::range(range, ..len);
1741 let len = end - start;
1742
1743 if len == 0 {
1744 (0..0, 0..0)
1745 } else {
1746 // `slice::range` guarantees that `start <= end <= len`.
1747 // because `len != 0`, we know that `start < end`, so `start < len`
1748 // and the indexing is valid.
1749 let wrapped_start = self.to_wrapped_index(start);
1750
1751 // this subtraction can never overflow because `wrapped_start` is
1752 // at most `self.capacity()` (and if `self.capacity != 0`, then `wrapped_start` is strictly less
1753 // than `self.capacity`).
1754 let head_len = self.capacity() - wrapped_start.as_index();
1755
1756 if head_len >= len {
1757 // we know that `len + wrapped_start <= self.capacity <= usize::MAX`, so this addition can't overflow
1758 (wrapped_start.as_index()..wrapped_start + len, 0..0)
1759 } else {
1760 // can't overflow because of the if condition
1761 let tail_len = len - head_len;
1762 (wrapped_start.as_index()..self.capacity(), 0..tail_len)
1763 }
1764 }
1765 }
1766
1767 /// Creates an iterator that covers the specified range in the deque.
1768 ///
1769 /// # Panics
1770 ///
1771 /// Panics if the range has `start_bound > end_bound`, or, if the range is
1772 /// bounded on either end and past the length of the deque.
1773 ///
1774 /// # Examples
1775 ///
1776 /// ```
1777 /// use std::collections::VecDeque;
1778 ///
1779 /// let deque: VecDeque<_> = [1, 2, 3].into();
1780 /// let range = deque.range(2..).copied().collect::<VecDeque<_>>();
1781 /// assert_eq!(range, [3]);
1782 ///
1783 /// // A full range covers all contents
1784 /// let all = deque.range(..);
1785 /// assert_eq!(all.len(), 3);
1786 /// ```
1787 #[inline]
1788 #[stable(feature = "deque_range", since = "1.51.0")]
1789 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1790 where
1791 R: RangeBounds<usize>,
1792 {
1793 let (a_range, b_range) = self.slice_ranges(range, self.len);
1794 // SAFETY: The ranges returned by `slice_ranges`
1795 // are valid ranges into the physical buffer, so
1796 // it's ok to pass them to `buffer_range` and
1797 // dereference the result.
1798 let a = unsafe { &*self.buffer_range(a_range) };
1799 let b = unsafe { &*self.buffer_range(b_range) };
1800 Iter::new(a.iter(), b.iter())
1801 }
1802
1803 /// Creates an iterator that covers the specified mutable range in the deque.
1804 ///
1805 /// # Panics
1806 ///
1807 /// Panics if the range has `start_bound > end_bound`, or, if the range is
1808 /// bounded on either end and past the length of the deque.
1809 ///
1810 /// # Examples
1811 ///
1812 /// ```
1813 /// use std::collections::VecDeque;
1814 ///
1815 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1816 /// for v in deque.range_mut(2..) {
1817 /// *v *= 2;
1818 /// }
1819 /// assert_eq!(deque, [1, 2, 6]);
1820 ///
1821 /// // A full range covers all contents
1822 /// for v in deque.range_mut(..) {
1823 /// *v *= 2;
1824 /// }
1825 /// assert_eq!(deque, [2, 4, 12]);
1826 /// ```
1827 #[inline]
1828 #[stable(feature = "deque_range", since = "1.51.0")]
1829 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1830 where
1831 R: RangeBounds<usize>,
1832 {
1833 let (a_range, b_range) = self.slice_ranges(range, self.len);
1834 // SAFETY: The ranges returned by `slice_ranges`
1835 // are valid ranges into the physical buffer, so
1836 // it's ok to pass them to `buffer_range` and
1837 // dereference the result.
1838 let a = unsafe { &mut *self.buffer_range(a_range) };
1839 let b = unsafe { &mut *self.buffer_range(b_range) };
1840 IterMut::new(a.iter_mut(), b.iter_mut())
1841 }
1842
1843 /// Removes the specified range from the deque in bulk, returning all
1844 /// removed elements as an iterator. If the iterator is dropped before
1845 /// being fully consumed, it drops the remaining removed elements.
1846 ///
1847 /// The returned iterator keeps a mutable borrow on the queue to optimize
1848 /// its implementation.
1849 ///
1850 ///
1851 /// # Panics
1852 ///
1853 /// Panics if the range has `start_bound > end_bound`, or, if the range is
1854 /// bounded on either end and past the length of the deque.
1855 ///
1856 /// # Leaking
1857 ///
1858 /// If the returned iterator goes out of scope without being dropped (due to
1859 /// [`mem::forget`], for example), the deque may have lost and leaked
1860 /// elements arbitrarily, including elements outside the range.
1861 ///
1862 /// # Examples
1863 ///
1864 /// ```
1865 /// use std::collections::VecDeque;
1866 ///
1867 /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1868 /// let drained = deque.drain(2..).collect::<VecDeque<_>>();
1869 /// assert_eq!(drained, [3]);
1870 /// assert_eq!(deque, [1, 2]);
1871 ///
1872 /// // A full range clears all contents, like `clear()` does
1873 /// deque.drain(..);
1874 /// assert!(deque.is_empty());
1875 /// ```
1876 #[inline]
1877 #[stable(feature = "drain", since = "1.6.0")]
1878 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1879 where
1880 R: RangeBounds<usize>,
1881 {
1882 // Memory safety
1883 //
1884 // When the Drain is first created, the source deque is shortened to
1885 // make sure no uninitialized or moved-from elements are accessible at
1886 // all if the Drain's destructor never gets to run.
1887 //
1888 // Drain will ptr::read out the values to remove.
1889 // When finished, the remaining data will be copied back to cover the hole,
1890 // and the head/tail values will be restored correctly.
1891 //
1892 let Range { start, end } = slice::range(range, ..self.len);
1893 let drain_start = start;
1894 let drain_len = end - start;
1895
1896 // The deque's elements are parted into three segments:
1897 // * 0 -> drain_start
1898 // * drain_start -> drain_start+drain_len
1899 // * drain_start+drain_len -> self.len
1900 //
1901 // H = self.head; T = self.head+self.len; t = drain_start+drain_len; h = drain_head
1902 //
1903 // We store drain_start as self.len, and drain_len and self.len as
1904 // drain_len and orig_len respectively on the Drain. This also
1905 // truncates the effective array such that if the Drain is leaked, we
1906 // have forgotten about the potentially moved values after the start of
1907 // the drain.
1908 //
1909 // H h t T
1910 // [. . . o o x x o o . . .]
1911 //
1912 // "forget" about the values after the start of the drain until after
1913 // the drain is complete and the Drain destructor is run.
1914
1915 unsafe { Drain::new(self, drain_start, drain_len) }
1916 }
1917
1918 /// Creates a splicing iterator that replaces the specified range in the deque with the given
1919 /// `replace_with` iterator and yields the removed items. `replace_with` does not need to be the
1920 /// same length as `range`.
1921 ///
1922 /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped.
1923 ///
1924 /// It is unspecified how many elements are removed from the deque if the `Splice` value is
1925 /// leaked.
1926 ///
1927 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
1928 ///
1929 /// This is optimal if:
1930 ///
1931 /// * The tail (elements in the deque after `range`) is empty,
1932 /// * or `replace_with` yields fewer or equal elements than `range`'s length
1933 /// * or the lower bound of its `size_hint()` is exact.
1934 ///
1935 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
1936 ///
1937 /// # Panics
1938 ///
1939 /// Panics if the range has `start_bound > end_bound`, or, if the range is
1940 /// bounded on either end and past the length of the deque.
1941 ///
1942 /// # Examples
1943 ///
1944 /// ```
1945 /// # #![feature(deque_extend_front)]
1946 /// # use std::collections::VecDeque;
1947 ///
1948 /// let mut v = VecDeque::from(vec![1, 2, 3, 4]);
1949 /// let new = [7, 8, 9];
1950 /// let u: Vec<_> = v.splice(1..3, new).collect();
1951 /// assert_eq!(v, [1, 7, 8, 9, 4]);
1952 /// assert_eq!(u, [2, 3]);
1953 /// ```
1954 ///
1955 /// Using `splice` to insert new items into a vector efficiently at a specific position
1956 /// indicated by an empty range:
1957 ///
1958 /// ```
1959 /// # #![feature(deque_extend_front)]
1960 /// # use std::collections::VecDeque;
1961 ///
1962 /// let mut v = VecDeque::from(vec![1, 5]);
1963 /// let new = [2, 3, 4];
1964 /// v.splice(1..1, new);
1965 /// assert_eq!(v, [1, 2, 3, 4, 5]);
1966 /// ```
1967 #[unstable(feature = "deque_extend_front", issue = "146975")]
1968 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
1969 where
1970 R: RangeBounds<usize>,
1971 I: IntoIterator<Item = T>,
1972 {
1973 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
1974 }
1975
1976 /// Clears the deque, removing all values.
1977 ///
1978 /// # Examples
1979 ///
1980 /// ```
1981 /// use std::collections::VecDeque;
1982 ///
1983 /// let mut deque = VecDeque::new();
1984 /// deque.push_back(1);
1985 /// deque.clear();
1986 /// assert!(deque.is_empty());
1987 /// ```
1988 #[stable(feature = "rust1", since = "1.0.0")]
1989 #[inline]
1990 pub fn clear(&mut self) {
1991 self.truncate(0);
1992 // Not strictly necessary, but leaves things in a more consistent/predictable state.
1993 self.head = WrappedIndex::zero();
1994 }
1995
1996 /// Returns `true` if the deque contains an element equal to the
1997 /// given value.
1998 ///
1999 /// This operation is *O*(*n*).
2000 ///
2001 /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
2002 ///
2003 /// [`binary_search`]: VecDeque::binary_search
2004 ///
2005 /// # Examples
2006 ///
2007 /// ```
2008 /// use std::collections::VecDeque;
2009 ///
2010 /// let mut deque: VecDeque<u32> = VecDeque::new();
2011 ///
2012 /// deque.push_back(0);
2013 /// deque.push_back(1);
2014 ///
2015 /// assert_eq!(deque.contains(&1), true);
2016 /// assert_eq!(deque.contains(&10), false);
2017 /// ```
2018 #[stable(feature = "vec_deque_contains", since = "1.12.0")]
2019 pub fn contains(&self, x: &T) -> bool
2020 where
2021 T: PartialEq<T>,
2022 {
2023 let (a, b) = self.as_slices();
2024 a.contains(x) || b.contains(x)
2025 }
2026
2027 /// Provides a reference to the front element, or `None` if the deque is
2028 /// empty.
2029 ///
2030 /// # Examples
2031 ///
2032 /// ```
2033 /// use std::collections::VecDeque;
2034 ///
2035 /// let mut d = VecDeque::new();
2036 /// assert_eq!(d.front(), None);
2037 ///
2038 /// d.push_back(1);
2039 /// d.push_back(2);
2040 /// assert_eq!(d.front(), Some(&1));
2041 /// ```
2042 #[stable(feature = "rust1", since = "1.0.0")]
2043 #[rustc_confusables("first")]
2044 pub fn front(&self) -> Option<&T> {
2045 self.get(0)
2046 }
2047
2048 /// Provides a mutable reference to the front element, or `None` if the
2049 /// deque is empty.
2050 ///
2051 /// # Examples
2052 ///
2053 /// ```
2054 /// use std::collections::VecDeque;
2055 ///
2056 /// let mut d = VecDeque::new();
2057 /// assert_eq!(d.front_mut(), None);
2058 ///
2059 /// d.push_back(1);
2060 /// d.push_back(2);
2061 /// match d.front_mut() {
2062 /// Some(x) => *x = 9,
2063 /// None => (),
2064 /// }
2065 /// assert_eq!(d.front(), Some(&9));
2066 /// ```
2067 #[stable(feature = "rust1", since = "1.0.0")]
2068 pub fn front_mut(&mut self) -> Option<&mut T> {
2069 self.get_mut(0)
2070 }
2071
2072 /// Provides a reference to the back element, or `None` if the deque is
2073 /// empty.
2074 ///
2075 /// # Examples
2076 ///
2077 /// ```
2078 /// use std::collections::VecDeque;
2079 ///
2080 /// let mut d = VecDeque::new();
2081 /// assert_eq!(d.back(), None);
2082 ///
2083 /// d.push_back(1);
2084 /// d.push_back(2);
2085 /// assert_eq!(d.back(), Some(&2));
2086 /// ```
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 #[rustc_confusables("last")]
2089 pub fn back(&self) -> Option<&T> {
2090 self.get(self.len.wrapping_sub(1))
2091 }
2092
2093 /// Provides a mutable reference to the back element, or `None` if the
2094 /// deque is empty.
2095 ///
2096 /// # Examples
2097 ///
2098 /// ```
2099 /// use std::collections::VecDeque;
2100 ///
2101 /// let mut d = VecDeque::new();
2102 /// assert_eq!(d.back(), None);
2103 ///
2104 /// d.push_back(1);
2105 /// d.push_back(2);
2106 /// match d.back_mut() {
2107 /// Some(x) => *x = 9,
2108 /// None => (),
2109 /// }
2110 /// assert_eq!(d.back(), Some(&9));
2111 /// ```
2112 #[stable(feature = "rust1", since = "1.0.0")]
2113 pub fn back_mut(&mut self) -> Option<&mut T> {
2114 self.get_mut(self.len.wrapping_sub(1))
2115 }
2116
2117 /// Removes the first element and returns it, or `None` if the deque is
2118 /// empty.
2119 ///
2120 /// # Examples
2121 ///
2122 /// ```
2123 /// use std::collections::VecDeque;
2124 ///
2125 /// let mut d = VecDeque::new();
2126 /// d.push_back(1);
2127 /// d.push_back(2);
2128 ///
2129 /// assert_eq!(d.pop_front(), Some(1));
2130 /// assert_eq!(d.pop_front(), Some(2));
2131 /// assert_eq!(d.pop_front(), None);
2132 /// ```
2133 #[stable(feature = "rust1", since = "1.0.0")]
2134 pub fn pop_front(&mut self) -> Option<T> {
2135 if self.is_empty() {
2136 None
2137 } else {
2138 let old_head = self.head;
2139 self.head = self.to_wrapped_index(1);
2140 self.len -= 1;
2141 unsafe {
2142 core::hint::assert_unchecked(self.len < self.capacity());
2143 Some(self.buffer_read(old_head))
2144 }
2145 }
2146 }
2147
2148 /// Removes the last element from the deque and returns it, or `None` if
2149 /// it is empty.
2150 ///
2151 /// # Examples
2152 ///
2153 /// ```
2154 /// use std::collections::VecDeque;
2155 ///
2156 /// let mut buf = VecDeque::new();
2157 /// assert_eq!(buf.pop_back(), None);
2158 /// buf.push_back(1);
2159 /// buf.push_back(3);
2160 /// assert_eq!(buf.pop_back(), Some(3));
2161 /// ```
2162 #[stable(feature = "rust1", since = "1.0.0")]
2163 pub fn pop_back(&mut self) -> Option<T> {
2164 if self.is_empty() {
2165 None
2166 } else {
2167 self.len -= 1;
2168 unsafe {
2169 core::hint::assert_unchecked(self.len < self.capacity());
2170 Some(self.buffer_read(self.to_wrapped_index(self.len)))
2171 }
2172 }
2173 }
2174
2175 /// Removes and returns the first element from the deque if the predicate
2176 /// returns `true`, or [`None`] if the predicate returns false or the deque
2177 /// is empty (the predicate will not be called in that case).
2178 ///
2179 /// # Examples
2180 ///
2181 /// ```
2182 /// use std::collections::VecDeque;
2183 ///
2184 /// let mut deque: VecDeque<i32> = vec![0, 1, 2, 3, 4].into();
2185 /// let pred = |x: &mut i32| *x % 2 == 0;
2186 ///
2187 /// assert_eq!(deque.pop_front_if(pred), Some(0));
2188 /// assert_eq!(deque, [1, 2, 3, 4]);
2189 /// assert_eq!(deque.pop_front_if(pred), None);
2190 /// ```
2191 #[stable(feature = "vec_deque_pop_if", since = "1.93.0")]
2192 pub fn pop_front_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2193 let first = self.front_mut()?;
2194 if predicate(first) { self.pop_front() } else { None }
2195 }
2196
2197 /// Removes and returns the last element from the deque if the predicate
2198 /// returns `true`, or [`None`] if the predicate returns false or the deque
2199 /// is empty (the predicate will not be called in that case).
2200 ///
2201 /// # Examples
2202 ///
2203 /// ```
2204 /// use std::collections::VecDeque;
2205 ///
2206 /// let mut deque: VecDeque<i32> = vec![0, 1, 2, 3, 4].into();
2207 /// let pred = |x: &mut i32| *x % 2 == 0;
2208 ///
2209 /// assert_eq!(deque.pop_back_if(pred), Some(4));
2210 /// assert_eq!(deque, [0, 1, 2, 3]);
2211 /// assert_eq!(deque.pop_back_if(pred), None);
2212 /// ```
2213 #[stable(feature = "vec_deque_pop_if", since = "1.93.0")]
2214 pub fn pop_back_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2215 let last = self.back_mut()?;
2216 if predicate(last) { self.pop_back() } else { None }
2217 }
2218
2219 /// Prepends an element to the deque.
2220 ///
2221 /// # Examples
2222 ///
2223 /// ```
2224 /// use std::collections::VecDeque;
2225 ///
2226 /// let mut d = VecDeque::new();
2227 /// d.push_front(1);
2228 /// d.push_front(2);
2229 /// assert_eq!(d.front(), Some(&2));
2230 /// ```
2231 #[stable(feature = "rust1", since = "1.0.0")]
2232 pub fn push_front(&mut self, value: T) {
2233 let _ = self.push_front_mut(value);
2234 }
2235
2236 /// Prepends an element to the deque, returning a reference to it.
2237 ///
2238 /// # Examples
2239 ///
2240 /// ```
2241 /// use std::collections::VecDeque;
2242 ///
2243 /// let mut d = VecDeque::from([1, 2, 3]);
2244 /// let x = d.push_front_mut(8);
2245 /// *x -= 1;
2246 /// assert_eq!(d.front(), Some(&7));
2247 /// ```
2248 #[stable(feature = "push_mut", since = "1.95.0")]
2249 #[must_use = "if you don't need a reference to the value, use `VecDeque::push_front` instead"]
2250 pub fn push_front_mut(&mut self, value: T) -> &mut T {
2251 if self.is_full() {
2252 self.grow();
2253 }
2254
2255 self.head = self.wrap_sub(self.head, 1);
2256 self.len += 1;
2257 // SAFETY: We know that self.head is within range of the deque.
2258 unsafe { self.buffer_write(self.head, value) }
2259 }
2260
2261 /// Appends an element to the back of the deque.
2262 ///
2263 /// # Examples
2264 ///
2265 /// ```
2266 /// use std::collections::VecDeque;
2267 ///
2268 /// let mut buf = VecDeque::new();
2269 /// buf.push_back(1);
2270 /// buf.push_back(3);
2271 /// assert_eq!(3, *buf.back().unwrap());
2272 /// ```
2273 #[stable(feature = "rust1", since = "1.0.0")]
2274 #[rustc_confusables("push", "put", "append")]
2275 pub fn push_back(&mut self, value: T) {
2276 let _ = self.push_back_mut(value);
2277 }
2278
2279 /// Appends an element to the back of the deque, returning a reference to it.
2280 ///
2281 /// # Examples
2282 ///
2283 /// ```
2284 /// use std::collections::VecDeque;
2285 ///
2286 /// let mut d = VecDeque::from([1, 2, 3]);
2287 /// let x = d.push_back_mut(9);
2288 /// *x += 1;
2289 /// assert_eq!(d.back(), Some(&10));
2290 /// ```
2291 #[stable(feature = "push_mut", since = "1.95.0")]
2292 #[must_use = "if you don't need a reference to the value, use `VecDeque::push_back` instead"]
2293 pub fn push_back_mut(&mut self, value: T) -> &mut T {
2294 if self.is_full() {
2295 self.grow();
2296 }
2297
2298 let len = self.len;
2299 self.len += 1;
2300 unsafe { self.buffer_write(self.to_wrapped_index(len), value) }
2301 }
2302
2303 /// Prepends all contents of the iterator to the front of the deque.
2304 /// The order of the contents is preserved.
2305 ///
2306 /// To get behavior like [`append`][VecDeque::append] where elements are moved
2307 /// from the other collection to this one, use `self.prepend(other.drain(..))`.
2308 ///
2309 /// # Examples
2310 ///
2311 /// ```
2312 /// #![feature(deque_extend_front)]
2313 /// use std::collections::VecDeque;
2314 ///
2315 /// let mut deque = VecDeque::from([4, 5, 6]);
2316 /// deque.prepend([1, 2, 3]);
2317 /// assert_eq!(deque, [1, 2, 3, 4, 5, 6]);
2318 /// ```
2319 ///
2320 /// Move values between collections like [`append`][VecDeque::append] does but prepend to the front:
2321 ///
2322 /// ```
2323 /// #![feature(deque_extend_front)]
2324 /// use std::collections::VecDeque;
2325 ///
2326 /// let mut deque1 = VecDeque::from([4, 5, 6]);
2327 /// let mut deque2 = VecDeque::from([1, 2, 3]);
2328 /// deque1.prepend(deque2.drain(..));
2329 /// assert_eq!(deque1, [1, 2, 3, 4, 5, 6]);
2330 /// assert!(deque2.is_empty());
2331 /// ```
2332 #[unstable(feature = "deque_extend_front", issue = "146975")]
2333 #[track_caller]
2334 pub fn prepend<I: IntoIterator<Item = T, IntoIter: DoubleEndedIterator>>(&mut self, other: I) {
2335 self.extend_front(other.into_iter().rev())
2336 }
2337
2338 /// Prepends all contents of the iterator to the front of the deque,
2339 /// as if [`push_front`][VecDeque::push_front] was called repeatedly with
2340 /// the values yielded by the iterator.
2341 ///
2342 /// # Examples
2343 ///
2344 /// ```
2345 /// #![feature(deque_extend_front)]
2346 /// use std::collections::VecDeque;
2347 ///
2348 /// let mut deque = VecDeque::from([4, 5, 6]);
2349 /// deque.extend_front([3, 2, 1]);
2350 /// assert_eq!(deque, [1, 2, 3, 4, 5, 6]);
2351 /// ```
2352 ///
2353 /// This behaves like [`push_front`][VecDeque::push_front] was called repeatedly:
2354 ///
2355 /// ```
2356 /// use std::collections::VecDeque;
2357 ///
2358 /// let mut deque = VecDeque::from([4, 5, 6]);
2359 /// for v in [3, 2, 1] {
2360 /// deque.push_front(v);
2361 /// }
2362 /// assert_eq!(deque, [1, 2, 3, 4, 5, 6]);
2363 /// ```
2364 #[unstable(feature = "deque_extend_front", issue = "146975")]
2365 #[track_caller]
2366 pub fn extend_front<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2367 <Self as SpecExtendFront<T, I::IntoIter>>::spec_extend_front(self, iter.into_iter());
2368 }
2369
2370 #[inline]
2371 fn is_contiguous(&self) -> bool {
2372 // Do the calculation like this to avoid overflowing if len + head > usize::MAX
2373 self.head <= self.capacity() - self.len
2374 }
2375
2376 /// Removes an element from anywhere in the deque and returns it,
2377 /// replacing it with the first element.
2378 ///
2379 /// This does not preserve ordering, but is *O*(1).
2380 ///
2381 /// Returns `None` if `index` is out of bounds.
2382 ///
2383 /// Element at index 0 is the front of the queue.
2384 ///
2385 /// # Examples
2386 ///
2387 /// ```
2388 /// use std::collections::VecDeque;
2389 ///
2390 /// let mut buf = VecDeque::new();
2391 /// assert_eq!(buf.swap_remove_front(0), None);
2392 /// buf.push_back(1);
2393 /// buf.push_back(2);
2394 /// buf.push_back(3);
2395 /// assert_eq!(buf, [1, 2, 3]);
2396 ///
2397 /// assert_eq!(buf.swap_remove_front(2), Some(3));
2398 /// assert_eq!(buf, [2, 1]);
2399 /// ```
2400 #[stable(feature = "deque_extras_15", since = "1.5.0")]
2401 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
2402 let length = self.len;
2403 if index < length && index != 0 {
2404 self.swap(index, 0);
2405 } else if index >= length {
2406 return None;
2407 }
2408 self.pop_front()
2409 }
2410
2411 /// Removes an element from anywhere in the deque and returns it,
2412 /// replacing it with the last element.
2413 ///
2414 /// This does not preserve ordering, but is *O*(1).
2415 ///
2416 /// Returns `None` if `index` is out of bounds.
2417 ///
2418 /// Element at index 0 is the front of the queue.
2419 ///
2420 /// # Examples
2421 ///
2422 /// ```
2423 /// use std::collections::VecDeque;
2424 ///
2425 /// let mut buf = VecDeque::new();
2426 /// assert_eq!(buf.swap_remove_back(0), None);
2427 /// buf.push_back(1);
2428 /// buf.push_back(2);
2429 /// buf.push_back(3);
2430 /// assert_eq!(buf, [1, 2, 3]);
2431 ///
2432 /// assert_eq!(buf.swap_remove_back(0), Some(1));
2433 /// assert_eq!(buf, [3, 2]);
2434 /// ```
2435 #[stable(feature = "deque_extras_15", since = "1.5.0")]
2436 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
2437 let length = self.len;
2438 if length > 0 && index < length - 1 {
2439 self.swap(index, length - 1);
2440 } else if index >= length {
2441 return None;
2442 }
2443 self.pop_back()
2444 }
2445
2446 /// Inserts an element at `index` within the deque, shifting all elements
2447 /// with indices greater than or equal to `index` towards the back.
2448 ///
2449 /// Element at index 0 is the front of the queue.
2450 ///
2451 /// # Panics
2452 ///
2453 /// Panics if `index` is strictly greater than the deque's length.
2454 ///
2455 /// # Examples
2456 ///
2457 /// ```
2458 /// use std::collections::VecDeque;
2459 ///
2460 /// let mut vec_deque = VecDeque::new();
2461 /// vec_deque.push_back('a');
2462 /// vec_deque.push_back('b');
2463 /// vec_deque.push_back('c');
2464 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
2465 ///
2466 /// vec_deque.insert(1, 'd');
2467 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
2468 ///
2469 /// vec_deque.insert(4, 'e');
2470 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c', 'e']);
2471 /// ```
2472 #[stable(feature = "deque_extras_15", since = "1.5.0")]
2473 pub fn insert(&mut self, index: usize, value: T) {
2474 let _ = self.insert_mut(index, value);
2475 }
2476
2477 /// Inserts an element at `index` within the deque, shifting all elements
2478 /// with indices greater than or equal to `index` towards the back, and
2479 /// returning a reference to it.
2480 ///
2481 /// Element at index 0 is the front of the queue.
2482 ///
2483 /// # Panics
2484 ///
2485 /// Panics if `index` is strictly greater than the deque's length.
2486 ///
2487 /// # Examples
2488 ///
2489 /// ```
2490 /// use std::collections::VecDeque;
2491 ///
2492 /// let mut vec_deque = VecDeque::from([1, 2, 3]);
2493 ///
2494 /// let x = vec_deque.insert_mut(1, 5);
2495 /// *x += 7;
2496 /// assert_eq!(vec_deque, &[1, 12, 2, 3]);
2497 /// ```
2498 #[stable(feature = "push_mut", since = "1.95.0")]
2499 #[must_use = "if you don't need a reference to the value, use `VecDeque::insert` instead"]
2500 pub fn insert_mut(&mut self, index: usize, value: T) -> &mut T {
2501 assert!(index <= self.len(), "index out of bounds");
2502
2503 if self.is_full() {
2504 self.grow();
2505 }
2506
2507 let k = self.len - index;
2508 if k < index {
2509 // `index + 1` can't overflow, because if index was usize::MAX, then either the
2510 // assert would've failed, or the deque would've tried to grow past usize::MAX
2511 // and panicked.
2512 unsafe {
2513 // see `remove()` for explanation why this wrap_copy() call is safe.
2514 self.wrap_copy(self.to_wrapped_index(index), self.to_wrapped_index(index + 1), k);
2515 self.len += 1;
2516 self.buffer_write(self.to_wrapped_index(index), value)
2517 }
2518 } else {
2519 let old_head = self.head;
2520 self.head = self.wrap_sub(self.head, 1);
2521 unsafe {
2522 self.wrap_copy(old_head, self.head, index);
2523 self.len += 1;
2524 self.buffer_write(self.to_wrapped_index(index), value)
2525 }
2526 }
2527 }
2528
2529 /// Removes and returns the element at `index` from the deque.
2530 /// Whichever end is closer to the removal point will be moved to make
2531 /// room, and all the affected elements will be moved to new positions.
2532 /// Returns `None` if `index` is out of bounds.
2533 ///
2534 /// Element at index 0 is the front of the queue.
2535 ///
2536 /// # Examples
2537 ///
2538 /// ```
2539 /// use std::collections::VecDeque;
2540 ///
2541 /// let mut buf = VecDeque::new();
2542 /// buf.push_back('a');
2543 /// buf.push_back('b');
2544 /// buf.push_back('c');
2545 /// assert_eq!(buf, ['a', 'b', 'c']);
2546 ///
2547 /// assert_eq!(buf.remove(1), Some('b'));
2548 /// assert_eq!(buf, ['a', 'c']);
2549 /// ```
2550 #[stable(feature = "rust1", since = "1.0.0")]
2551 #[rustc_confusables("delete", "take")]
2552 pub fn remove(&mut self, index: usize) -> Option<T> {
2553 if self.len <= index {
2554 return None;
2555 }
2556
2557 let wrapped_idx = self.to_wrapped_index(index);
2558
2559 let elem = unsafe { Some(self.buffer_read(wrapped_idx)) };
2560
2561 let k = self.len - index - 1;
2562 // safety: due to the nature of the if-condition, whichever wrap_copy gets called,
2563 // its length argument will be at most `self.len / 2`, so there can't be more than
2564 // one overlapping area.
2565 if k < index {
2566 unsafe { self.wrap_copy(self.wrap_add(wrapped_idx, 1), wrapped_idx, k) };
2567 self.len -= 1;
2568 } else {
2569 let old_head = self.head;
2570 self.head = self.to_wrapped_index(1);
2571 unsafe { self.wrap_copy(old_head, self.head, index) };
2572 self.len -= 1;
2573 }
2574
2575 elem
2576 }
2577
2578 /// Splits the deque into two at the given index.
2579 ///
2580 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2581 /// and the returned deque contains elements `[at, len)`.
2582 ///
2583 /// Note that the capacity of `self` does not change.
2584 ///
2585 /// Element at index 0 is the front of the queue.
2586 ///
2587 /// # Panics
2588 ///
2589 /// Panics if `at > len`.
2590 ///
2591 /// # Examples
2592 ///
2593 /// ```
2594 /// use std::collections::VecDeque;
2595 ///
2596 /// let mut buf: VecDeque<_> = ['a', 'b', 'c'].into();
2597 /// let buf2 = buf.split_off(1);
2598 /// assert_eq!(buf, ['a']);
2599 /// assert_eq!(buf2, ['b', 'c']);
2600 /// ```
2601 #[inline]
2602 #[must_use = "use `.truncate()` if you don't need the other half"]
2603 #[stable(feature = "split_off", since = "1.4.0")]
2604 pub fn split_off(&mut self, at: usize) -> Self
2605 where
2606 A: Clone,
2607 {
2608 let len = self.len;
2609 assert!(at <= len, "`at` out of bounds");
2610
2611 let other_len = len - at;
2612 let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2613
2614 let (first_half, second_half) = self.as_slices();
2615 let first_len = first_half.len();
2616 let second_len = second_half.len();
2617
2618 unsafe {
2619 if at < first_len {
2620 // `at` lies in the first half.
2621 let amount_in_first = first_len - at;
2622
2623 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2624
2625 // just take all of the second half.
2626 ptr::copy_nonoverlapping(
2627 second_half.as_ptr(),
2628 other.ptr().add(amount_in_first),
2629 second_len,
2630 );
2631 } else {
2632 // `at` lies in the second half, need to factor in the elements we skipped
2633 // in the first half.
2634 let offset = at - first_len;
2635 let amount_in_second = second_len - offset;
2636 ptr::copy_nonoverlapping(
2637 second_half.as_ptr().add(offset),
2638 other.ptr(),
2639 amount_in_second,
2640 );
2641 }
2642 }
2643
2644 // Cleanup where the ends of the buffers are
2645 self.len = at;
2646 other.len = other_len;
2647
2648 other
2649 }
2650
2651 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2652 ///
2653 /// # Panics
2654 ///
2655 /// Panics if the new number of elements in self overflows a `usize`.
2656 ///
2657 /// # Examples
2658 ///
2659 /// ```
2660 /// use std::collections::VecDeque;
2661 ///
2662 /// let mut buf: VecDeque<_> = [1, 2].into();
2663 /// let mut buf2: VecDeque<_> = [3, 4].into();
2664 /// buf.append(&mut buf2);
2665 /// assert_eq!(buf, [1, 2, 3, 4]);
2666 /// assert_eq!(buf2, []);
2667 /// ```
2668 #[inline]
2669 #[stable(feature = "append", since = "1.4.0")]
2670 pub fn append(&mut self, other: &mut Self) {
2671 if T::IS_ZST {
2672 self.len = self.len.checked_add(other.len).expect("capacity overflow");
2673 other.len = 0;
2674 other.head = WrappedIndex::zero();
2675 return;
2676 }
2677
2678 self.reserve(other.len);
2679 unsafe {
2680 let (left, right) = other.as_slices();
2681 self.copy_slice(self.to_wrapped_index(self.len), left);
2682 // no overflow, because self.capacity() >= old_cap + left.len() >= self.len + left.len()
2683 self.copy_slice(self.to_wrapped_index(self.len + left.len()), right);
2684 }
2685 // SAFETY: Update pointers after copying to avoid leaving doppelganger
2686 // in case of panics.
2687 self.len += other.len;
2688 // Now that we own its values, forget everything in `other`.
2689 other.len = 0;
2690 other.head = WrappedIndex::zero();
2691 }
2692
2693 /// Retains only the elements specified by the predicate.
2694 ///
2695 /// In other words, remove all elements `e` for which `f(&e)` returns false.
2696 /// This method operates in place, visiting each element exactly once in the
2697 /// original order, and preserves the order of the retained elements.
2698 ///
2699 /// # Examples
2700 ///
2701 /// ```
2702 /// use std::collections::VecDeque;
2703 ///
2704 /// let mut buf = VecDeque::new();
2705 /// buf.extend(1..5);
2706 /// buf.retain(|&x| x % 2 == 0);
2707 /// assert_eq!(buf, [2, 4]);
2708 /// ```
2709 ///
2710 /// Because the elements are visited exactly once in the original order,
2711 /// external state may be used to decide which elements to keep.
2712 ///
2713 /// ```
2714 /// use std::collections::VecDeque;
2715 ///
2716 /// let mut buf = VecDeque::new();
2717 /// buf.extend(1..6);
2718 ///
2719 /// let keep = [false, true, true, false, true];
2720 /// let mut iter = keep.iter();
2721 /// buf.retain(|_| *iter.next().unwrap());
2722 /// assert_eq!(buf, [2, 3, 5]);
2723 /// ```
2724 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2725 pub fn retain<F>(&mut self, mut f: F)
2726 where
2727 F: FnMut(&T) -> bool,
2728 {
2729 self.retain_mut(|elem| f(elem));
2730 }
2731
2732 /// Retains only the elements specified by the predicate.
2733 ///
2734 /// In other words, remove all elements `e` for which `f(&mut e)` returns false.
2735 /// This method operates in place, visiting each element exactly once in the
2736 /// original order, and preserves the order of the retained elements.
2737 ///
2738 /// # Examples
2739 ///
2740 /// ```
2741 /// use std::collections::VecDeque;
2742 ///
2743 /// let mut buf = VecDeque::new();
2744 /// buf.extend(1..5);
2745 /// buf.retain_mut(|x| if *x % 2 == 0 {
2746 /// *x += 1;
2747 /// true
2748 /// } else {
2749 /// false
2750 /// });
2751 /// assert_eq!(buf, [3, 5]);
2752 /// ```
2753 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2754 pub fn retain_mut<F>(&mut self, mut f: F)
2755 where
2756 F: FnMut(&mut T) -> bool,
2757 {
2758 let len = self.len;
2759 let mut idx = 0;
2760 let mut cur = 0;
2761
2762 // Stage 1: All values are retained.
2763 while cur < len {
2764 if !f(&mut self[cur]) {
2765 cur += 1;
2766 break;
2767 }
2768 cur += 1;
2769 idx += 1;
2770 }
2771 // Stage 2: Swap retained value into current idx.
2772 while cur < len {
2773 if !f(&mut self[cur]) {
2774 cur += 1;
2775 continue;
2776 }
2777
2778 self.swap(idx, cur);
2779 cur += 1;
2780 idx += 1;
2781 }
2782 // Stage 3: Truncate all values after idx.
2783 if cur != idx {
2784 self.truncate(idx);
2785 }
2786 }
2787
2788 // Double the buffer size. This method is inline(never), so we expect it to only
2789 // be called in cold paths.
2790 // This may panic or abort
2791 #[inline(never)]
2792 fn grow(&mut self) {
2793 // Extend or possibly remove this assertion when valid use-cases for growing the
2794 // buffer without it being full emerge
2795 debug_assert!(self.is_full());
2796 let old_cap = self.capacity();
2797 self.buf.grow_one();
2798 unsafe {
2799 self.handle_capacity_increase(old_cap);
2800 }
2801 debug_assert!(!self.is_full());
2802 }
2803
2804 /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2805 /// either by removing excess elements from the back or by appending
2806 /// elements generated by calling `generator` to the back.
2807 ///
2808 /// # Examples
2809 ///
2810 /// ```
2811 /// use std::collections::VecDeque;
2812 ///
2813 /// let mut buf = VecDeque::new();
2814 /// buf.push_back(5);
2815 /// buf.push_back(10);
2816 /// buf.push_back(15);
2817 /// assert_eq!(buf, [5, 10, 15]);
2818 ///
2819 /// buf.resize_with(5, Default::default);
2820 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2821 ///
2822 /// buf.resize_with(2, || unreachable!());
2823 /// assert_eq!(buf, [5, 10]);
2824 ///
2825 /// let mut state = 100;
2826 /// buf.resize_with(5, || { state += 1; state });
2827 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2828 /// ```
2829 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2830 pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2831 let len = self.len;
2832
2833 if new_len > len {
2834 self.extend(repeat_with(generator).take(new_len - len))
2835 } else {
2836 self.truncate(new_len);
2837 }
2838 }
2839
2840 /// Rearranges the internal storage of this deque so it is one contiguous
2841 /// slice, which is then returned.
2842 ///
2843 /// This method does not allocate and does not change the order of the
2844 /// inserted elements. As it returns a mutable slice, this can be used to
2845 /// sort a deque.
2846 ///
2847 /// Once the internal storage is contiguous, the [`as_slices`] and
2848 /// [`as_mut_slices`] methods will return the entire contents of the
2849 /// deque in a single slice.
2850 ///
2851 /// [`as_slices`]: VecDeque::as_slices
2852 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2853 ///
2854 /// # Examples
2855 ///
2856 /// Sorting the content of a deque.
2857 ///
2858 /// ```
2859 /// use std::collections::VecDeque;
2860 ///
2861 /// let mut buf = VecDeque::with_capacity(15);
2862 ///
2863 /// buf.push_back(2);
2864 /// buf.push_back(1);
2865 /// buf.push_front(3);
2866 ///
2867 /// // sorting the deque
2868 /// buf.make_contiguous().sort();
2869 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2870 ///
2871 /// // sorting it in reverse order
2872 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2873 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2874 /// ```
2875 ///
2876 /// Getting immutable access to the contiguous slice.
2877 ///
2878 /// ```rust
2879 /// use std::collections::VecDeque;
2880 ///
2881 /// let mut buf = VecDeque::new();
2882 ///
2883 /// buf.push_back(2);
2884 /// buf.push_back(1);
2885 /// buf.push_front(3);
2886 ///
2887 /// buf.make_contiguous();
2888 /// if let (slice, &[]) = buf.as_slices() {
2889 /// // we can now be sure that `slice` contains all elements of the deque,
2890 /// // while still having immutable access to `buf`.
2891 /// assert_eq!(buf.len(), slice.len());
2892 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2893 /// }
2894 /// ```
2895 #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2896 pub fn make_contiguous(&mut self) -> &mut [T] {
2897 if T::IS_ZST {
2898 self.head = WrappedIndex::zero();
2899 }
2900
2901 if self.is_contiguous() {
2902 unsafe {
2903 return slice::from_raw_parts_mut(self.ptr().add(self.head.as_index()), self.len);
2904 }
2905 }
2906
2907 let &mut Self { head, len, .. } = self;
2908 let ptr = self.ptr();
2909 let cap = self.capacity();
2910
2911 let free = cap - len;
2912 let head_len = cap - head.as_index();
2913
2914 // tail <= head < capacity
2915 // head cannot be <= capacity, because we know that VecDeque is non-empty, since it is not
2916 // contiguous at this point
2917 let tail = WrappedIndex::from_arbitrary_number(len - head_len);
2918 let tail_len = tail.as_index();
2919
2920 if free >= head_len {
2921 // there is enough free space to copy the head in one go,
2922 // this means that we first shift the tail backwards, and then
2923 // copy the head to the correct position.
2924 //
2925 // from: DEFGH....ABC
2926 // to: ABCDEFGH....
2927 unsafe {
2928 self.copy(
2929 WrappedIndex::zero(),
2930 WrappedIndex::from_arbitrary_number(head_len),
2931 tail_len,
2932 );
2933 // ...DEFGH.ABC
2934 self.copy_nonoverlapping(head, WrappedIndex::zero(), head_len);
2935 // ABCDEFGH....
2936 }
2937
2938 self.head = WrappedIndex::zero();
2939 } else if free >= tail_len {
2940 // there is enough free space to copy the tail in one go,
2941 // this means that we first shift the head forwards, and then
2942 // copy the tail to the correct position.
2943 //
2944 // from: FGH....ABCDE
2945 // to: ...ABCDEFGH.
2946 unsafe {
2947 self.copy(head, tail, head_len);
2948 // FGHABCDE....
2949 self.copy_nonoverlapping(WrappedIndex::zero(), tail.add(head_len), tail_len);
2950 // ...ABCDEFGH.
2951 }
2952
2953 self.head = tail;
2954 } else {
2955 // `free` is smaller than both `head_len` and `tail_len`.
2956 // the general algorithm for this first moves the slices
2957 // right next to each other and then uses `slice::rotate`
2958 // to rotate them into place:
2959 //
2960 // initially: HIJK..ABCDEFG
2961 // step 1: ..HIJKABCDEFG
2962 // step 2: ..ABCDEFGHIJK
2963 //
2964 // or:
2965 //
2966 // initially: FGHIJK..ABCDE
2967 // step 1: FGHIJKABCDE..
2968 // step 2: ABCDEFGHIJK..
2969
2970 // pick the shorter of the 2 slices to reduce the amount
2971 // of memory that needs to be moved around.
2972 if head_len > tail_len {
2973 // tail is shorter, so:
2974 // 1. copy tail forwards
2975 // 2. rotate used part of the buffer
2976 // 3. update head to point to the new beginning (which is just `free`)
2977
2978 unsafe {
2979 // if there is no free space in the buffer, then the slices are already
2980 // right next to each other and we don't need to move any memory.
2981 if free != 0 {
2982 // because we only move the tail forward as much as there's free space
2983 // behind it, we don't overwrite any elements of the head slice, and
2984 // the slices end up right next to each other.
2985 self.copy(
2986 WrappedIndex::zero(),
2987 WrappedIndex::from_arbitrary_number(free),
2988 tail_len,
2989 );
2990 }
2991
2992 // We just copied the tail right next to the head slice,
2993 // so all of the elements in the range are initialized
2994 let slice = &mut *self.buffer_range(free..self.capacity());
2995
2996 // because the deque wasn't contiguous, we know that `tail_len < self.len == slice.len()`,
2997 // so this will never panic.
2998 slice.rotate_left(tail_len);
2999
3000 // the used part of the buffer now is `free..self.capacity()`, so set
3001 // `head` to the beginning of that range.
3002 self.head = WrappedIndex::from_arbitrary_number(free);
3003 }
3004 } else {
3005 // head is shorter so:
3006 // 1. copy head backwards
3007 // 2. rotate used part of the buffer
3008 // 3. update head to point to the new beginning (which is the beginning of the buffer)
3009
3010 unsafe {
3011 // if there is no free space in the buffer, then the slices are already
3012 // right next to each other and we don't need to move any memory.
3013 if free != 0 {
3014 // copy the head slice to lie right behind the tail slice.
3015 self.copy(
3016 self.head,
3017 WrappedIndex::from_arbitrary_number(tail_len),
3018 head_len,
3019 );
3020 }
3021
3022 // because we copied the head slice so that both slices lie right
3023 // next to each other, all the elements in the range are initialized.
3024 let slice = &mut *self.buffer_range(0..self.len);
3025
3026 // because the deque wasn't contiguous, we know that `head_len < self.len == slice.len()`
3027 // so this will never panic.
3028 slice.rotate_right(head_len);
3029
3030 // the used part of the buffer now is `0..self.len`, so set
3031 // `head` to the beginning of that range.
3032 self.head = WrappedIndex::zero();
3033 }
3034 }
3035 }
3036
3037 unsafe { slice::from_raw_parts_mut(ptr.add(self.head.as_index()), self.len) }
3038 }
3039
3040 /// Rotates the double-ended queue `n` places to the left.
3041 ///
3042 /// Equivalently,
3043 /// - Rotates item `n` into the first position.
3044 /// - Pops the first `n` items and pushes them to the end.
3045 /// - Rotates `len() - n` places to the right.
3046 ///
3047 /// # Panics
3048 ///
3049 /// If `n` is greater than `len()`. Note that `n == len()`
3050 /// does _not_ panic and is a no-op rotation.
3051 ///
3052 /// # Complexity
3053 ///
3054 /// Takes `*O*(min(n, len() - n))` time and no extra space.
3055 ///
3056 /// # Examples
3057 ///
3058 /// ```
3059 /// use std::collections::VecDeque;
3060 ///
3061 /// let mut buf: VecDeque<_> = (0..10).collect();
3062 ///
3063 /// buf.rotate_left(3);
3064 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
3065 ///
3066 /// for i in 1..10 {
3067 /// assert_eq!(i * 3 % 10, buf[0]);
3068 /// buf.rotate_left(3);
3069 /// }
3070 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
3071 /// ```
3072 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
3073 pub fn rotate_left(&mut self, n: usize) {
3074 assert!(n <= self.len());
3075 let k = self.len - n;
3076 if n <= k {
3077 unsafe { self.rotate_left_inner(n) }
3078 } else {
3079 unsafe { self.rotate_right_inner(k) }
3080 }
3081 }
3082
3083 /// Rotates the double-ended queue `n` places to the right.
3084 ///
3085 /// Equivalently,
3086 /// - Rotates the first item into position `n`.
3087 /// - Pops the last `n` items and pushes them to the front.
3088 /// - Rotates `len() - n` places to the left.
3089 ///
3090 /// # Panics
3091 ///
3092 /// If `n` is greater than `len()`. Note that `n == len()`
3093 /// does _not_ panic and is a no-op rotation.
3094 ///
3095 /// # Complexity
3096 ///
3097 /// Takes `*O*(min(n, len() - n))` time and no extra space.
3098 ///
3099 /// # Examples
3100 ///
3101 /// ```
3102 /// use std::collections::VecDeque;
3103 ///
3104 /// let mut buf: VecDeque<_> = (0..10).collect();
3105 ///
3106 /// buf.rotate_right(3);
3107 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
3108 ///
3109 /// for i in 1..10 {
3110 /// assert_eq!(0, buf[i * 3 % 10]);
3111 /// buf.rotate_right(3);
3112 /// }
3113 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
3114 /// ```
3115 #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
3116 pub fn rotate_right(&mut self, n: usize) {
3117 assert!(n <= self.len());
3118 let k = self.len - n;
3119 if n <= k {
3120 unsafe { self.rotate_right_inner(n) }
3121 } else {
3122 unsafe { self.rotate_left_inner(k) }
3123 }
3124 }
3125
3126 // SAFETY: the following two methods require that the rotation amount
3127 // be less than half the length of the deque.
3128 //
3129 // `wrap_copy` requires that `min(x, capacity() - x) + copy_len <= capacity()`,
3130 // but then `min` is never more than half the capacity, regardless of x,
3131 // so it's sound to call here because we're calling with something
3132 // less than half the length, which is never above half the capacity.
3133
3134 unsafe fn rotate_left_inner(&mut self, mid: usize) {
3135 debug_assert!(mid * 2 <= self.len());
3136 unsafe {
3137 self.wrap_copy(self.head, self.to_wrapped_index(self.len), mid);
3138 }
3139 self.head = self.to_wrapped_index(mid);
3140 }
3141
3142 unsafe fn rotate_right_inner(&mut self, k: usize) {
3143 debug_assert!(k * 2 <= self.len());
3144 self.head = self.wrap_sub(self.head, k);
3145 unsafe {
3146 self.wrap_copy(self.to_wrapped_index(self.len), self.head, k);
3147 }
3148 }
3149
3150 /// Binary searches this `VecDeque` for a given element.
3151 /// If the `VecDeque` is not sorted, the returned result is unspecified and
3152 /// meaningless.
3153 ///
3154 /// If the value is found then [`Result::Ok`] is returned, containing the
3155 /// index of the matching element. If there are multiple matches, then any
3156 /// one of the matches could be returned. If the value is not found then
3157 /// [`Result::Err`] is returned, containing the index where a matching
3158 /// element could be inserted while maintaining sorted order.
3159 ///
3160 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
3161 ///
3162 /// [`binary_search_by`]: VecDeque::binary_search_by
3163 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
3164 /// [`partition_point`]: VecDeque::partition_point
3165 ///
3166 /// # Examples
3167 ///
3168 /// Looks up a series of four elements. The first is found, with a
3169 /// uniquely determined position; the second and third are not
3170 /// found; the fourth could match any position in `[1, 4]`.
3171 ///
3172 /// ```
3173 /// use std::collections::VecDeque;
3174 ///
3175 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3176 ///
3177 /// assert_eq!(deque.binary_search(&13), Ok(9));
3178 /// assert_eq!(deque.binary_search(&4), Err(7));
3179 /// assert_eq!(deque.binary_search(&100), Err(13));
3180 /// let r = deque.binary_search(&1);
3181 /// assert!(matches!(r, Ok(1..=4)));
3182 /// ```
3183 ///
3184 /// If you want to insert an item to a sorted deque, while maintaining
3185 /// sort order, consider using [`partition_point`]:
3186 ///
3187 /// ```
3188 /// use std::collections::VecDeque;
3189 ///
3190 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3191 /// let num = 42;
3192 /// let idx = deque.partition_point(|&x| x <= num);
3193 /// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
3194 /// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` may allow `insert`
3195 /// // to shift less elements.
3196 /// deque.insert(idx, num);
3197 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
3198 /// ```
3199 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3200 #[inline]
3201 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
3202 where
3203 T: Ord,
3204 {
3205 self.binary_search_by(|e| e.cmp(x))
3206 }
3207
3208 /// Binary searches this `VecDeque` with a comparator function.
3209 ///
3210 /// The comparator function should return an order code that indicates
3211 /// whether its argument is `Less`, `Equal` or `Greater` the desired
3212 /// target.
3213 /// If the `VecDeque` is not sorted or if the comparator function does not
3214 /// implement an order consistent with the sort order of the underlying
3215 /// `VecDeque`, the returned result is unspecified and meaningless.
3216 ///
3217 /// If the value is found then [`Result::Ok`] is returned, containing the
3218 /// index of the matching element. If there are multiple matches, then any
3219 /// one of the matches could be returned. If the value is not found then
3220 /// [`Result::Err`] is returned, containing the index where a matching
3221 /// element could be inserted while maintaining sorted order.
3222 ///
3223 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
3224 ///
3225 /// [`binary_search`]: VecDeque::binary_search
3226 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
3227 /// [`partition_point`]: VecDeque::partition_point
3228 ///
3229 /// # Examples
3230 ///
3231 /// Looks up a series of four elements. The first is found, with a
3232 /// uniquely determined position; the second and third are not
3233 /// found; the fourth could match any position in `[1, 4]`.
3234 ///
3235 /// ```
3236 /// use std::collections::VecDeque;
3237 ///
3238 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3239 ///
3240 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
3241 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
3242 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
3243 /// let r = deque.binary_search_by(|x| x.cmp(&1));
3244 /// assert!(matches!(r, Ok(1..=4)));
3245 /// ```
3246 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3247 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
3248 where
3249 F: FnMut(&'a T) -> Ordering,
3250 {
3251 let (front, back) = self.as_slices();
3252 let cmp_back = back.first().map(|elem| f(elem));
3253
3254 if let Some(Ordering::Equal) = cmp_back {
3255 Ok(front.len())
3256 } else if let Some(Ordering::Less) = cmp_back {
3257 back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
3258 } else {
3259 front.binary_search_by(f)
3260 }
3261 }
3262
3263 /// Binary searches this `VecDeque` with a key extraction function.
3264 ///
3265 /// Assumes that the deque is sorted by the key, for instance with
3266 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
3267 /// If the deque is not sorted by the key, the returned result is
3268 /// unspecified and meaningless.
3269 ///
3270 /// If the value is found then [`Result::Ok`] is returned, containing the
3271 /// index of the matching element. If there are multiple matches, then any
3272 /// one of the matches could be returned. If the value is not found then
3273 /// [`Result::Err`] is returned, containing the index where a matching
3274 /// element could be inserted while maintaining sorted order.
3275 ///
3276 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
3277 ///
3278 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
3279 /// [`binary_search`]: VecDeque::binary_search
3280 /// [`binary_search_by`]: VecDeque::binary_search_by
3281 /// [`partition_point`]: VecDeque::partition_point
3282 ///
3283 /// # Examples
3284 ///
3285 /// Looks up a series of four elements in a slice of pairs sorted by
3286 /// their second elements. The first is found, with a uniquely
3287 /// determined position; the second and third are not found; the
3288 /// fourth could match any position in `[1, 4]`.
3289 ///
3290 /// ```
3291 /// use std::collections::VecDeque;
3292 ///
3293 /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
3294 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
3295 /// (1, 21), (2, 34), (4, 55)].into();
3296 ///
3297 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
3298 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
3299 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
3300 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
3301 /// assert!(matches!(r, Ok(1..=4)));
3302 /// ```
3303 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3304 #[inline]
3305 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
3306 where
3307 F: FnMut(&'a T) -> B,
3308 B: Ord,
3309 {
3310 self.binary_search_by(|k| f(k).cmp(b))
3311 }
3312
3313 /// Returns the index of the partition point according to the given predicate
3314 /// (the index of the first element of the second partition).
3315 ///
3316 /// The deque is assumed to be partitioned according to the given predicate.
3317 /// This means that all elements for which the predicate returns true are at the start of the deque
3318 /// and all elements for which the predicate returns false are at the end.
3319 /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
3320 /// (all odd numbers are at the start, all even at the end).
3321 ///
3322 /// If the deque is not partitioned, the returned result is unspecified and meaningless,
3323 /// as this method performs a kind of binary search.
3324 ///
3325 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
3326 ///
3327 /// [`binary_search`]: VecDeque::binary_search
3328 /// [`binary_search_by`]: VecDeque::binary_search_by
3329 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
3330 ///
3331 /// # Examples
3332 ///
3333 /// ```
3334 /// use std::collections::VecDeque;
3335 ///
3336 /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
3337 /// let i = deque.partition_point(|&x| x < 5);
3338 ///
3339 /// assert_eq!(i, 4);
3340 /// assert!(deque.iter().take(i).all(|&x| x < 5));
3341 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
3342 /// ```
3343 ///
3344 /// If you want to insert an item to a sorted deque, while maintaining
3345 /// sort order:
3346 ///
3347 /// ```
3348 /// use std::collections::VecDeque;
3349 ///
3350 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
3351 /// let num = 42;
3352 /// let idx = deque.partition_point(|&x| x < num);
3353 /// deque.insert(idx, num);
3354 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
3355 /// ```
3356 #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
3357 pub fn partition_point<P>(&self, mut pred: P) -> usize
3358 where
3359 P: FnMut(&T) -> bool,
3360 {
3361 let (front, back) = self.as_slices();
3362
3363 if let Some(true) = back.first().map(|v| pred(v)) {
3364 back.partition_point(pred) + front.len()
3365 } else {
3366 front.partition_point(pred)
3367 }
3368 }
3369}
3370
3371impl<T: Clone, A: Allocator> VecDeque<T, A> {
3372 /// Modifies the deque in-place so that `len()` is equal to new_len,
3373 /// either by removing excess elements from the back or by appending clones of `value`
3374 /// to the back.
3375 ///
3376 /// # Examples
3377 ///
3378 /// ```
3379 /// use std::collections::VecDeque;
3380 ///
3381 /// let mut buf = VecDeque::new();
3382 /// buf.push_back(5);
3383 /// buf.push_back(10);
3384 /// buf.push_back(15);
3385 /// assert_eq!(buf, [5, 10, 15]);
3386 ///
3387 /// buf.resize(2, 0);
3388 /// assert_eq!(buf, [5, 10]);
3389 ///
3390 /// buf.resize(5, 20);
3391 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
3392 /// ```
3393 #[stable(feature = "deque_extras", since = "1.16.0")]
3394 pub fn resize(&mut self, new_len: usize, value: T) {
3395 if new_len > self.len() {
3396 let extra = new_len - self.len();
3397 self.extend(repeat_n(value, extra))
3398 } else {
3399 self.truncate(new_len);
3400 }
3401 }
3402
3403 /// Clones the elements at the range `src` and appends them to the end.
3404 ///
3405 /// # Panics
3406 ///
3407 /// Panics if the starting index is greater than the end index
3408 /// or if either index is greater than the length of the vector.
3409 ///
3410 /// # Examples
3411 ///
3412 /// ```
3413 /// #![feature(deque_extend_front)]
3414 /// use std::collections::VecDeque;
3415 ///
3416 /// let mut characters = VecDeque::from(['a', 'b', 'c', 'd', 'e']);
3417 /// characters.extend_from_within(2..);
3418 /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
3419 ///
3420 /// let mut numbers = VecDeque::from([0, 1, 2, 3, 4]);
3421 /// numbers.extend_from_within(..2);
3422 /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
3423 ///
3424 /// let mut strings = VecDeque::from([String::from("hello"), String::from("world"), String::from("!")]);
3425 /// strings.extend_from_within(1..=2);
3426 /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
3427 /// ```
3428 #[cfg(not(no_global_oom_handling))]
3429 #[unstable(feature = "deque_extend_front", issue = "146975")]
3430 pub fn extend_from_within<R>(&mut self, src: R)
3431 where
3432 R: RangeBounds<usize>,
3433 {
3434 let range = slice::range(src, ..self.len());
3435 self.reserve(range.len());
3436
3437 // SAFETY:
3438 // - `slice::range` guarantees that the given range is valid for indexing self
3439 // - at least `range.len()` additional space is available
3440 unsafe {
3441 self.spec_extend_from_within(range);
3442 }
3443 }
3444
3445 /// Clones the elements at the range `src` and prepends them to the front.
3446 ///
3447 /// # Panics
3448 ///
3449 /// Panics if the starting index is greater than the end index
3450 /// or if either index is greater than the length of the vector.
3451 ///
3452 /// # Examples
3453 ///
3454 /// ```
3455 /// #![feature(deque_extend_front)]
3456 /// use std::collections::VecDeque;
3457 ///
3458 /// let mut characters = VecDeque::from(['a', 'b', 'c', 'd', 'e']);
3459 /// characters.prepend_from_within(2..);
3460 /// assert_eq!(characters, ['c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']);
3461 ///
3462 /// let mut numbers = VecDeque::from([0, 1, 2, 3, 4]);
3463 /// numbers.prepend_from_within(..2);
3464 /// assert_eq!(numbers, [0, 1, 0, 1, 2, 3, 4]);
3465 ///
3466 /// let mut strings = VecDeque::from([String::from("hello"), String::from("world"), String::from("!")]);
3467 /// strings.prepend_from_within(1..=2);
3468 /// assert_eq!(strings, ["world", "!", "hello", "world", "!"]);
3469 /// ```
3470 #[cfg(not(no_global_oom_handling))]
3471 #[unstable(feature = "deque_extend_front", issue = "146975")]
3472 pub fn prepend_from_within<R>(&mut self, src: R)
3473 where
3474 R: RangeBounds<usize>,
3475 {
3476 let range = slice::range(src, ..self.len());
3477 self.reserve(range.len());
3478
3479 // SAFETY:
3480 // - `slice::range` guarantees that the given range is valid for indexing self
3481 // - at least `range.len()` additional space is available
3482 unsafe {
3483 self.spec_prepend_from_within(range);
3484 }
3485 }
3486}
3487
3488/// Associated functions have the following preconditions:
3489///
3490/// - `src` needs to be a valid range: `src.start <= src.end <= self.len()`.
3491/// - The buffer must have enough spare capacity: `self.capacity() - self.len() >= src.len()`.
3492#[cfg(not(no_global_oom_handling))]
3493trait SpecExtendFromWithin {
3494 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
3495
3496 unsafe fn spec_prepend_from_within(&mut self, src: Range<usize>);
3497}
3498
3499#[cfg(not(no_global_oom_handling))]
3500impl<T: Clone, A: Allocator> SpecExtendFromWithin for VecDeque<T, A> {
3501 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3502 let dst = self.len();
3503 let count = src.end - src.start;
3504 let src = src.start;
3505
3506 unsafe {
3507 // SAFETY:
3508 // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3509 // - Ranges are in bounds: guaranteed by the caller.
3510 let ranges = self.nonoverlapping_ranges(src, dst, count, self.head);
3511
3512 // `len` is updated after every clone to prevent leaking and
3513 // leave the deque in the right state when a clone implementation panics
3514
3515 for (src, dst, count) in ranges {
3516 for offset in 0..count {
3517 dst.add(offset).write((*src.add(offset)).clone());
3518 self.len += 1;
3519 }
3520 }
3521 }
3522 }
3523
3524 default unsafe fn spec_prepend_from_within(&mut self, src: Range<usize>) {
3525 let dst = 0;
3526 let count = src.end - src.start;
3527 let src = src.start + count;
3528
3529 let new_head = self.wrap_sub(self.head, count);
3530 let cap = self.capacity();
3531
3532 unsafe {
3533 // SAFETY:
3534 // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3535 // - Ranges are in bounds: guaranteed by the caller.
3536 let ranges = self.nonoverlapping_ranges(src, dst, count, new_head);
3537
3538 // Cloning is done in reverse because we prepend to the front of the deque,
3539 // we can't get holes in the *logical* buffer.
3540 // `head` and `len` are updated after every clone to prevent leaking and
3541 // leave the deque in the right state when a clone implementation panics
3542
3543 // Clone the first range
3544 let (src, dst, count) = ranges[1];
3545 for offset in (0..count).rev() {
3546 dst.add(offset).write((*src.add(offset)).clone());
3547 self.head = self.head.sub(1);
3548 self.len += 1;
3549 }
3550
3551 // Clone the second range
3552 let (src, dst, count) = ranges[0];
3553 let mut iter = (0..count).rev();
3554 if let Some(offset) = iter.next() {
3555 dst.add(offset).write((*src.add(offset)).clone());
3556 // After the first clone of the second range, wrap `head` around
3557 if self.head.is_zero() {
3558 // SAFETY: the wrapped index may be temporarily equal to the capacity even if it
3559 // is not zero, because we subtract it one line below.
3560 self.head = WrappedIndex::from_arbitrary_number(cap);
3561 }
3562 self.head = self.head.sub(1);
3563 self.len += 1;
3564
3565 // Continue like normal
3566 for offset in iter {
3567 dst.add(offset).write((*src.add(offset)).clone());
3568 self.head = self.head.sub(1);
3569 self.len += 1;
3570 }
3571 }
3572 }
3573 }
3574}
3575
3576#[cfg(not(no_global_oom_handling))]
3577impl<T: TrivialClone, A: Allocator> SpecExtendFromWithin for VecDeque<T, A> {
3578 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3579 let dst = self.len();
3580 let count = src.end - src.start;
3581 let src = src.start;
3582
3583 unsafe {
3584 // SAFETY:
3585 // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3586 // - Ranges are in bounds: guaranteed by the caller.
3587 let ranges = self.nonoverlapping_ranges(src, dst, count, self.head);
3588 for (src, dst, count) in ranges {
3589 ptr::copy_nonoverlapping(src, dst, count);
3590 }
3591 }
3592
3593 // SAFETY:
3594 // - The elements were just initialized by `copy_nonoverlapping`
3595 self.len += count;
3596 }
3597
3598 unsafe fn spec_prepend_from_within(&mut self, src: Range<usize>) {
3599 let dst = 0;
3600 let count = src.end - src.start;
3601 let src = src.start + count;
3602
3603 let new_head = self.wrap_sub(self.head, count);
3604
3605 unsafe {
3606 // SAFETY:
3607 // - Ranges do not overlap: src entirely spans initialized values, dst entirely spans uninitialized values.
3608 // - Ranges are in bounds: guaranteed by the caller.
3609 let ranges = self.nonoverlapping_ranges(src, dst, count, new_head);
3610 for (src, dst, count) in ranges {
3611 ptr::copy_nonoverlapping(src, dst, count);
3612 }
3613 }
3614
3615 // SAFETY:
3616 // - The elements were just initialized by `copy_nonoverlapping`
3617 self.head = new_head;
3618 self.len += count;
3619 }
3620}
3621
3622use index::{WrappedIndex, wrap_index};
3623
3624// The code is separated into a module to make it harder to construct a BufferIndex without
3625// going through wrapping.
3626mod index {
3627 use core::cmp::Ordering;
3628
3629 /// Returns the index in the underlying buffer for a given logical element index.
3630 #[inline]
3631 pub(super) fn wrap_index(logical_index: usize, capacity: usize) -> WrappedIndex {
3632 debug_assert!(
3633 (logical_index == 0 && capacity == 0)
3634 || logical_index < capacity
3635 || (logical_index - capacity) < capacity
3636 );
3637 if logical_index >= capacity {
3638 WrappedIndex(logical_index - capacity)
3639 } else {
3640 WrappedIndex(logical_index)
3641 }
3642 }
3643
3644 /// Represents an index that can be safely used to index the VecDeque buffer.
3645 /// It exists as a separate type to avoid passing logical (unwrapped) indices to various
3646 /// VecDeque functions by accident.
3647 ///
3648 /// The invariant of this index is that it is always < VecDeque capacity, unless the VecDeque
3649 /// is empty (in that case the index can be 0 when the capacity is 0).
3650 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
3651 #[repr(transparent)]
3652 pub(super) struct WrappedIndex(usize);
3653
3654 impl WrappedIndex {
3655 /// The newly constructed index has to be in-bounds for the VecDeque
3656 /// that uses the index.
3657 #[inline(always)]
3658 pub(super) fn from_arbitrary_number(index: usize) -> Self {
3659 Self(index)
3660 }
3661
3662 /// Safety invariant: the newly constructed index must still be in-bounds for the VecDeque
3663 #[inline(always)]
3664 pub(super) unsafe fn add(self, offset: usize) -> Self {
3665 Self(self.0 + offset)
3666 }
3667
3668 /// Safety invariant: the newly constructed index must still be in-bounds for the VecDeque
3669 #[inline(always)]
3670 pub(super) unsafe fn sub(self, offset: usize) -> Self {
3671 debug_assert!(self.0 >= offset);
3672 Self(self.0 - offset)
3673 }
3674
3675 #[inline(always)]
3676 pub(super) const fn zero() -> Self {
3677 Self(0)
3678 }
3679
3680 #[inline(always)]
3681 pub(super) fn abs_diff(self, other: Self) -> usize {
3682 self.0.abs_diff(other.0)
3683 }
3684
3685 #[inline(always)]
3686 pub(super) fn as_index(self) -> usize {
3687 self.0
3688 }
3689
3690 #[inline(always)]
3691 pub(super) fn is_zero(self) -> bool {
3692 self.0 == 0
3693 }
3694 }
3695
3696 impl core::ops::Add<usize> for WrappedIndex {
3697 // The output might not be wrapped anymore
3698 type Output = usize;
3699
3700 #[inline(always)]
3701 fn add(self, rhs: usize) -> Self::Output {
3702 self.0 + rhs
3703 }
3704 }
3705
3706 impl core::fmt::Display for WrappedIndex {
3707 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3708 self.0.fmt(f)
3709 }
3710 }
3711
3712 impl core::cmp::PartialEq<usize> for WrappedIndex {
3713 #[inline(always)]
3714 fn eq(&self, other: &usize) -> bool {
3715 self.0.eq(other)
3716 }
3717 }
3718
3719 impl core::cmp::PartialOrd<usize> for WrappedIndex {
3720 #[inline(always)]
3721 fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
3722 self.0.partial_cmp(other)
3723 }
3724 }
3725}
3726
3727#[stable(feature = "rust1", since = "1.0.0")]
3728impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
3729 fn eq(&self, other: &Self) -> bool {
3730 if self.len != other.len() {
3731 return false;
3732 }
3733 let (sa, sb) = self.as_slices();
3734 let (oa, ob) = other.as_slices();
3735 if sa.len() == oa.len() {
3736 sa == oa && sb == ob
3737 } else if sa.len() < oa.len() {
3738 // Always divisible in three sections, for example:
3739 // self: [a b c|d e f]
3740 // other: [0 1 2 3|4 5]
3741 // front = 3, mid = 1,
3742 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
3743 let front = sa.len();
3744 let mid = oa.len() - front;
3745
3746 let (oa_front, oa_mid) = oa.split_at(front);
3747 let (sb_mid, sb_back) = sb.split_at(mid);
3748 debug_assert_eq!(sa.len(), oa_front.len());
3749 debug_assert_eq!(sb_mid.len(), oa_mid.len());
3750 debug_assert_eq!(sb_back.len(), ob.len());
3751 sa == oa_front && sb_mid == oa_mid && sb_back == ob
3752 } else {
3753 let front = oa.len();
3754 let mid = sa.len() - front;
3755
3756 let (sa_front, sa_mid) = sa.split_at(front);
3757 let (ob_mid, ob_back) = ob.split_at(mid);
3758 debug_assert_eq!(sa_front.len(), oa.len());
3759 debug_assert_eq!(sa_mid.len(), ob_mid.len());
3760 debug_assert_eq!(sb.len(), ob_back.len());
3761 sa_front == oa && sa_mid == ob_mid && sb == ob_back
3762 }
3763 }
3764}
3765
3766#[stable(feature = "rust1", since = "1.0.0")]
3767impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
3768
3769__impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
3770__impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
3771__impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
3772__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
3773__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
3774__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
3775
3776#[stable(feature = "rust1", since = "1.0.0")]
3777impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
3778 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3779 self.iter().partial_cmp(other.iter())
3780 }
3781}
3782
3783#[stable(feature = "rust1", since = "1.0.0")]
3784impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
3785 #[inline]
3786 fn cmp(&self, other: &Self) -> Ordering {
3787 self.iter().cmp(other.iter())
3788 }
3789}
3790
3791#[stable(feature = "rust1", since = "1.0.0")]
3792impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
3793 fn hash<H: Hasher>(&self, state: &mut H) {
3794 state.write_length_prefix(self.len);
3795 // It's not possible to use Hash::hash_slice on slices
3796 // returned by as_slices method as their length can vary
3797 // in otherwise identical deques.
3798 //
3799 // Hasher only guarantees equivalence for the exact same
3800 // set of calls to its methods.
3801 self.iter().for_each(|elem| elem.hash(state));
3802 }
3803}
3804
3805#[stable(feature = "rust1", since = "1.0.0")]
3806impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
3807 type Output = T;
3808
3809 #[inline]
3810 fn index(&self, index: usize) -> &T {
3811 self.get(index).expect("Out of bounds access")
3812 }
3813}
3814
3815#[stable(feature = "rust1", since = "1.0.0")]
3816impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
3817 #[inline]
3818 fn index_mut(&mut self, index: usize) -> &mut T {
3819 self.get_mut(index).expect("Out of bounds access")
3820 }
3821}
3822
3823#[stable(feature = "rust1", since = "1.0.0")]
3824impl<T> FromIterator<T> for VecDeque<T> {
3825 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
3826 SpecFromIter::spec_from_iter(iter.into_iter())
3827 }
3828}
3829
3830#[stable(feature = "rust1", since = "1.0.0")]
3831impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
3832 type Item = T;
3833 type IntoIter = IntoIter<T, A>;
3834
3835 /// Consumes the deque into a front-to-back iterator yielding elements by
3836 /// value.
3837 fn into_iter(self) -> IntoIter<T, A> {
3838 IntoIter::new(self)
3839 }
3840}
3841
3842#[stable(feature = "rust1", since = "1.0.0")]
3843impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
3844 type Item = &'a T;
3845 type IntoIter = Iter<'a, T>;
3846
3847 fn into_iter(self) -> Iter<'a, T> {
3848 self.iter()
3849 }
3850}
3851
3852#[stable(feature = "rust1", since = "1.0.0")]
3853impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
3854 type Item = &'a mut T;
3855 type IntoIter = IterMut<'a, T>;
3856
3857 fn into_iter(self) -> IterMut<'a, T> {
3858 self.iter_mut()
3859 }
3860}
3861
3862#[stable(feature = "rust1", since = "1.0.0")]
3863impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
3864 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
3865 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter());
3866 }
3867
3868 #[inline]
3869 fn extend_one(&mut self, elem: T) {
3870 self.push_back(elem);
3871 }
3872
3873 #[inline]
3874 fn extend_reserve(&mut self, additional: usize) {
3875 self.reserve(additional);
3876 }
3877
3878 #[inline]
3879 unsafe fn extend_one_unchecked(&mut self, item: T) {
3880 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3881 unsafe {
3882 self.push_unchecked(item);
3883 }
3884 }
3885}
3886
3887#[stable(feature = "extend_ref", since = "1.2.0")]
3888impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
3889 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3890 self.spec_extend(iter.into_iter());
3891 }
3892
3893 #[inline]
3894 fn extend_one(&mut self, &elem: &'a T) {
3895 self.push_back(elem);
3896 }
3897
3898 #[inline]
3899 fn extend_reserve(&mut self, additional: usize) {
3900 self.reserve(additional);
3901 }
3902
3903 #[inline]
3904 unsafe fn extend_one_unchecked(&mut self, &item: &'a T) {
3905 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3906 unsafe {
3907 self.push_unchecked(item);
3908 }
3909 }
3910}
3911
3912#[stable(feature = "rust1", since = "1.0.0")]
3913impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
3914 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3915 f.debug_list().entries(self.iter()).finish()
3916 }
3917}
3918
3919#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3920impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
3921 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3922 ///
3923 /// [`Vec<T>`]: crate::vec::Vec
3924 /// [`VecDeque<T>`]: crate::collections::VecDeque
3925 ///
3926 /// This conversion is guaranteed to run in *O*(1) time
3927 /// and to not re-allocate the `Vec`'s buffer or allocate
3928 /// any additional memory.
3929 #[inline]
3930 fn from(other: Vec<T, A>) -> Self {
3931 let (ptr, len, cap, alloc) = other.into_raw_parts_with_alloc();
3932 Self {
3933 head: WrappedIndex::zero(),
3934 len,
3935 buf: unsafe { RawVec::from_raw_parts_in(ptr, cap, alloc) },
3936 }
3937 }
3938}
3939
3940#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3941impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
3942 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
3943 ///
3944 /// [`Vec<T>`]: crate::vec::Vec
3945 /// [`VecDeque<T>`]: crate::collections::VecDeque
3946 ///
3947 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
3948 /// the circular buffer doesn't happen to be at the beginning of the allocation.
3949 ///
3950 /// # Examples
3951 ///
3952 /// ```
3953 /// use std::collections::VecDeque;
3954 ///
3955 /// // This one is *O*(1).
3956 /// let deque: VecDeque<_> = (1..5).collect();
3957 /// let ptr = deque.as_slices().0.as_ptr();
3958 /// let vec = Vec::from(deque);
3959 /// assert_eq!(vec, [1, 2, 3, 4]);
3960 /// assert_eq!(vec.as_ptr(), ptr);
3961 ///
3962 /// // This one needs data rearranging.
3963 /// let mut deque: VecDeque<_> = (1..5).collect();
3964 /// deque.push_front(9);
3965 /// deque.push_front(8);
3966 /// let ptr = deque.as_slices().1.as_ptr();
3967 /// let vec = Vec::from(deque);
3968 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
3969 /// assert_eq!(vec.as_ptr(), ptr);
3970 /// ```
3971 fn from(mut other: VecDeque<T, A>) -> Self {
3972 other.make_contiguous();
3973
3974 unsafe {
3975 let other = ManuallyDrop::new(other);
3976 let buf = other.buf.ptr();
3977 let len = other.len();
3978 let cap = other.capacity();
3979 let alloc = ptr::read(other.allocator());
3980
3981 if !other.head.is_zero() {
3982 ptr::copy(buf.add(other.head.as_index()), buf, len);
3983 }
3984 Vec::from_raw_parts_in(buf, len, cap, alloc)
3985 }
3986 }
3987}
3988
3989#[stable(feature = "std_collections_from_array", since = "1.56.0")]
3990impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
3991 /// Converts a `[T; N]` into a `VecDeque<T>`.
3992 ///
3993 /// ```
3994 /// use std::collections::VecDeque;
3995 ///
3996 /// let deq1 = VecDeque::from([1, 2, 3, 4]);
3997 /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
3998 /// assert_eq!(deq1, deq2);
3999 /// ```
4000 fn from(arr: [T; N]) -> Self {
4001 let mut deq = VecDeque::with_capacity(N);
4002 let arr = ManuallyDrop::new(arr);
4003 if !<T>::IS_ZST {
4004 // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
4005 unsafe {
4006 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);
4007 }
4008 }
4009 deq.head = WrappedIndex::zero();
4010 deq.len = N;
4011 deq
4012 }
4013}