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