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