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