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