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