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