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