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