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