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