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