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