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