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