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