]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/vec_deque/mod.rs
Rollup merge of #95949 - SoniEx2:patch-5, r=m-ou-se
[rust.git] / library / alloc / src / 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 use core::cmp::{self, Ordering};
11 use core::fmt;
12 use core::hash::{Hash, Hasher};
13 use core::iter::{repeat_with, FromIterator};
14 use core::marker::PhantomData;
15 use core::mem::{self, ManuallyDrop, MaybeUninit};
16 use core::ops::{Index, IndexMut, Range, RangeBounds};
17 use core::ptr::{self, NonNull};
18 use core::slice;
19
20 use crate::alloc::{Allocator, Global};
21 use crate::collections::TryReserveError;
22 use crate::collections::TryReserveErrorKind;
23 use crate::raw_vec::RawVec;
24 use crate::vec::Vec;
25
26 #[macro_use]
27 mod macros;
28
29 #[stable(feature = "drain", since = "1.6.0")]
30 pub use self::drain::Drain;
31
32 mod drain;
33
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use self::iter_mut::IterMut;
36
37 mod iter_mut;
38
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub use self::into_iter::IntoIter;
41
42 mod into_iter;
43
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub use self::iter::Iter;
46
47 mod iter;
48
49 use self::pair_slices::PairSlices;
50
51 mod pair_slices;
52
53 use self::ring_slices::RingSlices;
54
55 mod ring_slices;
56
57 #[cfg(test)]
58 mod tests;
59
60 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
61 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
62
63 const MAXIMUM_ZST_CAPACITY: usize = 1 << (usize::BITS - 1); // Largest possible power of two
64
65 /// A double-ended queue implemented with a growable ring buffer.
66 ///
67 /// The "default" usage of this type as a queue is to use [`push_back`] to add to
68 /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`]
69 /// push onto the back in this manner, and iterating over `VecDeque` goes front
70 /// to back.
71 ///
72 /// A `VecDeque` with a known list of items can be initialized from an array:
73 ///
74 /// ```
75 /// use std::collections::VecDeque;
76 ///
77 /// let deq = VecDeque::from([-1, 0, 1]);
78 /// ```
79 ///
80 /// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
81 /// in memory. If you want to access the elements as a single slice, such as for
82 /// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
83 /// so that its elements do not wrap, and returns a mutable slice to the
84 /// now-contiguous element sequence.
85 ///
86 /// [`push_back`]: VecDeque::push_back
87 /// [`pop_front`]: VecDeque::pop_front
88 /// [`extend`]: VecDeque::extend
89 /// [`append`]: VecDeque::append
90 /// [`make_contiguous`]: VecDeque::make_contiguous
91 #[cfg_attr(not(test), rustc_diagnostic_item = "VecDeque")]
92 #[stable(feature = "rust1", since = "1.0.0")]
93 #[rustc_insignificant_dtor]
94 pub struct VecDeque<
95     T,
96     #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
97 > {
98     // tail and head are pointers into the buffer. Tail always points
99     // to the first element that could be read, Head always points
100     // to where data should be written.
101     // If tail == head the buffer is empty. The length of the ringbuffer
102     // is defined as the distance between the two.
103     tail: usize,
104     head: usize,
105     buf: RawVec<T, A>,
106 }
107
108 #[stable(feature = "rust1", since = "1.0.0")]
109 impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A> {
110     fn clone(&self) -> Self {
111         let mut deq = Self::with_capacity_in(self.len(), self.allocator().clone());
112         deq.extend(self.iter().cloned());
113         deq
114     }
115
116     fn clone_from(&mut self, other: &Self) {
117         self.truncate(other.len());
118
119         let mut iter = PairSlices::from(self, other);
120         while let Some((dst, src)) = iter.next() {
121             dst.clone_from_slice(&src);
122         }
123
124         if iter.has_remainder() {
125             for remainder in iter.remainder() {
126                 self.extend(remainder.iter().cloned());
127             }
128         }
129     }
130 }
131
132 #[stable(feature = "rust1", since = "1.0.0")]
133 unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
134     fn drop(&mut self) {
135         /// Runs the destructor for all items in the slice when it gets dropped (normally or
136         /// during unwinding).
137         struct Dropper<'a, T>(&'a mut [T]);
138
139         impl<'a, T> Drop for Dropper<'a, T> {
140             fn drop(&mut self) {
141                 unsafe {
142                     ptr::drop_in_place(self.0);
143                 }
144             }
145         }
146
147         let (front, back) = self.as_mut_slices();
148         unsafe {
149             let _back_dropper = Dropper(back);
150             // use drop for [T]
151             ptr::drop_in_place(front);
152         }
153         // RawVec handles deallocation
154     }
155 }
156
157 #[stable(feature = "rust1", since = "1.0.0")]
158 impl<T> Default for VecDeque<T> {
159     /// Creates an empty deque.
160     #[inline]
161     fn default() -> VecDeque<T> {
162         VecDeque::new()
163     }
164 }
165
166 impl<T, A: Allocator> VecDeque<T, A> {
167     /// Marginally more convenient
168     #[inline]
169     fn ptr(&self) -> *mut T {
170         self.buf.ptr()
171     }
172
173     /// Marginally more convenient
174     #[inline]
175     fn cap(&self) -> usize {
176         if mem::size_of::<T>() == 0 {
177             // For zero sized types, we are always at maximum capacity
178             MAXIMUM_ZST_CAPACITY
179         } else {
180             self.buf.capacity()
181         }
182     }
183
184     /// Turn ptr into a slice, since the elements of the backing buffer may be uninitialized,
185     /// we will return a slice of [`MaybeUninit<T>`].
186     ///
187     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
188     /// incorrect usage of this method.
189     ///
190     /// [zeroed]: mem::MaybeUninit::zeroed
191     #[inline]
192     unsafe fn buffer_as_slice(&self) -> &[MaybeUninit<T>] {
193         unsafe { slice::from_raw_parts(self.ptr() as *mut MaybeUninit<T>, self.cap()) }
194     }
195
196     /// Turn ptr into a mut slice, since the elements of the backing buffer may be uninitialized,
197     /// we will return a slice of [`MaybeUninit<T>`].
198     ///
199     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
200     /// incorrect usage of this method.
201     ///
202     /// [zeroed]: mem::MaybeUninit::zeroed
203     #[inline]
204     unsafe fn buffer_as_mut_slice(&mut self) -> &mut [MaybeUninit<T>] {
205         unsafe { slice::from_raw_parts_mut(self.ptr() as *mut MaybeUninit<T>, self.cap()) }
206     }
207
208     /// Moves an element out of the buffer
209     #[inline]
210     unsafe fn buffer_read(&mut self, off: usize) -> T {
211         unsafe { ptr::read(self.ptr().add(off)) }
212     }
213
214     /// Writes an element into the buffer, moving it.
215     #[inline]
216     unsafe fn buffer_write(&mut self, off: usize, value: T) {
217         unsafe {
218             ptr::write(self.ptr().add(off), value);
219         }
220     }
221
222     /// Returns `true` if the buffer is at full capacity.
223     #[inline]
224     fn is_full(&self) -> bool {
225         self.cap() - self.len() == 1
226     }
227
228     /// Returns the index in the underlying buffer for a given logical element
229     /// index.
230     #[inline]
231     fn wrap_index(&self, idx: usize) -> usize {
232         wrap_index(idx, self.cap())
233     }
234
235     /// Returns the index in the underlying buffer for a given logical element
236     /// index + addend.
237     #[inline]
238     fn wrap_add(&self, idx: usize, addend: usize) -> usize {
239         wrap_index(idx.wrapping_add(addend), self.cap())
240     }
241
242     /// Returns the index in the underlying buffer for a given logical element
243     /// index - subtrahend.
244     #[inline]
245     fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
246         wrap_index(idx.wrapping_sub(subtrahend), self.cap())
247     }
248
249     /// Copies a contiguous block of memory len long from src to dst
250     #[inline]
251     unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
252         debug_assert!(
253             dst + len <= self.cap(),
254             "cpy dst={} src={} len={} cap={}",
255             dst,
256             src,
257             len,
258             self.cap()
259         );
260         debug_assert!(
261             src + len <= self.cap(),
262             "cpy dst={} src={} len={} cap={}",
263             dst,
264             src,
265             len,
266             self.cap()
267         );
268         unsafe {
269             ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
270         }
271     }
272
273     /// Copies a contiguous block of memory len long from src to dst
274     #[inline]
275     unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
276         debug_assert!(
277             dst + len <= self.cap(),
278             "cno dst={} src={} len={} cap={}",
279             dst,
280             src,
281             len,
282             self.cap()
283         );
284         debug_assert!(
285             src + len <= self.cap(),
286             "cno dst={} src={} len={} cap={}",
287             dst,
288             src,
289             len,
290             self.cap()
291         );
292         unsafe {
293             ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
294         }
295     }
296
297     /// Copies a potentially wrapping block of memory len long from src to dest.
298     /// (abs(dst - src) + len) must be no larger than cap() (There must be at
299     /// most one continuous overlapping region between src and dest).
300     unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
301         #[allow(dead_code)]
302         fn diff(a: usize, b: usize) -> usize {
303             if a <= b { b - a } else { a - b }
304         }
305         debug_assert!(
306             cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
307             "wrc dst={} src={} len={} cap={}",
308             dst,
309             src,
310             len,
311             self.cap()
312         );
313
314         if src == dst || len == 0 {
315             return;
316         }
317
318         let dst_after_src = self.wrap_sub(dst, src) < len;
319
320         let src_pre_wrap_len = self.cap() - src;
321         let dst_pre_wrap_len = self.cap() - dst;
322         let src_wraps = src_pre_wrap_len < len;
323         let dst_wraps = dst_pre_wrap_len < len;
324
325         match (dst_after_src, src_wraps, dst_wraps) {
326             (_, false, false) => {
327                 // src doesn't wrap, dst doesn't wrap
328                 //
329                 //        S . . .
330                 // 1 [_ _ A A B B C C _]
331                 // 2 [_ _ A A A A B B _]
332                 //            D . . .
333                 //
334                 unsafe {
335                     self.copy(dst, src, len);
336                 }
337             }
338             (false, false, true) => {
339                 // dst before src, src doesn't wrap, dst wraps
340                 //
341                 //    S . . .
342                 // 1 [A A B B _ _ _ C C]
343                 // 2 [A A B B _ _ _ A A]
344                 // 3 [B B B B _ _ _ A A]
345                 //    . .           D .
346                 //
347                 unsafe {
348                     self.copy(dst, src, dst_pre_wrap_len);
349                     self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
350                 }
351             }
352             (true, false, true) => {
353                 // src before dst, src doesn't wrap, dst wraps
354                 //
355                 //              S . . .
356                 // 1 [C C _ _ _ A A B B]
357                 // 2 [B B _ _ _ A A B B]
358                 // 3 [B B _ _ _ A A A A]
359                 //    . .           D .
360                 //
361                 unsafe {
362                     self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
363                     self.copy(dst, src, dst_pre_wrap_len);
364                 }
365             }
366             (false, true, false) => {
367                 // dst before src, src wraps, dst doesn't wrap
368                 //
369                 //    . .           S .
370                 // 1 [C C _ _ _ A A B B]
371                 // 2 [C C _ _ _ B B B B]
372                 // 3 [C C _ _ _ B B C C]
373                 //              D . . .
374                 //
375                 unsafe {
376                     self.copy(dst, src, src_pre_wrap_len);
377                     self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
378                 }
379             }
380             (true, true, false) => {
381                 // src before dst, src wraps, dst doesn't wrap
382                 //
383                 //    . .           S .
384                 // 1 [A A B B _ _ _ C C]
385                 // 2 [A A A A _ _ _ C C]
386                 // 3 [C C A A _ _ _ C C]
387                 //    D . . .
388                 //
389                 unsafe {
390                     self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
391                     self.copy(dst, src, src_pre_wrap_len);
392                 }
393             }
394             (false, true, true) => {
395                 // dst before src, src wraps, dst wraps
396                 //
397                 //    . . .         S .
398                 // 1 [A B C D _ E F G H]
399                 // 2 [A B C D _ E G H H]
400                 // 3 [A B C D _ E G H A]
401                 // 4 [B C C D _ E G H A]
402                 //    . .         D . .
403                 //
404                 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
405                 let delta = dst_pre_wrap_len - src_pre_wrap_len;
406                 unsafe {
407                     self.copy(dst, src, src_pre_wrap_len);
408                     self.copy(dst + src_pre_wrap_len, 0, delta);
409                     self.copy(0, delta, len - dst_pre_wrap_len);
410                 }
411             }
412             (true, true, true) => {
413                 // src before dst, src wraps, dst wraps
414                 //
415                 //    . .         S . .
416                 // 1 [A B C D _ E F G H]
417                 // 2 [A A B D _ E F G H]
418                 // 3 [H A B D _ E F G H]
419                 // 4 [H A B D _ E F F G]
420                 //    . . .         D .
421                 //
422                 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
423                 let delta = src_pre_wrap_len - dst_pre_wrap_len;
424                 unsafe {
425                     self.copy(delta, 0, len - src_pre_wrap_len);
426                     self.copy(0, self.cap() - delta, delta);
427                     self.copy(dst, src, dst_pre_wrap_len);
428                 }
429             }
430         }
431     }
432
433     /// Copies all values from `src` to `dst`, wrapping around if needed.
434     /// Assumes capacity is sufficient.
435     #[inline]
436     unsafe fn copy_slice(&mut self, dst: usize, src: &[T]) {
437         debug_assert!(src.len() <= self.cap());
438         let head_room = self.cap() - dst;
439         if src.len() <= head_room {
440             unsafe {
441                 ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst), src.len());
442             }
443         } else {
444             let (left, right) = src.split_at(head_room);
445             unsafe {
446                 ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst), left.len());
447                 ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
448             }
449         }
450     }
451
452     /// Frobs the head and tail sections around to handle the fact that we
453     /// just reallocated. Unsafe because it trusts old_capacity.
454     #[inline]
455     unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
456         let new_capacity = self.cap();
457
458         // Move the shortest contiguous section of the ring buffer
459         //    T             H
460         //   [o o o o o o o . ]
461         //    T             H
462         // A [o o o o o o o . . . . . . . . . ]
463         //        H T
464         //   [o o . o o o o o ]
465         //          T             H
466         // B [. . . o o o o o o o . . . . . . ]
467         //              H T
468         //   [o o o o o . o o ]
469         //              H                 T
470         // C [o o o o o . . . . . . . . . o o ]
471
472         if self.tail <= self.head {
473             // A
474             // Nop
475         } else if self.head < old_capacity - self.tail {
476             // B
477             unsafe {
478                 self.copy_nonoverlapping(old_capacity, 0, self.head);
479             }
480             self.head += old_capacity;
481             debug_assert!(self.head > self.tail);
482         } else {
483             // C
484             let new_tail = new_capacity - (old_capacity - self.tail);
485             unsafe {
486                 self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
487             }
488             self.tail = new_tail;
489             debug_assert!(self.head < self.tail);
490         }
491         debug_assert!(self.head < self.cap());
492         debug_assert!(self.tail < self.cap());
493         debug_assert!(self.cap().count_ones() == 1);
494     }
495 }
496
497 impl<T> VecDeque<T> {
498     /// Creates an empty deque.
499     ///
500     /// # Examples
501     ///
502     /// ```
503     /// use std::collections::VecDeque;
504     ///
505     /// let deque: VecDeque<u32> = VecDeque::new();
506     /// ```
507     #[inline]
508     #[stable(feature = "rust1", since = "1.0.0")]
509     #[must_use]
510     pub fn new() -> VecDeque<T> {
511         VecDeque::new_in(Global)
512     }
513
514     /// Creates an empty deque with space for at least `capacity` elements.
515     ///
516     /// # Examples
517     ///
518     /// ```
519     /// use std::collections::VecDeque;
520     ///
521     /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
522     /// ```
523     #[inline]
524     #[stable(feature = "rust1", since = "1.0.0")]
525     #[must_use]
526     pub fn with_capacity(capacity: usize) -> VecDeque<T> {
527         Self::with_capacity_in(capacity, Global)
528     }
529 }
530
531 impl<T, A: Allocator> VecDeque<T, A> {
532     /// Creates an empty deque.
533     ///
534     /// # Examples
535     ///
536     /// ```
537     /// use std::collections::VecDeque;
538     ///
539     /// let deque: VecDeque<u32> = VecDeque::new();
540     /// ```
541     #[inline]
542     #[unstable(feature = "allocator_api", issue = "32838")]
543     pub fn new_in(alloc: A) -> VecDeque<T, A> {
544         VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc)
545     }
546
547     /// Creates an empty deque with space for at least `capacity` elements.
548     ///
549     /// # Examples
550     ///
551     /// ```
552     /// use std::collections::VecDeque;
553     ///
554     /// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
555     /// ```
556     #[unstable(feature = "allocator_api", issue = "32838")]
557     pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
558         assert!(capacity < 1_usize << usize::BITS - 1, "capacity overflow");
559         // +1 since the ringbuffer always leaves one space empty
560         let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
561
562         VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) }
563     }
564
565     /// Provides a reference to the element at the given index.
566     ///
567     /// Element at index 0 is the front of the queue.
568     ///
569     /// # Examples
570     ///
571     /// ```
572     /// use std::collections::VecDeque;
573     ///
574     /// let mut buf = VecDeque::new();
575     /// buf.push_back(3);
576     /// buf.push_back(4);
577     /// buf.push_back(5);
578     /// assert_eq!(buf.get(1), Some(&4));
579     /// ```
580     #[stable(feature = "rust1", since = "1.0.0")]
581     pub fn get(&self, index: usize) -> Option<&T> {
582         if index < self.len() {
583             let idx = self.wrap_add(self.tail, index);
584             unsafe { Some(&*self.ptr().add(idx)) }
585         } else {
586             None
587         }
588     }
589
590     /// Provides a mutable reference to the element at the given index.
591     ///
592     /// Element at index 0 is the front of the queue.
593     ///
594     /// # Examples
595     ///
596     /// ```
597     /// use std::collections::VecDeque;
598     ///
599     /// let mut buf = VecDeque::new();
600     /// buf.push_back(3);
601     /// buf.push_back(4);
602     /// buf.push_back(5);
603     /// if let Some(elem) = buf.get_mut(1) {
604     ///     *elem = 7;
605     /// }
606     ///
607     /// assert_eq!(buf[1], 7);
608     /// ```
609     #[stable(feature = "rust1", since = "1.0.0")]
610     pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
611         if index < self.len() {
612             let idx = self.wrap_add(self.tail, index);
613             unsafe { Some(&mut *self.ptr().add(idx)) }
614         } else {
615             None
616         }
617     }
618
619     /// Swaps elements at indices `i` and `j`.
620     ///
621     /// `i` and `j` may be equal.
622     ///
623     /// Element at index 0 is the front of the queue.
624     ///
625     /// # Panics
626     ///
627     /// Panics if either index is out of bounds.
628     ///
629     /// # Examples
630     ///
631     /// ```
632     /// use std::collections::VecDeque;
633     ///
634     /// let mut buf = VecDeque::new();
635     /// buf.push_back(3);
636     /// buf.push_back(4);
637     /// buf.push_back(5);
638     /// assert_eq!(buf, [3, 4, 5]);
639     /// buf.swap(0, 2);
640     /// assert_eq!(buf, [5, 4, 3]);
641     /// ```
642     #[stable(feature = "rust1", since = "1.0.0")]
643     pub fn swap(&mut self, i: usize, j: usize) {
644         assert!(i < self.len());
645         assert!(j < self.len());
646         let ri = self.wrap_add(self.tail, i);
647         let rj = self.wrap_add(self.tail, j);
648         unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
649     }
650
651     /// Returns the number of elements the deque can hold without
652     /// reallocating.
653     ///
654     /// # Examples
655     ///
656     /// ```
657     /// use std::collections::VecDeque;
658     ///
659     /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
660     /// assert!(buf.capacity() >= 10);
661     /// ```
662     #[inline]
663     #[stable(feature = "rust1", since = "1.0.0")]
664     pub fn capacity(&self) -> usize {
665         self.cap() - 1
666     }
667
668     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
669     /// given deque. Does nothing if the capacity is already sufficient.
670     ///
671     /// Note that the allocator may give the collection more space than it requests. Therefore
672     /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
673     /// insertions are expected.
674     ///
675     /// # Panics
676     ///
677     /// Panics if the new capacity overflows `usize`.
678     ///
679     /// # Examples
680     ///
681     /// ```
682     /// use std::collections::VecDeque;
683     ///
684     /// let mut buf: VecDeque<i32> = [1].into();
685     /// buf.reserve_exact(10);
686     /// assert!(buf.capacity() >= 11);
687     /// ```
688     ///
689     /// [`reserve`]: VecDeque::reserve
690     #[stable(feature = "rust1", since = "1.0.0")]
691     pub fn reserve_exact(&mut self, additional: usize) {
692         self.reserve(additional);
693     }
694
695     /// Reserves capacity for at least `additional` more elements to be inserted in the given
696     /// deque. The collection may reserve more space to avoid frequent reallocations.
697     ///
698     /// # Panics
699     ///
700     /// Panics if the new capacity overflows `usize`.
701     ///
702     /// # Examples
703     ///
704     /// ```
705     /// use std::collections::VecDeque;
706     ///
707     /// let mut buf: VecDeque<i32> = [1].into();
708     /// buf.reserve(10);
709     /// assert!(buf.capacity() >= 11);
710     /// ```
711     #[stable(feature = "rust1", since = "1.0.0")]
712     pub fn reserve(&mut self, additional: usize) {
713         let old_cap = self.cap();
714         let used_cap = self.len() + 1;
715         let new_cap = used_cap
716             .checked_add(additional)
717             .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
718             .expect("capacity overflow");
719
720         if new_cap > old_cap {
721             self.buf.reserve_exact(used_cap, new_cap - used_cap);
722             unsafe {
723                 self.handle_capacity_increase(old_cap);
724             }
725         }
726     }
727
728     /// Tries to reserve the minimum capacity for exactly `additional` more elements to
729     /// be inserted in the given deque. After calling `try_reserve_exact`,
730     /// capacity will be greater than or equal to `self.len() + additional`.
731     /// Does nothing if the capacity is already sufficient.
732     ///
733     /// Note that the allocator may give the collection more space than it
734     /// requests. Therefore, capacity can not be relied upon to be precisely
735     /// minimal. Prefer [`try_reserve`] if future insertions are expected.
736     ///
737     /// [`try_reserve`]: VecDeque::try_reserve
738     ///
739     /// # Errors
740     ///
741     /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
742     /// is returned.
743     ///
744     /// # Examples
745     ///
746     /// ```
747     /// use std::collections::TryReserveError;
748     /// use std::collections::VecDeque;
749     ///
750     /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
751     ///     let mut output = VecDeque::new();
752     ///
753     ///     // Pre-reserve the memory, exiting if we can't
754     ///     output.try_reserve_exact(data.len())?;
755     ///
756     ///     // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
757     ///     output.extend(data.iter().map(|&val| {
758     ///         val * 2 + 5 // very complicated
759     ///     }));
760     ///
761     ///     Ok(output)
762     /// }
763     /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
764     /// ```
765     #[stable(feature = "try_reserve", since = "1.57.0")]
766     pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
767         self.try_reserve(additional)
768     }
769
770     /// Tries to reserve capacity for at least `additional` more elements to be inserted
771     /// in the given deque. The collection may reserve more space to avoid
772     /// frequent reallocations. After calling `try_reserve`, capacity will be
773     /// greater than or equal to `self.len() + additional`. Does nothing if
774     /// capacity is already sufficient.
775     ///
776     /// # Errors
777     ///
778     /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
779     /// is returned.
780     ///
781     /// # Examples
782     ///
783     /// ```
784     /// use std::collections::TryReserveError;
785     /// use std::collections::VecDeque;
786     ///
787     /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
788     ///     let mut output = VecDeque::new();
789     ///
790     ///     // Pre-reserve the memory, exiting if we can't
791     ///     output.try_reserve(data.len())?;
792     ///
793     ///     // Now we know this can't OOM in the middle of our complex work
794     ///     output.extend(data.iter().map(|&val| {
795     ///         val * 2 + 5 // very complicated
796     ///     }));
797     ///
798     ///     Ok(output)
799     /// }
800     /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
801     /// ```
802     #[stable(feature = "try_reserve", since = "1.57.0")]
803     pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
804         let old_cap = self.cap();
805         let used_cap = self.len() + 1;
806         let new_cap = used_cap
807             .checked_add(additional)
808             .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
809             .ok_or(TryReserveErrorKind::CapacityOverflow)?;
810
811         if new_cap > old_cap {
812             self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
813             unsafe {
814                 self.handle_capacity_increase(old_cap);
815             }
816         }
817         Ok(())
818     }
819
820     /// Shrinks the capacity of the deque as much as possible.
821     ///
822     /// It will drop down as close as possible to the length but the allocator may still inform the
823     /// deque that there is space for a few more elements.
824     ///
825     /// # Examples
826     ///
827     /// ```
828     /// use std::collections::VecDeque;
829     ///
830     /// let mut buf = VecDeque::with_capacity(15);
831     /// buf.extend(0..4);
832     /// assert_eq!(buf.capacity(), 15);
833     /// buf.shrink_to_fit();
834     /// assert!(buf.capacity() >= 4);
835     /// ```
836     #[stable(feature = "deque_extras_15", since = "1.5.0")]
837     pub fn shrink_to_fit(&mut self) {
838         self.shrink_to(0);
839     }
840
841     /// Shrinks the capacity of the deque with a lower bound.
842     ///
843     /// The capacity will remain at least as large as both the length
844     /// and the supplied value.
845     ///
846     /// If the current capacity is less than the lower limit, this is a no-op.
847     ///
848     /// # Examples
849     ///
850     /// ```
851     /// use std::collections::VecDeque;
852     ///
853     /// let mut buf = VecDeque::with_capacity(15);
854     /// buf.extend(0..4);
855     /// assert_eq!(buf.capacity(), 15);
856     /// buf.shrink_to(6);
857     /// assert!(buf.capacity() >= 6);
858     /// buf.shrink_to(0);
859     /// assert!(buf.capacity() >= 4);
860     /// ```
861     #[stable(feature = "shrink_to", since = "1.56.0")]
862     pub fn shrink_to(&mut self, min_capacity: usize) {
863         let min_capacity = cmp::min(min_capacity, self.capacity());
864         // We don't have to worry about an overflow as neither `self.len()` nor `self.capacity()`
865         // can ever be `usize::MAX`. +1 as the ringbuffer always leaves one space empty.
866         let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
867             .next_power_of_two();
868
869         if target_cap < self.cap() {
870             // There are three cases of interest:
871             //   All elements are out of desired bounds
872             //   Elements are contiguous, and head is out of desired bounds
873             //   Elements are discontiguous, and tail is out of desired bounds
874             //
875             // At all other times, element positions are unaffected.
876             //
877             // Indicates that elements at the head should be moved.
878             let head_outside = self.head == 0 || self.head >= target_cap;
879             // Move elements from out of desired bounds (positions after target_cap)
880             if self.tail >= target_cap && head_outside {
881                 //                    T             H
882                 //   [. . . . . . . . o o o o o o o . ]
883                 //    T             H
884                 //   [o o o o o o o . ]
885                 unsafe {
886                     self.copy_nonoverlapping(0, self.tail, self.len());
887                 }
888                 self.head = self.len();
889                 self.tail = 0;
890             } else if self.tail != 0 && self.tail < target_cap && head_outside {
891                 //          T             H
892                 //   [. . . o o o o o o o . . . . . . ]
893                 //        H T
894                 //   [o o . o o o o o ]
895                 let len = self.wrap_sub(self.head, target_cap);
896                 unsafe {
897                     self.copy_nonoverlapping(0, target_cap, len);
898                 }
899                 self.head = len;
900                 debug_assert!(self.head < self.tail);
901             } else if self.tail >= target_cap {
902                 //              H                 T
903                 //   [o o o o o . . . . . . . . . o o ]
904                 //              H T
905                 //   [o o o o o . o o ]
906                 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
907                 let len = self.cap() - self.tail;
908                 let new_tail = target_cap - len;
909                 unsafe {
910                     self.copy_nonoverlapping(new_tail, self.tail, len);
911                 }
912                 self.tail = new_tail;
913                 debug_assert!(self.head < self.tail);
914             }
915
916             self.buf.shrink_to_fit(target_cap);
917
918             debug_assert!(self.head < self.cap());
919             debug_assert!(self.tail < self.cap());
920             debug_assert!(self.cap().count_ones() == 1);
921         }
922     }
923
924     /// Shortens the deque, keeping the first `len` elements and dropping
925     /// the rest.
926     ///
927     /// If `len` is greater than the deque's current length, this has no
928     /// effect.
929     ///
930     /// # Examples
931     ///
932     /// ```
933     /// use std::collections::VecDeque;
934     ///
935     /// let mut buf = VecDeque::new();
936     /// buf.push_back(5);
937     /// buf.push_back(10);
938     /// buf.push_back(15);
939     /// assert_eq!(buf, [5, 10, 15]);
940     /// buf.truncate(1);
941     /// assert_eq!(buf, [5]);
942     /// ```
943     #[stable(feature = "deque_extras", since = "1.16.0")]
944     pub fn truncate(&mut self, len: usize) {
945         /// Runs the destructor for all items in the slice when it gets dropped (normally or
946         /// during unwinding).
947         struct Dropper<'a, T>(&'a mut [T]);
948
949         impl<'a, T> Drop for Dropper<'a, T> {
950             fn drop(&mut self) {
951                 unsafe {
952                     ptr::drop_in_place(self.0);
953                 }
954             }
955         }
956
957         // Safe because:
958         //
959         // * Any slice passed to `drop_in_place` is valid; the second case has
960         //   `len <= front.len()` and returning on `len > self.len()` ensures
961         //   `begin <= back.len()` in the first case
962         // * The head of the VecDeque is moved before calling `drop_in_place`,
963         //   so no value is dropped twice if `drop_in_place` panics
964         unsafe {
965             if len > self.len() {
966                 return;
967             }
968             let num_dropped = self.len() - len;
969             let (front, back) = self.as_mut_slices();
970             if len > front.len() {
971                 let begin = len - front.len();
972                 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
973                 self.head = self.wrap_sub(self.head, num_dropped);
974                 ptr::drop_in_place(drop_back);
975             } else {
976                 let drop_back = back as *mut _;
977                 let drop_front = front.get_unchecked_mut(len..) as *mut _;
978                 self.head = self.wrap_sub(self.head, num_dropped);
979
980                 // Make sure the second half is dropped even when a destructor
981                 // in the first one panics.
982                 let _back_dropper = Dropper(&mut *drop_back);
983                 ptr::drop_in_place(drop_front);
984             }
985         }
986     }
987
988     /// Returns a reference to the underlying allocator.
989     #[unstable(feature = "allocator_api", issue = "32838")]
990     #[inline]
991     pub fn allocator(&self) -> &A {
992         self.buf.allocator()
993     }
994
995     /// Returns a front-to-back iterator.
996     ///
997     /// # Examples
998     ///
999     /// ```
1000     /// use std::collections::VecDeque;
1001     ///
1002     /// let mut buf = VecDeque::new();
1003     /// buf.push_back(5);
1004     /// buf.push_back(3);
1005     /// buf.push_back(4);
1006     /// let b: &[_] = &[&5, &3, &4];
1007     /// let c: Vec<&i32> = buf.iter().collect();
1008     /// assert_eq!(&c[..], b);
1009     /// ```
1010     #[stable(feature = "rust1", since = "1.0.0")]
1011     pub fn iter(&self) -> Iter<'_, T> {
1012         Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } }
1013     }
1014
1015     /// Returns a front-to-back iterator that returns mutable references.
1016     ///
1017     /// # Examples
1018     ///
1019     /// ```
1020     /// use std::collections::VecDeque;
1021     ///
1022     /// let mut buf = VecDeque::new();
1023     /// buf.push_back(5);
1024     /// buf.push_back(3);
1025     /// buf.push_back(4);
1026     /// for num in buf.iter_mut() {
1027     ///     *num = *num - 2;
1028     /// }
1029     /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1030     /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1031     /// ```
1032     #[stable(feature = "rust1", since = "1.0.0")]
1033     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1034         // SAFETY: The internal `IterMut` safety invariant is established because the
1035         // `ring` we create is a dereferenceable slice for lifetime '_.
1036         let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1037
1038         unsafe { IterMut::new(ring, self.tail, self.head, PhantomData) }
1039     }
1040
1041     /// Returns a pair of slices which contain, in order, the contents of the
1042     /// deque.
1043     ///
1044     /// If [`make_contiguous`] was previously called, all elements of the
1045     /// deque will be in the first slice and the second slice will be empty.
1046     ///
1047     /// [`make_contiguous`]: VecDeque::make_contiguous
1048     ///
1049     /// # Examples
1050     ///
1051     /// ```
1052     /// use std::collections::VecDeque;
1053     ///
1054     /// let mut deque = VecDeque::new();
1055     ///
1056     /// deque.push_back(0);
1057     /// deque.push_back(1);
1058     /// deque.push_back(2);
1059     ///
1060     /// assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..]));
1061     ///
1062     /// deque.push_front(10);
1063     /// deque.push_front(9);
1064     ///
1065     /// assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1066     /// ```
1067     #[inline]
1068     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1069     pub fn as_slices(&self) -> (&[T], &[T]) {
1070         // Safety:
1071         // - `self.head` and `self.tail` in a ring buffer are always valid indices.
1072         // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
1073         unsafe {
1074             let buf = self.buffer_as_slice();
1075             let (front, back) = RingSlices::ring_slices(buf, self.head, self.tail);
1076             (MaybeUninit::slice_assume_init_ref(front), MaybeUninit::slice_assume_init_ref(back))
1077         }
1078     }
1079
1080     /// Returns a pair of slices which contain, in order, the contents of the
1081     /// deque.
1082     ///
1083     /// If [`make_contiguous`] was previously called, all elements of the
1084     /// deque will be in the first slice and the second slice will be empty.
1085     ///
1086     /// [`make_contiguous`]: VecDeque::make_contiguous
1087     ///
1088     /// # Examples
1089     ///
1090     /// ```
1091     /// use std::collections::VecDeque;
1092     ///
1093     /// let mut deque = VecDeque::new();
1094     ///
1095     /// deque.push_back(0);
1096     /// deque.push_back(1);
1097     ///
1098     /// deque.push_front(10);
1099     /// deque.push_front(9);
1100     ///
1101     /// deque.as_mut_slices().0[0] = 42;
1102     /// deque.as_mut_slices().1[0] = 24;
1103     /// assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
1104     /// ```
1105     #[inline]
1106     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1107     pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1108         // Safety:
1109         // - `self.head` and `self.tail` in a ring buffer are always valid indices.
1110         // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
1111         unsafe {
1112             let head = self.head;
1113             let tail = self.tail;
1114             let buf = self.buffer_as_mut_slice();
1115             let (front, back) = RingSlices::ring_slices(buf, head, tail);
1116             (MaybeUninit::slice_assume_init_mut(front), MaybeUninit::slice_assume_init_mut(back))
1117         }
1118     }
1119
1120     /// Returns the number of elements in the deque.
1121     ///
1122     /// # Examples
1123     ///
1124     /// ```
1125     /// use std::collections::VecDeque;
1126     ///
1127     /// let mut deque = VecDeque::new();
1128     /// assert_eq!(deque.len(), 0);
1129     /// deque.push_back(1);
1130     /// assert_eq!(deque.len(), 1);
1131     /// ```
1132     #[stable(feature = "rust1", since = "1.0.0")]
1133     pub fn len(&self) -> usize {
1134         count(self.tail, self.head, self.cap())
1135     }
1136
1137     /// Returns `true` if the deque is empty.
1138     ///
1139     /// # Examples
1140     ///
1141     /// ```
1142     /// use std::collections::VecDeque;
1143     ///
1144     /// let mut deque = VecDeque::new();
1145     /// assert!(deque.is_empty());
1146     /// deque.push_front(1);
1147     /// assert!(!deque.is_empty());
1148     /// ```
1149     #[stable(feature = "rust1", since = "1.0.0")]
1150     pub fn is_empty(&self) -> bool {
1151         self.tail == self.head
1152     }
1153
1154     fn range_tail_head<R>(&self, range: R) -> (usize, usize)
1155     where
1156         R: RangeBounds<usize>,
1157     {
1158         let Range { start, end } = slice::range(range, ..self.len());
1159         let tail = self.wrap_add(self.tail, start);
1160         let head = self.wrap_add(self.tail, end);
1161         (tail, head)
1162     }
1163
1164     /// Creates an iterator that covers the specified range in the deque.
1165     ///
1166     /// # Panics
1167     ///
1168     /// Panics if the starting point is greater than the end point or if
1169     /// the end point is greater than the length of the deque.
1170     ///
1171     /// # Examples
1172     ///
1173     /// ```
1174     /// use std::collections::VecDeque;
1175     ///
1176     /// let deque: VecDeque<_> = [1, 2, 3].into();
1177     /// let range = deque.range(2..).copied().collect::<VecDeque<_>>();
1178     /// assert_eq!(range, [3]);
1179     ///
1180     /// // A full range covers all contents
1181     /// let all = deque.range(..);
1182     /// assert_eq!(all.len(), 3);
1183     /// ```
1184     #[inline]
1185     #[stable(feature = "deque_range", since = "1.51.0")]
1186     pub fn range<R>(&self, range: R) -> Iter<'_, T>
1187     where
1188         R: RangeBounds<usize>,
1189     {
1190         let (tail, head) = self.range_tail_head(range);
1191         Iter {
1192             tail,
1193             head,
1194             // The shared reference we have in &self is maintained in the '_ of Iter.
1195             ring: unsafe { self.buffer_as_slice() },
1196         }
1197     }
1198
1199     /// Creates an iterator that covers the specified mutable range in the deque.
1200     ///
1201     /// # Panics
1202     ///
1203     /// Panics if the starting point is greater than the end point or if
1204     /// the end point is greater than the length of the deque.
1205     ///
1206     /// # Examples
1207     ///
1208     /// ```
1209     /// use std::collections::VecDeque;
1210     ///
1211     /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1212     /// for v in deque.range_mut(2..) {
1213     ///   *v *= 2;
1214     /// }
1215     /// assert_eq!(deque, [1, 2, 6]);
1216     ///
1217     /// // A full range covers all contents
1218     /// for v in deque.range_mut(..) {
1219     ///   *v *= 2;
1220     /// }
1221     /// assert_eq!(deque, [2, 4, 12]);
1222     /// ```
1223     #[inline]
1224     #[stable(feature = "deque_range", since = "1.51.0")]
1225     pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1226     where
1227         R: RangeBounds<usize>,
1228     {
1229         let (tail, head) = self.range_tail_head(range);
1230
1231         // SAFETY: The internal `IterMut` safety invariant is established because the
1232         // `ring` we create is a dereferenceable slice for lifetime '_.
1233         let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
1234
1235         unsafe { IterMut::new(ring, tail, head, PhantomData) }
1236     }
1237
1238     /// Removes the specified range from the deque in bulk, returning all
1239     /// removed elements as an iterator. If the iterator is dropped before
1240     /// being fully consumed, it drops the remaining removed elements.
1241     ///
1242     /// The returned iterator keeps a mutable borrow on the queue to optimize
1243     /// its implementation.
1244     ///
1245     ///
1246     /// # Panics
1247     ///
1248     /// Panics if the starting point is greater than the end point or if
1249     /// the end point is greater than the length of the deque.
1250     ///
1251     /// # Leaking
1252     ///
1253     /// If the returned iterator goes out of scope without being dropped (due to
1254     /// [`mem::forget`], for example), the deque may have lost and leaked
1255     /// elements arbitrarily, including elements outside the range.
1256     ///
1257     /// # Examples
1258     ///
1259     /// ```
1260     /// use std::collections::VecDeque;
1261     ///
1262     /// let mut deque: VecDeque<_> = [1, 2, 3].into();
1263     /// let drained = deque.drain(2..).collect::<VecDeque<_>>();
1264     /// assert_eq!(drained, [3]);
1265     /// assert_eq!(deque, [1, 2]);
1266     ///
1267     /// // A full range clears all contents, like `clear()` does
1268     /// deque.drain(..);
1269     /// assert!(deque.is_empty());
1270     /// ```
1271     #[inline]
1272     #[stable(feature = "drain", since = "1.6.0")]
1273     pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1274     where
1275         R: RangeBounds<usize>,
1276     {
1277         // Memory safety
1278         //
1279         // When the Drain is first created, the source deque is shortened to
1280         // make sure no uninitialized or moved-from elements are accessible at
1281         // all if the Drain's destructor never gets to run.
1282         //
1283         // Drain will ptr::read out the values to remove.
1284         // When finished, the remaining data will be copied back to cover the hole,
1285         // and the head/tail values will be restored correctly.
1286         //
1287         let (drain_tail, drain_head) = self.range_tail_head(range);
1288
1289         // The deque's elements are parted into three segments:
1290         // * self.tail  -> drain_tail
1291         // * drain_tail -> drain_head
1292         // * drain_head -> self.head
1293         //
1294         // T = self.tail; H = self.head; t = drain_tail; h = drain_head
1295         //
1296         // We store drain_tail as self.head, and drain_head and self.head as
1297         // after_tail and after_head respectively on the Drain. This also
1298         // truncates the effective array such that if the Drain is leaked, we
1299         // have forgotten about the potentially moved values after the start of
1300         // the drain.
1301         //
1302         //        T   t   h   H
1303         // [. . . o o x x o o . . .]
1304         //
1305         let head = self.head;
1306
1307         // "forget" about the values after the start of the drain until after
1308         // the drain is complete and the Drain destructor is run.
1309         self.head = drain_tail;
1310
1311         let deque = NonNull::from(&mut *self);
1312         let iter = Iter {
1313             tail: drain_tail,
1314             head: drain_head,
1315             // Crucially, we only create shared references from `self` here and read from
1316             // it.  We do not write to `self` nor reborrow to a mutable reference.
1317             // Hence the raw pointer we created above, for `deque`, remains valid.
1318             ring: unsafe { self.buffer_as_slice() },
1319         };
1320
1321         unsafe { Drain::new(drain_head, head, iter, deque) }
1322     }
1323
1324     /// Clears the deque, removing all values.
1325     ///
1326     /// # Examples
1327     ///
1328     /// ```
1329     /// use std::collections::VecDeque;
1330     ///
1331     /// let mut deque = VecDeque::new();
1332     /// deque.push_back(1);
1333     /// deque.clear();
1334     /// assert!(deque.is_empty());
1335     /// ```
1336     #[stable(feature = "rust1", since = "1.0.0")]
1337     #[inline]
1338     pub fn clear(&mut self) {
1339         self.truncate(0);
1340     }
1341
1342     /// Returns `true` if the deque contains an element equal to the
1343     /// given value.
1344     ///
1345     /// This operation is *O*(*n*).
1346     ///
1347     /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
1348     ///
1349     /// [`binary_search`]: VecDeque::binary_search
1350     ///
1351     /// # Examples
1352     ///
1353     /// ```
1354     /// use std::collections::VecDeque;
1355     ///
1356     /// let mut deque: VecDeque<u32> = VecDeque::new();
1357     ///
1358     /// deque.push_back(0);
1359     /// deque.push_back(1);
1360     ///
1361     /// assert_eq!(deque.contains(&1), true);
1362     /// assert_eq!(deque.contains(&10), false);
1363     /// ```
1364     #[stable(feature = "vec_deque_contains", since = "1.12.0")]
1365     pub fn contains(&self, x: &T) -> bool
1366     where
1367         T: PartialEq<T>,
1368     {
1369         let (a, b) = self.as_slices();
1370         a.contains(x) || b.contains(x)
1371     }
1372
1373     /// Provides a reference to the front element, or `None` if the deque is
1374     /// empty.
1375     ///
1376     /// # Examples
1377     ///
1378     /// ```
1379     /// use std::collections::VecDeque;
1380     ///
1381     /// let mut d = VecDeque::new();
1382     /// assert_eq!(d.front(), None);
1383     ///
1384     /// d.push_back(1);
1385     /// d.push_back(2);
1386     /// assert_eq!(d.front(), Some(&1));
1387     /// ```
1388     #[stable(feature = "rust1", since = "1.0.0")]
1389     pub fn front(&self) -> Option<&T> {
1390         self.get(0)
1391     }
1392
1393     /// Provides a mutable reference to the front element, or `None` if the
1394     /// deque is empty.
1395     ///
1396     /// # Examples
1397     ///
1398     /// ```
1399     /// use std::collections::VecDeque;
1400     ///
1401     /// let mut d = VecDeque::new();
1402     /// assert_eq!(d.front_mut(), None);
1403     ///
1404     /// d.push_back(1);
1405     /// d.push_back(2);
1406     /// match d.front_mut() {
1407     ///     Some(x) => *x = 9,
1408     ///     None => (),
1409     /// }
1410     /// assert_eq!(d.front(), Some(&9));
1411     /// ```
1412     #[stable(feature = "rust1", since = "1.0.0")]
1413     pub fn front_mut(&mut self) -> Option<&mut T> {
1414         self.get_mut(0)
1415     }
1416
1417     /// Provides a reference to the back element, or `None` if the deque is
1418     /// empty.
1419     ///
1420     /// # Examples
1421     ///
1422     /// ```
1423     /// use std::collections::VecDeque;
1424     ///
1425     /// let mut d = VecDeque::new();
1426     /// assert_eq!(d.back(), None);
1427     ///
1428     /// d.push_back(1);
1429     /// d.push_back(2);
1430     /// assert_eq!(d.back(), Some(&2));
1431     /// ```
1432     #[stable(feature = "rust1", since = "1.0.0")]
1433     pub fn back(&self) -> Option<&T> {
1434         self.get(self.len().wrapping_sub(1))
1435     }
1436
1437     /// Provides a mutable reference to the back element, or `None` if the
1438     /// deque is empty.
1439     ///
1440     /// # Examples
1441     ///
1442     /// ```
1443     /// use std::collections::VecDeque;
1444     ///
1445     /// let mut d = VecDeque::new();
1446     /// assert_eq!(d.back(), None);
1447     ///
1448     /// d.push_back(1);
1449     /// d.push_back(2);
1450     /// match d.back_mut() {
1451     ///     Some(x) => *x = 9,
1452     ///     None => (),
1453     /// }
1454     /// assert_eq!(d.back(), Some(&9));
1455     /// ```
1456     #[stable(feature = "rust1", since = "1.0.0")]
1457     pub fn back_mut(&mut self) -> Option<&mut T> {
1458         self.get_mut(self.len().wrapping_sub(1))
1459     }
1460
1461     /// Removes the first element and returns it, or `None` if the deque is
1462     /// empty.
1463     ///
1464     /// # Examples
1465     ///
1466     /// ```
1467     /// use std::collections::VecDeque;
1468     ///
1469     /// let mut d = VecDeque::new();
1470     /// d.push_back(1);
1471     /// d.push_back(2);
1472     ///
1473     /// assert_eq!(d.pop_front(), Some(1));
1474     /// assert_eq!(d.pop_front(), Some(2));
1475     /// assert_eq!(d.pop_front(), None);
1476     /// ```
1477     #[stable(feature = "rust1", since = "1.0.0")]
1478     pub fn pop_front(&mut self) -> Option<T> {
1479         if self.is_empty() {
1480             None
1481         } else {
1482             let tail = self.tail;
1483             self.tail = self.wrap_add(self.tail, 1);
1484             unsafe { Some(self.buffer_read(tail)) }
1485         }
1486     }
1487
1488     /// Removes the last element from the deque and returns it, or `None` if
1489     /// it is empty.
1490     ///
1491     /// # Examples
1492     ///
1493     /// ```
1494     /// use std::collections::VecDeque;
1495     ///
1496     /// let mut buf = VecDeque::new();
1497     /// assert_eq!(buf.pop_back(), None);
1498     /// buf.push_back(1);
1499     /// buf.push_back(3);
1500     /// assert_eq!(buf.pop_back(), Some(3));
1501     /// ```
1502     #[stable(feature = "rust1", since = "1.0.0")]
1503     pub fn pop_back(&mut self) -> Option<T> {
1504         if self.is_empty() {
1505             None
1506         } else {
1507             self.head = self.wrap_sub(self.head, 1);
1508             let head = self.head;
1509             unsafe { Some(self.buffer_read(head)) }
1510         }
1511     }
1512
1513     /// Prepends an element to the deque.
1514     ///
1515     /// # Examples
1516     ///
1517     /// ```
1518     /// use std::collections::VecDeque;
1519     ///
1520     /// let mut d = VecDeque::new();
1521     /// d.push_front(1);
1522     /// d.push_front(2);
1523     /// assert_eq!(d.front(), Some(&2));
1524     /// ```
1525     #[stable(feature = "rust1", since = "1.0.0")]
1526     pub fn push_front(&mut self, value: T) {
1527         if self.is_full() {
1528             self.grow();
1529         }
1530
1531         self.tail = self.wrap_sub(self.tail, 1);
1532         let tail = self.tail;
1533         unsafe {
1534             self.buffer_write(tail, value);
1535         }
1536     }
1537
1538     /// Appends an element to the back of the deque.
1539     ///
1540     /// # Examples
1541     ///
1542     /// ```
1543     /// use std::collections::VecDeque;
1544     ///
1545     /// let mut buf = VecDeque::new();
1546     /// buf.push_back(1);
1547     /// buf.push_back(3);
1548     /// assert_eq!(3, *buf.back().unwrap());
1549     /// ```
1550     #[stable(feature = "rust1", since = "1.0.0")]
1551     pub fn push_back(&mut self, value: T) {
1552         if self.is_full() {
1553             self.grow();
1554         }
1555
1556         let head = self.head;
1557         self.head = self.wrap_add(self.head, 1);
1558         unsafe { self.buffer_write(head, value) }
1559     }
1560
1561     #[inline]
1562     fn is_contiguous(&self) -> bool {
1563         // FIXME: Should we consider `head == 0` to mean
1564         // that `self` is contiguous?
1565         self.tail <= self.head
1566     }
1567
1568     /// Removes an element from anywhere in the deque and returns it,
1569     /// replacing it with the first element.
1570     ///
1571     /// This does not preserve ordering, but is *O*(1).
1572     ///
1573     /// Returns `None` if `index` is out of bounds.
1574     ///
1575     /// Element at index 0 is the front of the queue.
1576     ///
1577     /// # Examples
1578     ///
1579     /// ```
1580     /// use std::collections::VecDeque;
1581     ///
1582     /// let mut buf = VecDeque::new();
1583     /// assert_eq!(buf.swap_remove_front(0), None);
1584     /// buf.push_back(1);
1585     /// buf.push_back(2);
1586     /// buf.push_back(3);
1587     /// assert_eq!(buf, [1, 2, 3]);
1588     ///
1589     /// assert_eq!(buf.swap_remove_front(2), Some(3));
1590     /// assert_eq!(buf, [2, 1]);
1591     /// ```
1592     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1593     pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1594         let length = self.len();
1595         if length > 0 && index < length && index != 0 {
1596             self.swap(index, 0);
1597         } else if index >= length {
1598             return None;
1599         }
1600         self.pop_front()
1601     }
1602
1603     /// Removes an element from anywhere in the deque and returns it,
1604     /// replacing it with the last element.
1605     ///
1606     /// This does not preserve ordering, but is *O*(1).
1607     ///
1608     /// Returns `None` if `index` is out of bounds.
1609     ///
1610     /// Element at index 0 is the front of the queue.
1611     ///
1612     /// # Examples
1613     ///
1614     /// ```
1615     /// use std::collections::VecDeque;
1616     ///
1617     /// let mut buf = VecDeque::new();
1618     /// assert_eq!(buf.swap_remove_back(0), None);
1619     /// buf.push_back(1);
1620     /// buf.push_back(2);
1621     /// buf.push_back(3);
1622     /// assert_eq!(buf, [1, 2, 3]);
1623     ///
1624     /// assert_eq!(buf.swap_remove_back(0), Some(1));
1625     /// assert_eq!(buf, [3, 2]);
1626     /// ```
1627     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1628     pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1629         let length = self.len();
1630         if length > 0 && index < length - 1 {
1631             self.swap(index, length - 1);
1632         } else if index >= length {
1633             return None;
1634         }
1635         self.pop_back()
1636     }
1637
1638     /// Inserts an element at `index` within the deque, shifting all elements
1639     /// with indices greater than or equal to `index` towards the back.
1640     ///
1641     /// Element at index 0 is the front of the queue.
1642     ///
1643     /// # Panics
1644     ///
1645     /// Panics if `index` is greater than deque's length
1646     ///
1647     /// # Examples
1648     ///
1649     /// ```
1650     /// use std::collections::VecDeque;
1651     ///
1652     /// let mut vec_deque = VecDeque::new();
1653     /// vec_deque.push_back('a');
1654     /// vec_deque.push_back('b');
1655     /// vec_deque.push_back('c');
1656     /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1657     ///
1658     /// vec_deque.insert(1, 'd');
1659     /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1660     /// ```
1661     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1662     pub fn insert(&mut self, index: usize, value: T) {
1663         assert!(index <= self.len(), "index out of bounds");
1664         if self.is_full() {
1665             self.grow();
1666         }
1667
1668         // Move the least number of elements in the ring buffer and insert
1669         // the given object
1670         //
1671         // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1672         //
1673         // There are three main cases:
1674         //  Elements are contiguous
1675         //      - special case when tail is 0
1676         //  Elements are discontiguous and the insert is in the tail section
1677         //  Elements are discontiguous and the insert is in the head section
1678         //
1679         // For each of those there are two more cases:
1680         //  Insert is closer to tail
1681         //  Insert is closer to head
1682         //
1683         // Key: H - self.head
1684         //      T - self.tail
1685         //      o - Valid element
1686         //      I - Insertion element
1687         //      A - The element that should be after the insertion point
1688         //      M - Indicates element was moved
1689
1690         let idx = self.wrap_add(self.tail, index);
1691
1692         let distance_to_tail = index;
1693         let distance_to_head = self.len() - index;
1694
1695         let contiguous = self.is_contiguous();
1696
1697         match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1698             (true, true, _) if index == 0 => {
1699                 // push_front
1700                 //
1701                 //       T
1702                 //       I             H
1703                 //      [A o o o o o o . . . . . . . . .]
1704                 //
1705                 //                       H         T
1706                 //      [A o o o o o o o . . . . . I]
1707                 //
1708
1709                 self.tail = self.wrap_sub(self.tail, 1);
1710             }
1711             (true, true, _) => {
1712                 unsafe {
1713                     // contiguous, insert closer to tail:
1714                     //
1715                     //             T   I         H
1716                     //      [. . . o o A o o o o . . . . . .]
1717                     //
1718                     //           T               H
1719                     //      [. . o o I A o o o o . . . . . .]
1720                     //           M M
1721                     //
1722                     // contiguous, insert closer to tail and tail is 0:
1723                     //
1724                     //
1725                     //       T   I         H
1726                     //      [o o A o o o o . . . . . . . . .]
1727                     //
1728                     //                       H             T
1729                     //      [o I A o o o o o . . . . . . . o]
1730                     //       M                             M
1731
1732                     let new_tail = self.wrap_sub(self.tail, 1);
1733
1734                     self.copy(new_tail, self.tail, 1);
1735                     // Already moved the tail, so we only copy `index - 1` elements.
1736                     self.copy(self.tail, self.tail + 1, index - 1);
1737
1738                     self.tail = new_tail;
1739                 }
1740             }
1741             (true, false, _) => {
1742                 unsafe {
1743                     //  contiguous, insert closer to head:
1744                     //
1745                     //             T       I     H
1746                     //      [. . . o o o o A o o . . . . . .]
1747                     //
1748                     //             T               H
1749                     //      [. . . o o o o I A o o . . . . .]
1750                     //                       M M M
1751
1752                     self.copy(idx + 1, idx, self.head - idx);
1753                     self.head = self.wrap_add(self.head, 1);
1754                 }
1755             }
1756             (false, true, true) => {
1757                 unsafe {
1758                     // discontiguous, insert closer to tail, tail section:
1759                     //
1760                     //                   H         T   I
1761                     //      [o o o o o o . . . . . o o A o o]
1762                     //
1763                     //                   H       T
1764                     //      [o o o o o o . . . . o o I A o o]
1765                     //                           M M
1766
1767                     self.copy(self.tail - 1, self.tail, index);
1768                     self.tail -= 1;
1769                 }
1770             }
1771             (false, false, true) => {
1772                 unsafe {
1773                     // discontiguous, insert closer to head, tail section:
1774                     //
1775                     //           H             T         I
1776                     //      [o o . . . . . . . o o o o o A o]
1777                     //
1778                     //             H           T
1779                     //      [o o o . . . . . . o o o o o I A]
1780                     //       M M M                         M
1781
1782                     // copy elements up to new head
1783                     self.copy(1, 0, self.head);
1784
1785                     // copy last element into empty spot at bottom of buffer
1786                     self.copy(0, self.cap() - 1, 1);
1787
1788                     // move elements from idx to end forward not including ^ element
1789                     self.copy(idx + 1, idx, self.cap() - 1 - idx);
1790
1791                     self.head += 1;
1792                 }
1793             }
1794             (false, true, false) if idx == 0 => {
1795                 unsafe {
1796                     // discontiguous, insert is closer to tail, head section,
1797                     // and is at index zero in the internal buffer:
1798                     //
1799                     //       I                   H     T
1800                     //      [A o o o o o o o o o . . . o o o]
1801                     //
1802                     //                           H   T
1803                     //      [A o o o o o o o o o . . o o o I]
1804                     //                               M M M
1805
1806                     // copy elements up to new tail
1807                     self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1808
1809                     // copy last element into empty spot at bottom of buffer
1810                     self.copy(self.cap() - 1, 0, 1);
1811
1812                     self.tail -= 1;
1813                 }
1814             }
1815             (false, true, false) => {
1816                 unsafe {
1817                     // discontiguous, insert closer to tail, head section:
1818                     //
1819                     //             I             H     T
1820                     //      [o o o A o o o o o o . . . o o o]
1821                     //
1822                     //                           H   T
1823                     //      [o o I A o o o o o o . . o o o o]
1824                     //       M M                     M M M M
1825
1826                     // copy elements up to new tail
1827                     self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1828
1829                     // copy last element into empty spot at bottom of buffer
1830                     self.copy(self.cap() - 1, 0, 1);
1831
1832                     // move elements from idx-1 to end forward not including ^ element
1833                     self.copy(0, 1, idx - 1);
1834
1835                     self.tail -= 1;
1836                 }
1837             }
1838             (false, false, false) => {
1839                 unsafe {
1840                     // discontiguous, insert closer to head, head section:
1841                     //
1842                     //               I     H           T
1843                     //      [o o o o A o o . . . . . . o o o]
1844                     //
1845                     //                     H           T
1846                     //      [o o o o I A o o . . . . . o o o]
1847                     //                 M M M
1848
1849                     self.copy(idx + 1, idx, self.head - idx);
1850                     self.head += 1;
1851                 }
1852             }
1853         }
1854
1855         // tail might've been changed so we need to recalculate
1856         let new_idx = self.wrap_add(self.tail, index);
1857         unsafe {
1858             self.buffer_write(new_idx, value);
1859         }
1860     }
1861
1862     /// Removes and returns the element at `index` from the deque.
1863     /// Whichever end is closer to the removal point will be moved to make
1864     /// room, and all the affected elements will be moved to new positions.
1865     /// Returns `None` if `index` is out of bounds.
1866     ///
1867     /// Element at index 0 is the front of the queue.
1868     ///
1869     /// # Examples
1870     ///
1871     /// ```
1872     /// use std::collections::VecDeque;
1873     ///
1874     /// let mut buf = VecDeque::new();
1875     /// buf.push_back(1);
1876     /// buf.push_back(2);
1877     /// buf.push_back(3);
1878     /// assert_eq!(buf, [1, 2, 3]);
1879     ///
1880     /// assert_eq!(buf.remove(1), Some(2));
1881     /// assert_eq!(buf, [1, 3]);
1882     /// ```
1883     #[stable(feature = "rust1", since = "1.0.0")]
1884     pub fn remove(&mut self, index: usize) -> Option<T> {
1885         if self.is_empty() || self.len() <= index {
1886             return None;
1887         }
1888
1889         // There are three main cases:
1890         //  Elements are contiguous
1891         //  Elements are discontiguous and the removal is in the tail section
1892         //  Elements are discontiguous and the removal is in the head section
1893         //      - special case when elements are technically contiguous,
1894         //        but self.head = 0
1895         //
1896         // For each of those there are two more cases:
1897         //  Insert is closer to tail
1898         //  Insert is closer to head
1899         //
1900         // Key: H - self.head
1901         //      T - self.tail
1902         //      o - Valid element
1903         //      x - Element marked for removal
1904         //      R - Indicates element that is being removed
1905         //      M - Indicates element was moved
1906
1907         let idx = self.wrap_add(self.tail, index);
1908
1909         let elem = unsafe { Some(self.buffer_read(idx)) };
1910
1911         let distance_to_tail = index;
1912         let distance_to_head = self.len() - index;
1913
1914         let contiguous = self.is_contiguous();
1915
1916         match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1917             (true, true, _) => {
1918                 unsafe {
1919                     // contiguous, remove closer to tail:
1920                     //
1921                     //             T   R         H
1922                     //      [. . . o o x o o o o . . . . . .]
1923                     //
1924                     //               T           H
1925                     //      [. . . . o o o o o o . . . . . .]
1926                     //               M M
1927
1928                     self.copy(self.tail + 1, self.tail, index);
1929                     self.tail += 1;
1930                 }
1931             }
1932             (true, false, _) => {
1933                 unsafe {
1934                     // contiguous, remove closer to head:
1935                     //
1936                     //             T       R     H
1937                     //      [. . . o o o o x o o . . . . . .]
1938                     //
1939                     //             T           H
1940                     //      [. . . o o o o o o . . . . . . .]
1941                     //                     M M
1942
1943                     self.copy(idx, idx + 1, self.head - idx - 1);
1944                     self.head -= 1;
1945                 }
1946             }
1947             (false, true, true) => {
1948                 unsafe {
1949                     // discontiguous, remove closer to tail, tail section:
1950                     //
1951                     //                   H         T   R
1952                     //      [o o o o o o . . . . . o o x o o]
1953                     //
1954                     //                   H           T
1955                     //      [o o o o o o . . . . . . o o o o]
1956                     //                               M M
1957
1958                     self.copy(self.tail + 1, self.tail, index);
1959                     self.tail = self.wrap_add(self.tail, 1);
1960                 }
1961             }
1962             (false, false, false) => {
1963                 unsafe {
1964                     // discontiguous, remove closer to head, head section:
1965                     //
1966                     //               R     H           T
1967                     //      [o o o o x o o . . . . . . o o o]
1968                     //
1969                     //                   H             T
1970                     //      [o o o o o o . . . . . . . o o o]
1971                     //               M M
1972
1973                     self.copy(idx, idx + 1, self.head - idx - 1);
1974                     self.head -= 1;
1975                 }
1976             }
1977             (false, false, true) => {
1978                 unsafe {
1979                     // discontiguous, remove closer to head, tail section:
1980                     //
1981                     //             H           T         R
1982                     //      [o o o . . . . . . o o o o o x o]
1983                     //
1984                     //           H             T
1985                     //      [o o . . . . . . . o o o o o o o]
1986                     //       M M                         M M
1987                     //
1988                     // or quasi-discontiguous, remove next to head, tail section:
1989                     //
1990                     //       H                 T         R
1991                     //      [. . . . . . . . . o o o o o x o]
1992                     //
1993                     //                         T           H
1994                     //      [. . . . . . . . . o o o o o o .]
1995                     //                                   M
1996
1997                     // draw in elements in the tail section
1998                     self.copy(idx, idx + 1, self.cap() - idx - 1);
1999
2000                     // Prevents underflow.
2001                     if self.head != 0 {
2002                         // copy first element into empty spot
2003                         self.copy(self.cap() - 1, 0, 1);
2004
2005                         // move elements in the head section backwards
2006                         self.copy(0, 1, self.head - 1);
2007                     }
2008
2009                     self.head = self.wrap_sub(self.head, 1);
2010                 }
2011             }
2012             (false, true, false) => {
2013                 unsafe {
2014                     // discontiguous, remove closer to tail, head section:
2015                     //
2016                     //           R               H     T
2017                     //      [o o x o o o o o o o . . . o o o]
2018                     //
2019                     //                           H       T
2020                     //      [o o o o o o o o o o . . . . o o]
2021                     //       M M M                       M M
2022
2023                     // draw in elements up to idx
2024                     self.copy(1, 0, idx);
2025
2026                     // copy last element into empty spot
2027                     self.copy(0, self.cap() - 1, 1);
2028
2029                     // move elements from tail to end forward, excluding the last one
2030                     self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
2031
2032                     self.tail = self.wrap_add(self.tail, 1);
2033                 }
2034             }
2035         }
2036
2037         elem
2038     }
2039
2040     /// Splits the deque into two at the given index.
2041     ///
2042     /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
2043     /// and the returned deque contains elements `[at, len)`.
2044     ///
2045     /// Note that the capacity of `self` does not change.
2046     ///
2047     /// Element at index 0 is the front of the queue.
2048     ///
2049     /// # Panics
2050     ///
2051     /// Panics if `at > len`.
2052     ///
2053     /// # Examples
2054     ///
2055     /// ```
2056     /// use std::collections::VecDeque;
2057     ///
2058     /// let mut buf: VecDeque<_> = [1, 2, 3].into();
2059     /// let buf2 = buf.split_off(1);
2060     /// assert_eq!(buf, [1]);
2061     /// assert_eq!(buf2, [2, 3]);
2062     /// ```
2063     #[inline]
2064     #[must_use = "use `.truncate()` if you don't need the other half"]
2065     #[stable(feature = "split_off", since = "1.4.0")]
2066     pub fn split_off(&mut self, at: usize) -> Self
2067     where
2068         A: Clone,
2069     {
2070         let len = self.len();
2071         assert!(at <= len, "`at` out of bounds");
2072
2073         let other_len = len - at;
2074         let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
2075
2076         unsafe {
2077             let (first_half, second_half) = self.as_slices();
2078
2079             let first_len = first_half.len();
2080             let second_len = second_half.len();
2081             if at < first_len {
2082                 // `at` lies in the first half.
2083                 let amount_in_first = first_len - at;
2084
2085                 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
2086
2087                 // just take all of the second half.
2088                 ptr::copy_nonoverlapping(
2089                     second_half.as_ptr(),
2090                     other.ptr().add(amount_in_first),
2091                     second_len,
2092                 );
2093             } else {
2094                 // `at` lies in the second half, need to factor in the elements we skipped
2095                 // in the first half.
2096                 let offset = at - first_len;
2097                 let amount_in_second = second_len - offset;
2098                 ptr::copy_nonoverlapping(
2099                     second_half.as_ptr().add(offset),
2100                     other.ptr(),
2101                     amount_in_second,
2102                 );
2103             }
2104         }
2105
2106         // Cleanup where the ends of the buffers are
2107         self.head = self.wrap_sub(self.head, other_len);
2108         other.head = other.wrap_index(other_len);
2109
2110         other
2111     }
2112
2113     /// Moves all the elements of `other` into `self`, leaving `other` empty.
2114     ///
2115     /// # Panics
2116     ///
2117     /// Panics if the new number of elements in self overflows a `usize`.
2118     ///
2119     /// # Examples
2120     ///
2121     /// ```
2122     /// use std::collections::VecDeque;
2123     ///
2124     /// let mut buf: VecDeque<_> = [1, 2].into();
2125     /// let mut buf2: VecDeque<_> = [3, 4].into();
2126     /// buf.append(&mut buf2);
2127     /// assert_eq!(buf, [1, 2, 3, 4]);
2128     /// assert_eq!(buf2, []);
2129     /// ```
2130     #[inline]
2131     #[stable(feature = "append", since = "1.4.0")]
2132     pub fn append(&mut self, other: &mut Self) {
2133         self.reserve(other.len());
2134         unsafe {
2135             let (left, right) = other.as_slices();
2136             self.copy_slice(self.head, left);
2137             self.copy_slice(self.wrap_add(self.head, left.len()), right);
2138         }
2139         // SAFETY: Update pointers after copying to avoid leaving doppelganger
2140         // in case of panics.
2141         self.head = self.wrap_add(self.head, other.len());
2142         // Silently drop values in `other`.
2143         other.tail = other.head;
2144     }
2145
2146     /// Retains only the elements specified by the predicate.
2147     ///
2148     /// In other words, remove all elements `e` for which `f(&e)` returns false.
2149     /// This method operates in place, visiting each element exactly once in the
2150     /// original order, and preserves the order of the retained elements.
2151     ///
2152     /// # Examples
2153     ///
2154     /// ```
2155     /// use std::collections::VecDeque;
2156     ///
2157     /// let mut buf = VecDeque::new();
2158     /// buf.extend(1..5);
2159     /// buf.retain(|&x| x % 2 == 0);
2160     /// assert_eq!(buf, [2, 4]);
2161     /// ```
2162     ///
2163     /// Because the elements are visited exactly once in the original order,
2164     /// external state may be used to decide which elements to keep.
2165     ///
2166     /// ```
2167     /// use std::collections::VecDeque;
2168     ///
2169     /// let mut buf = VecDeque::new();
2170     /// buf.extend(1..6);
2171     ///
2172     /// let keep = [false, true, true, false, true];
2173     /// let mut iter = keep.iter();
2174     /// buf.retain(|_| *iter.next().unwrap());
2175     /// assert_eq!(buf, [2, 3, 5]);
2176     /// ```
2177     #[stable(feature = "vec_deque_retain", since = "1.4.0")]
2178     pub fn retain<F>(&mut self, mut f: F)
2179     where
2180         F: FnMut(&T) -> bool,
2181     {
2182         self.retain_mut(|elem| f(elem));
2183     }
2184
2185     /// Retains only the elements specified by the predicate.
2186     ///
2187     /// In other words, remove all elements `e` for which `f(&e)` returns false.
2188     /// This method operates in place, visiting each element exactly once in the
2189     /// original order, and preserves the order of the retained elements.
2190     ///
2191     /// # Examples
2192     ///
2193     /// ```
2194     /// use std::collections::VecDeque;
2195     ///
2196     /// let mut buf = VecDeque::new();
2197     /// buf.extend(1..5);
2198     /// buf.retain_mut(|x| if *x % 2 == 0 {
2199     ///     *x += 1;
2200     ///     true
2201     /// } else {
2202     ///     false
2203     /// });
2204     /// assert_eq!(buf, [3, 5]);
2205     /// ```
2206     #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2207     pub fn retain_mut<F>(&mut self, mut f: F)
2208     where
2209         F: FnMut(&mut T) -> bool,
2210     {
2211         let len = self.len();
2212         let mut idx = 0;
2213         let mut cur = 0;
2214
2215         // Stage 1: All values are retained.
2216         while cur < len {
2217             if !f(&mut self[cur]) {
2218                 cur += 1;
2219                 break;
2220             }
2221             cur += 1;
2222             idx += 1;
2223         }
2224         // Stage 2: Swap retained value into current idx.
2225         while cur < len {
2226             if !f(&mut self[cur]) {
2227                 cur += 1;
2228                 continue;
2229             }
2230
2231             self.swap(idx, cur);
2232             cur += 1;
2233             idx += 1;
2234         }
2235         // Stage 3: Truncate all values after idx.
2236         if cur != idx {
2237             self.truncate(idx);
2238         }
2239     }
2240
2241     // Double the buffer size. This method is inline(never), so we expect it to only
2242     // be called in cold paths.
2243     // This may panic or abort
2244     #[inline(never)]
2245     fn grow(&mut self) {
2246         // Extend or possibly remove this assertion when valid use-cases for growing the
2247         // buffer without it being full emerge
2248         debug_assert!(self.is_full());
2249         let old_cap = self.cap();
2250         self.buf.reserve_exact(old_cap, old_cap);
2251         assert!(self.cap() == old_cap * 2);
2252         unsafe {
2253             self.handle_capacity_increase(old_cap);
2254         }
2255         debug_assert!(!self.is_full());
2256     }
2257
2258     /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2259     /// either by removing excess elements from the back or by appending
2260     /// elements generated by calling `generator` to the back.
2261     ///
2262     /// # Examples
2263     ///
2264     /// ```
2265     /// use std::collections::VecDeque;
2266     ///
2267     /// let mut buf = VecDeque::new();
2268     /// buf.push_back(5);
2269     /// buf.push_back(10);
2270     /// buf.push_back(15);
2271     /// assert_eq!(buf, [5, 10, 15]);
2272     ///
2273     /// buf.resize_with(5, Default::default);
2274     /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2275     ///
2276     /// buf.resize_with(2, || unreachable!());
2277     /// assert_eq!(buf, [5, 10]);
2278     ///
2279     /// let mut state = 100;
2280     /// buf.resize_with(5, || { state += 1; state });
2281     /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2282     /// ```
2283     #[stable(feature = "vec_resize_with", since = "1.33.0")]
2284     pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
2285         let len = self.len();
2286
2287         if new_len > len {
2288             self.extend(repeat_with(generator).take(new_len - len))
2289         } else {
2290             self.truncate(new_len);
2291         }
2292     }
2293
2294     /// Rearranges the internal storage of this deque so it is one contiguous
2295     /// slice, which is then returned.
2296     ///
2297     /// This method does not allocate and does not change the order of the
2298     /// inserted elements. As it returns a mutable slice, this can be used to
2299     /// sort a deque.
2300     ///
2301     /// Once the internal storage is contiguous, the [`as_slices`] and
2302     /// [`as_mut_slices`] methods will return the entire contents of the
2303     /// deque in a single slice.
2304     ///
2305     /// [`as_slices`]: VecDeque::as_slices
2306     /// [`as_mut_slices`]: VecDeque::as_mut_slices
2307     ///
2308     /// # Examples
2309     ///
2310     /// Sorting the content of a deque.
2311     ///
2312     /// ```
2313     /// use std::collections::VecDeque;
2314     ///
2315     /// let mut buf = VecDeque::with_capacity(15);
2316     ///
2317     /// buf.push_back(2);
2318     /// buf.push_back(1);
2319     /// buf.push_front(3);
2320     ///
2321     /// // sorting the deque
2322     /// buf.make_contiguous().sort();
2323     /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2324     ///
2325     /// // sorting it in reverse order
2326     /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2327     /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2328     /// ```
2329     ///
2330     /// Getting immutable access to the contiguous slice.
2331     ///
2332     /// ```rust
2333     /// use std::collections::VecDeque;
2334     ///
2335     /// let mut buf = VecDeque::new();
2336     ///
2337     /// buf.push_back(2);
2338     /// buf.push_back(1);
2339     /// buf.push_front(3);
2340     ///
2341     /// buf.make_contiguous();
2342     /// if let (slice, &[]) = buf.as_slices() {
2343     ///     // we can now be sure that `slice` contains all elements of the deque,
2344     ///     // while still having immutable access to `buf`.
2345     ///     assert_eq!(buf.len(), slice.len());
2346     ///     assert_eq!(slice, &[3, 2, 1] as &[_]);
2347     /// }
2348     /// ```
2349     #[stable(feature = "deque_make_contiguous", since = "1.48.0")]
2350     pub fn make_contiguous(&mut self) -> &mut [T] {
2351         if self.is_contiguous() {
2352             let tail = self.tail;
2353             let head = self.head;
2354             // Safety:
2355             // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2356             // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2357             return unsafe {
2358                 MaybeUninit::slice_assume_init_mut(
2359                     RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2360                 )
2361             };
2362         }
2363
2364         let buf = self.buf.ptr();
2365         let cap = self.cap();
2366         let len = self.len();
2367
2368         let free = self.tail - self.head;
2369         let tail_len = cap - self.tail;
2370
2371         if free >= tail_len {
2372             // there is enough free space to copy the tail in one go,
2373             // this means that we first shift the head backwards, and then
2374             // copy the tail to the correct position.
2375             //
2376             // from: DEFGH....ABC
2377             // to:   ABCDEFGH....
2378             unsafe {
2379                 ptr::copy(buf, buf.add(tail_len), self.head);
2380                 // ...DEFGH.ABC
2381                 ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
2382                 // ABCDEFGH....
2383
2384                 self.tail = 0;
2385                 self.head = len;
2386             }
2387         } else if free > self.head {
2388             // FIXME: We currently do not consider ....ABCDEFGH
2389             // to be contiguous because `head` would be `0` in this
2390             // case. While we probably want to change this it
2391             // isn't trivial as a few places expect `is_contiguous`
2392             // to mean that we can just slice using `buf[tail..head]`.
2393
2394             // there is enough free space to copy the head in one go,
2395             // this means that we first shift the tail forwards, and then
2396             // copy the head to the correct position.
2397             //
2398             // from: FGH....ABCDE
2399             // to:   ...ABCDEFGH.
2400             unsafe {
2401                 ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
2402                 // FGHABCDE....
2403                 ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
2404                 // ...ABCDEFGH.
2405
2406                 self.tail = self.head;
2407                 self.head = self.wrap_add(self.tail, len);
2408             }
2409         } else {
2410             // free is smaller than both head and tail,
2411             // this means we have to slowly "swap" the tail and the head.
2412             //
2413             // from: EFGHI...ABCD or HIJK.ABCDEFG
2414             // to:   ABCDEFGHI... or ABCDEFGHIJK.
2415             let mut left_edge: usize = 0;
2416             let mut right_edge: usize = self.tail;
2417             unsafe {
2418                 // The general problem looks like this
2419                 // GHIJKLM...ABCDEF - before any swaps
2420                 // ABCDEFM...GHIJKL - after 1 pass of swaps
2421                 // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2422                 //                  - then restart the algorithm with a new (smaller) store
2423                 // Sometimes the temp store is reached when the right edge is at the end
2424                 // of the buffer - this means we've hit the right order with fewer swaps!
2425                 // E.g
2426                 // EF..ABCD
2427                 // ABCDEF.. - after four only swaps we've finished
2428                 while left_edge < len && right_edge != cap {
2429                     let mut right_offset = 0;
2430                     for i in left_edge..right_edge {
2431                         right_offset = (i - left_edge) % (cap - right_edge);
2432                         let src: isize = (right_edge + right_offset) as isize;
2433                         ptr::swap(buf.add(i), buf.offset(src));
2434                     }
2435                     let n_ops = right_edge - left_edge;
2436                     left_edge += n_ops;
2437                     right_edge += right_offset + 1;
2438                 }
2439
2440                 self.tail = 0;
2441                 self.head = len;
2442             }
2443         }
2444
2445         let tail = self.tail;
2446         let head = self.head;
2447         // Safety:
2448         // - `self.head` and `self.tail` in a ring buffer are always valid indices.
2449         // - `RingSlices::ring_slices` guarantees that the slices split according to `self.head` and `self.tail` are initialized.
2450         unsafe {
2451             MaybeUninit::slice_assume_init_mut(
2452                 RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0,
2453             )
2454         }
2455     }
2456
2457     /// Rotates the double-ended queue `mid` places to the left.
2458     ///
2459     /// Equivalently,
2460     /// - Rotates item `mid` into the first position.
2461     /// - Pops the first `mid` items and pushes them to the end.
2462     /// - Rotates `len() - mid` places to the right.
2463     ///
2464     /// # Panics
2465     ///
2466     /// If `mid` is greater than `len()`. Note that `mid == len()`
2467     /// does _not_ panic and is a no-op rotation.
2468     ///
2469     /// # Complexity
2470     ///
2471     /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2472     ///
2473     /// # Examples
2474     ///
2475     /// ```
2476     /// use std::collections::VecDeque;
2477     ///
2478     /// let mut buf: VecDeque<_> = (0..10).collect();
2479     ///
2480     /// buf.rotate_left(3);
2481     /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2482     ///
2483     /// for i in 1..10 {
2484     ///     assert_eq!(i * 3 % 10, buf[0]);
2485     ///     buf.rotate_left(3);
2486     /// }
2487     /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2488     /// ```
2489     #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2490     pub fn rotate_left(&mut self, mid: usize) {
2491         assert!(mid <= self.len());
2492         let k = self.len() - mid;
2493         if mid <= k {
2494             unsafe { self.rotate_left_inner(mid) }
2495         } else {
2496             unsafe { self.rotate_right_inner(k) }
2497         }
2498     }
2499
2500     /// Rotates the double-ended queue `k` places to the right.
2501     ///
2502     /// Equivalently,
2503     /// - Rotates the first item into position `k`.
2504     /// - Pops the last `k` items and pushes them to the front.
2505     /// - Rotates `len() - k` places to the left.
2506     ///
2507     /// # Panics
2508     ///
2509     /// If `k` is greater than `len()`. Note that `k == len()`
2510     /// does _not_ panic and is a no-op rotation.
2511     ///
2512     /// # Complexity
2513     ///
2514     /// Takes `*O*(min(k, len() - k))` time and no extra space.
2515     ///
2516     /// # Examples
2517     ///
2518     /// ```
2519     /// use std::collections::VecDeque;
2520     ///
2521     /// let mut buf: VecDeque<_> = (0..10).collect();
2522     ///
2523     /// buf.rotate_right(3);
2524     /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2525     ///
2526     /// for i in 1..10 {
2527     ///     assert_eq!(0, buf[i * 3 % 10]);
2528     ///     buf.rotate_right(3);
2529     /// }
2530     /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2531     /// ```
2532     #[stable(feature = "vecdeque_rotate", since = "1.36.0")]
2533     pub fn rotate_right(&mut self, k: usize) {
2534         assert!(k <= self.len());
2535         let mid = self.len() - k;
2536         if k <= mid {
2537             unsafe { self.rotate_right_inner(k) }
2538         } else {
2539             unsafe { self.rotate_left_inner(mid) }
2540         }
2541     }
2542
2543     // SAFETY: the following two methods require that the rotation amount
2544     // be less than half the length of the deque.
2545     //
2546     // `wrap_copy` requires that `min(x, cap() - x) + copy_len <= cap()`,
2547     // but than `min` is never more than half the capacity, regardless of x,
2548     // so it's sound to call here because we're calling with something
2549     // less than half the length, which is never above half the capacity.
2550
2551     unsafe fn rotate_left_inner(&mut self, mid: usize) {
2552         debug_assert!(mid * 2 <= self.len());
2553         unsafe {
2554             self.wrap_copy(self.head, self.tail, mid);
2555         }
2556         self.head = self.wrap_add(self.head, mid);
2557         self.tail = self.wrap_add(self.tail, mid);
2558     }
2559
2560     unsafe fn rotate_right_inner(&mut self, k: usize) {
2561         debug_assert!(k * 2 <= self.len());
2562         self.head = self.wrap_sub(self.head, k);
2563         self.tail = self.wrap_sub(self.tail, k);
2564         unsafe {
2565             self.wrap_copy(self.tail, self.head, k);
2566         }
2567     }
2568
2569     /// Binary searches this `VecDeque` for a given element.
2570     /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2571     ///
2572     /// If the value is found then [`Result::Ok`] is returned, containing the
2573     /// index of the matching element. If there are multiple matches, then any
2574     /// one of the matches could be returned. If the value is not found then
2575     /// [`Result::Err`] is returned, containing the index where a matching
2576     /// element could be inserted while maintaining sorted order.
2577     ///
2578     /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2579     ///
2580     /// [`contains`]: VecDeque::contains
2581     /// [`binary_search_by`]: VecDeque::binary_search_by
2582     /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2583     /// [`partition_point`]: VecDeque::partition_point
2584     ///
2585     /// # Examples
2586     ///
2587     /// Looks up a series of four elements. The first is found, with a
2588     /// uniquely determined position; the second and third are not
2589     /// found; the fourth could match any position in `[1, 4]`.
2590     ///
2591     /// ```
2592     /// use std::collections::VecDeque;
2593     ///
2594     /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2595     ///
2596     /// assert_eq!(deque.binary_search(&13),  Ok(9));
2597     /// assert_eq!(deque.binary_search(&4),   Err(7));
2598     /// assert_eq!(deque.binary_search(&100), Err(13));
2599     /// let r = deque.binary_search(&1);
2600     /// assert!(matches!(r, Ok(1..=4)));
2601     /// ```
2602     ///
2603     /// If you want to insert an item to a sorted deque, while maintaining
2604     /// sort order, consider using [`partition_point`]:
2605     ///
2606     /// ```
2607     /// use std::collections::VecDeque;
2608     ///
2609     /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2610     /// let num = 42;
2611     /// let idx = deque.partition_point(|&x| x < num);
2612     /// // The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
2613     /// deque.insert(idx, num);
2614     /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2615     /// ```
2616     #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2617     #[inline]
2618     pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2619     where
2620         T: Ord,
2621     {
2622         self.binary_search_by(|e| e.cmp(x))
2623     }
2624
2625     /// Binary searches this `VecDeque` with a comparator function.
2626     /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2627     ///
2628     /// The comparator function should implement an order consistent
2629     /// with the sort order of the deque, returning an order code that
2630     /// indicates whether its argument is `Less`, `Equal` or `Greater`
2631     /// than the desired target.
2632     ///
2633     /// If the value is found then [`Result::Ok`] is returned, containing the
2634     /// index of the matching element. If there are multiple matches, then any
2635     /// one of the matches could be returned. If the value is not found then
2636     /// [`Result::Err`] is returned, containing the index where a matching
2637     /// element could be inserted while maintaining sorted order.
2638     ///
2639     /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2640     ///
2641     /// [`contains`]: VecDeque::contains
2642     /// [`binary_search`]: VecDeque::binary_search
2643     /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2644     /// [`partition_point`]: VecDeque::partition_point
2645     ///
2646     /// # Examples
2647     ///
2648     /// Looks up a series of four elements. The first is found, with a
2649     /// uniquely determined position; the second and third are not
2650     /// found; the fourth could match any position in `[1, 4]`.
2651     ///
2652     /// ```
2653     /// use std::collections::VecDeque;
2654     ///
2655     /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2656     ///
2657     /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)),  Ok(9));
2658     /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)),   Err(7));
2659     /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2660     /// let r = deque.binary_search_by(|x| x.cmp(&1));
2661     /// assert!(matches!(r, Ok(1..=4)));
2662     /// ```
2663     #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2664     pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2665     where
2666         F: FnMut(&'a T) -> Ordering,
2667     {
2668         let (front, back) = self.as_slices();
2669         let cmp_back = back.first().map(|elem| f(elem));
2670
2671         if let Some(Ordering::Equal) = cmp_back {
2672             Ok(front.len())
2673         } else if let Some(Ordering::Less) = cmp_back {
2674             back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
2675         } else {
2676             front.binary_search_by(f)
2677         }
2678     }
2679
2680     /// Binary searches this `VecDeque` with a key extraction function.
2681     /// This behaves similarly to [`contains`] if this `VecDeque` is sorted.
2682     ///
2683     /// Assumes that the deque is sorted by the key, for instance with
2684     /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2685     ///
2686     /// If the value is found then [`Result::Ok`] is returned, containing the
2687     /// index of the matching element. If there are multiple matches, then any
2688     /// one of the matches could be returned. If the value is not found then
2689     /// [`Result::Err`] is returned, containing the index where a matching
2690     /// element could be inserted while maintaining sorted order.
2691     ///
2692     /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2693     ///
2694     /// [`contains`]: VecDeque::contains
2695     /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2696     /// [`binary_search`]: VecDeque::binary_search
2697     /// [`binary_search_by`]: VecDeque::binary_search_by
2698     /// [`partition_point`]: VecDeque::partition_point
2699     ///
2700     /// # Examples
2701     ///
2702     /// Looks up a series of four elements in a slice of pairs sorted by
2703     /// their second elements. The first is found, with a uniquely
2704     /// determined position; the second and third are not found; the
2705     /// fourth could match any position in `[1, 4]`.
2706     ///
2707     /// ```
2708     /// use std::collections::VecDeque;
2709     ///
2710     /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
2711     ///          (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2712     ///          (1, 21), (2, 34), (4, 55)].into();
2713     ///
2714     /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
2715     /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
2716     /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2717     /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2718     /// assert!(matches!(r, Ok(1..=4)));
2719     /// ```
2720     #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2721     #[inline]
2722     pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2723     where
2724         F: FnMut(&'a T) -> B,
2725         B: Ord,
2726     {
2727         self.binary_search_by(|k| f(k).cmp(b))
2728     }
2729
2730     /// Returns the index of the partition point according to the given predicate
2731     /// (the index of the first element of the second partition).
2732     ///
2733     /// The deque is assumed to be partitioned according to the given predicate.
2734     /// This means that all elements for which the predicate returns true are at the start of the deque
2735     /// and all elements for which the predicate returns false are at the end.
2736     /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2737     /// (all odd numbers are at the start, all even at the end).
2738     ///
2739     /// If the deque is not partitioned, the returned result is unspecified and meaningless,
2740     /// as this method performs a kind of binary search.
2741     ///
2742     /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2743     ///
2744     /// [`binary_search`]: VecDeque::binary_search
2745     /// [`binary_search_by`]: VecDeque::binary_search_by
2746     /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2747     ///
2748     /// # Examples
2749     ///
2750     /// ```
2751     /// use std::collections::VecDeque;
2752     ///
2753     /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
2754     /// let i = deque.partition_point(|&x| x < 5);
2755     ///
2756     /// assert_eq!(i, 4);
2757     /// assert!(deque.iter().take(i).all(|&x| x < 5));
2758     /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2759     /// ```
2760     ///
2761     /// If you want to insert an item to a sorted deque, while maintaining
2762     /// sort order:
2763     ///
2764     /// ```
2765     /// use std::collections::VecDeque;
2766     ///
2767     /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
2768     /// let num = 42;
2769     /// let idx = deque.partition_point(|&x| x < num);
2770     /// deque.insert(idx, num);
2771     /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2772     /// ```
2773     #[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
2774     pub fn partition_point<P>(&self, mut pred: P) -> usize
2775     where
2776         P: FnMut(&T) -> bool,
2777     {
2778         let (front, back) = self.as_slices();
2779
2780         if let Some(true) = back.first().map(|v| pred(v)) {
2781             back.partition_point(pred) + front.len()
2782         } else {
2783             front.partition_point(pred)
2784         }
2785     }
2786 }
2787
2788 impl<T: Clone, A: Allocator> VecDeque<T, A> {
2789     /// Modifies the deque in-place so that `len()` is equal to new_len,
2790     /// either by removing excess elements from the back or by appending clones of `value`
2791     /// to the back.
2792     ///
2793     /// # Examples
2794     ///
2795     /// ```
2796     /// use std::collections::VecDeque;
2797     ///
2798     /// let mut buf = VecDeque::new();
2799     /// buf.push_back(5);
2800     /// buf.push_back(10);
2801     /// buf.push_back(15);
2802     /// assert_eq!(buf, [5, 10, 15]);
2803     ///
2804     /// buf.resize(2, 0);
2805     /// assert_eq!(buf, [5, 10]);
2806     ///
2807     /// buf.resize(5, 20);
2808     /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2809     /// ```
2810     #[stable(feature = "deque_extras", since = "1.16.0")]
2811     pub fn resize(&mut self, new_len: usize, value: T) {
2812         self.resize_with(new_len, || value.clone());
2813     }
2814 }
2815
2816 /// Returns the index in the underlying buffer for a given logical element index.
2817 #[inline]
2818 fn wrap_index(index: usize, size: usize) -> usize {
2819     // size is always a power of 2
2820     debug_assert!(size.is_power_of_two());
2821     index & (size - 1)
2822 }
2823
2824 /// Calculate the number of elements left to be read in the buffer
2825 #[inline]
2826 fn count(tail: usize, head: usize, size: usize) -> usize {
2827     // size is always a power of 2
2828     (head.wrapping_sub(tail)) & (size - 1)
2829 }
2830
2831 #[stable(feature = "rust1", since = "1.0.0")]
2832 impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
2833     fn eq(&self, other: &Self) -> bool {
2834         if self.len() != other.len() {
2835             return false;
2836         }
2837         let (sa, sb) = self.as_slices();
2838         let (oa, ob) = other.as_slices();
2839         if sa.len() == oa.len() {
2840             sa == oa && sb == ob
2841         } else if sa.len() < oa.len() {
2842             // Always divisible in three sections, for example:
2843             // self:  [a b c|d e f]
2844             // other: [0 1 2 3|4 5]
2845             // front = 3, mid = 1,
2846             // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2847             let front = sa.len();
2848             let mid = oa.len() - front;
2849
2850             let (oa_front, oa_mid) = oa.split_at(front);
2851             let (sb_mid, sb_back) = sb.split_at(mid);
2852             debug_assert_eq!(sa.len(), oa_front.len());
2853             debug_assert_eq!(sb_mid.len(), oa_mid.len());
2854             debug_assert_eq!(sb_back.len(), ob.len());
2855             sa == oa_front && sb_mid == oa_mid && sb_back == ob
2856         } else {
2857             let front = oa.len();
2858             let mid = sa.len() - front;
2859
2860             let (sa_front, sa_mid) = sa.split_at(front);
2861             let (ob_mid, ob_back) = ob.split_at(mid);
2862             debug_assert_eq!(sa_front.len(), oa.len());
2863             debug_assert_eq!(sa_mid.len(), ob_mid.len());
2864             debug_assert_eq!(sb.len(), ob_back.len());
2865             sa_front == oa && sa_mid == ob_mid && sb == ob_back
2866         }
2867     }
2868 }
2869
2870 #[stable(feature = "rust1", since = "1.0.0")]
2871 impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
2872
2873 __impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2874 __impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2875 __impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2876 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2877 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2878 __impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2879
2880 #[stable(feature = "rust1", since = "1.0.0")]
2881 impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
2882     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2883         self.iter().partial_cmp(other.iter())
2884     }
2885 }
2886
2887 #[stable(feature = "rust1", since = "1.0.0")]
2888 impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
2889     #[inline]
2890     fn cmp(&self, other: &Self) -> Ordering {
2891         self.iter().cmp(other.iter())
2892     }
2893 }
2894
2895 #[stable(feature = "rust1", since = "1.0.0")]
2896 impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
2897     fn hash<H: Hasher>(&self, state: &mut H) {
2898         self.len().hash(state);
2899         // It's not possible to use Hash::hash_slice on slices
2900         // returned by as_slices method as their length can vary
2901         // in otherwise identical deques.
2902         //
2903         // Hasher only guarantees equivalence for the exact same
2904         // set of calls to its methods.
2905         self.iter().for_each(|elem| elem.hash(state));
2906     }
2907 }
2908
2909 #[stable(feature = "rust1", since = "1.0.0")]
2910 impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
2911     type Output = T;
2912
2913     #[inline]
2914     fn index(&self, index: usize) -> &T {
2915         self.get(index).expect("Out of bounds access")
2916     }
2917 }
2918
2919 #[stable(feature = "rust1", since = "1.0.0")]
2920 impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
2921     #[inline]
2922     fn index_mut(&mut self, index: usize) -> &mut T {
2923         self.get_mut(index).expect("Out of bounds access")
2924     }
2925 }
2926
2927 #[stable(feature = "rust1", since = "1.0.0")]
2928 impl<T> FromIterator<T> for VecDeque<T> {
2929     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
2930         let iterator = iter.into_iter();
2931         let (lower, _) = iterator.size_hint();
2932         let mut deq = VecDeque::with_capacity(lower);
2933         deq.extend(iterator);
2934         deq
2935     }
2936 }
2937
2938 #[stable(feature = "rust1", since = "1.0.0")]
2939 impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
2940     type Item = T;
2941     type IntoIter = IntoIter<T, A>;
2942
2943     /// Consumes the deque into a front-to-back iterator yielding elements by
2944     /// value.
2945     fn into_iter(self) -> IntoIter<T, A> {
2946         IntoIter::new(self)
2947     }
2948 }
2949
2950 #[stable(feature = "rust1", since = "1.0.0")]
2951 impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
2952     type Item = &'a T;
2953     type IntoIter = Iter<'a, T>;
2954
2955     fn into_iter(self) -> Iter<'a, T> {
2956         self.iter()
2957     }
2958 }
2959
2960 #[stable(feature = "rust1", since = "1.0.0")]
2961 impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
2962     type Item = &'a mut T;
2963     type IntoIter = IterMut<'a, T>;
2964
2965     fn into_iter(self) -> IterMut<'a, T> {
2966         self.iter_mut()
2967     }
2968 }
2969
2970 #[stable(feature = "rust1", since = "1.0.0")]
2971 impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
2972     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2973         // This function should be the moral equivalent of:
2974         //
2975         //      for item in iter.into_iter() {
2976         //          self.push_back(item);
2977         //      }
2978         let mut iter = iter.into_iter();
2979         while let Some(element) = iter.next() {
2980             if self.len() == self.capacity() {
2981                 let (lower, _) = iter.size_hint();
2982                 self.reserve(lower.saturating_add(1));
2983             }
2984
2985             let head = self.head;
2986             self.head = self.wrap_add(self.head, 1);
2987             unsafe {
2988                 self.buffer_write(head, element);
2989             }
2990         }
2991     }
2992
2993     #[inline]
2994     fn extend_one(&mut self, elem: T) {
2995         self.push_back(elem);
2996     }
2997
2998     #[inline]
2999     fn extend_reserve(&mut self, additional: usize) {
3000         self.reserve(additional);
3001     }
3002 }
3003
3004 #[stable(feature = "extend_ref", since = "1.2.0")]
3005 impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
3006     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3007         self.extend(iter.into_iter().cloned());
3008     }
3009
3010     #[inline]
3011     fn extend_one(&mut self, &elem: &T) {
3012         self.push_back(elem);
3013     }
3014
3015     #[inline]
3016     fn extend_reserve(&mut self, additional: usize) {
3017         self.reserve(additional);
3018     }
3019 }
3020
3021 #[stable(feature = "rust1", since = "1.0.0")]
3022 impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
3023     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3024         f.debug_list().entries(self).finish()
3025     }
3026 }
3027
3028 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3029 impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
3030     /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
3031     ///
3032     /// [`Vec<T>`]: crate::vec::Vec
3033     /// [`VecDeque<T>`]: crate::collections::VecDeque
3034     ///
3035     /// This avoids reallocating where possible, but the conditions for that are
3036     /// strict, and subject to change, and so shouldn't be relied upon unless the
3037     /// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
3038     fn from(mut other: Vec<T, A>) -> Self {
3039         let len = other.len();
3040         if mem::size_of::<T>() == 0 {
3041             // There's no actual allocation for ZSTs to worry about capacity,
3042             // but `VecDeque` can't handle as much length as `Vec`.
3043             assert!(len < MAXIMUM_ZST_CAPACITY, "capacity overflow");
3044         } else {
3045             // We need to resize if the capacity is not a power of two, too small or
3046             // doesn't have at least one free space. We do this while it's still in
3047             // the `Vec` so the items will drop on panic.
3048             let min_cap = cmp::max(MINIMUM_CAPACITY, len) + 1;
3049             let cap = cmp::max(min_cap, other.capacity()).next_power_of_two();
3050             if other.capacity() != cap {
3051                 other.reserve_exact(cap - len);
3052             }
3053         }
3054
3055         unsafe {
3056             let (other_buf, len, capacity, alloc) = other.into_raw_parts_with_alloc();
3057             let buf = RawVec::from_raw_parts_in(other_buf, capacity, alloc);
3058             VecDeque { tail: 0, head: len, buf }
3059         }
3060     }
3061 }
3062
3063 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
3064 impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
3065     /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
3066     ///
3067     /// [`Vec<T>`]: crate::vec::Vec
3068     /// [`VecDeque<T>`]: crate::collections::VecDeque
3069     ///
3070     /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
3071     /// the circular buffer doesn't happen to be at the beginning of the allocation.
3072     ///
3073     /// # Examples
3074     ///
3075     /// ```
3076     /// use std::collections::VecDeque;
3077     ///
3078     /// // This one is *O*(1).
3079     /// let deque: VecDeque<_> = (1..5).collect();
3080     /// let ptr = deque.as_slices().0.as_ptr();
3081     /// let vec = Vec::from(deque);
3082     /// assert_eq!(vec, [1, 2, 3, 4]);
3083     /// assert_eq!(vec.as_ptr(), ptr);
3084     ///
3085     /// // This one needs data rearranging.
3086     /// let mut deque: VecDeque<_> = (1..5).collect();
3087     /// deque.push_front(9);
3088     /// deque.push_front(8);
3089     /// let ptr = deque.as_slices().1.as_ptr();
3090     /// let vec = Vec::from(deque);
3091     /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
3092     /// assert_eq!(vec.as_ptr(), ptr);
3093     /// ```
3094     fn from(mut other: VecDeque<T, A>) -> Self {
3095         other.make_contiguous();
3096
3097         unsafe {
3098             let other = ManuallyDrop::new(other);
3099             let buf = other.buf.ptr();
3100             let len = other.len();
3101             let cap = other.cap();
3102             let alloc = ptr::read(other.allocator());
3103
3104             if other.tail != 0 {
3105                 ptr::copy(buf.add(other.tail), buf, len);
3106             }
3107             Vec::from_raw_parts_in(buf, len, cap, alloc)
3108         }
3109     }
3110 }
3111
3112 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
3113 impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
3114     /// Converts a `[T; N]` into a `VecDeque<T>`.
3115     ///
3116     /// ```
3117     /// use std::collections::VecDeque;
3118     ///
3119     /// let deq1 = VecDeque::from([1, 2, 3, 4]);
3120     /// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
3121     /// assert_eq!(deq1, deq2);
3122     /// ```
3123     fn from(arr: [T; N]) -> Self {
3124         let mut deq = VecDeque::with_capacity(N);
3125         let arr = ManuallyDrop::new(arr);
3126         if mem::size_of::<T>() != 0 {
3127             // SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
3128             unsafe {
3129                 ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);
3130             }
3131         }
3132         deq.tail = 0;
3133         deq.head = N;
3134         deq
3135     }
3136 }