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