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