]> git.lizzy.rs Git - rust.git/blob - src/liballoc/collections/vec_deque.rs
Rollup merge of #60945 - blkerby:fill_buf_nll_doc_example, r=shepmaster
[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.cap()
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_cap.
318     #[inline]
319     unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
320         let new_cap = 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_cap - self.tail {
340             // B
341             self.copy_nonoverlapping(old_cap, 0, self.head);
342             self.head += old_cap;
343             debug_assert!(self.head > self.tail);
344         } else {
345             // C
346             let new_tail = new_cap - (old_cap - self.tail);
347             self.copy_nonoverlapping(new_tail, self.tail, old_cap - 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_cap_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_cap_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_cap_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
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2213     #[inline]
2214     fn next_back(&mut self) -> Option<&'a T> {
2215         if self.tail == self.head {
2216             return None;
2217         }
2218         self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2219         unsafe { Some(self.ring.get_unchecked(self.head)) }
2220     }
2221
2222     fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2223         where F: FnMut(Acc, Self::Item) -> Acc
2224     {
2225         let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2226         accum = back.iter().rfold(accum, &mut f);
2227         front.iter().rfold(accum, &mut f)
2228     }
2229
2230     fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
2231     where
2232         Self: Sized,
2233         F: FnMut(B, Self::Item) -> R,
2234         R: Try<Ok = B>,
2235     {
2236         let (mut iter, final_res);
2237         if self.tail <= self.head {
2238             // single slice self.ring[self.tail..self.head]
2239             iter = self.ring[self.tail..self.head].iter();
2240             final_res = iter.try_rfold(init, &mut f);
2241         } else {
2242             // two slices: self.ring[self.tail..], self.ring[..self.head]
2243             let (front, back) = self.ring.split_at(self.tail);
2244             let mut front_iter = front[..self.head].iter();
2245             let res = front_iter.try_rfold(init, &mut f);
2246             self.head = front_iter.len();
2247             iter = back.iter();
2248             final_res = iter.try_rfold(res?, &mut f);
2249         }
2250         self.head = self.tail + iter.len();
2251         final_res
2252     }
2253 }
2254
2255 #[stable(feature = "rust1", since = "1.0.0")]
2256 impl<T> ExactSizeIterator for Iter<'_, T> {
2257     fn is_empty(&self) -> bool {
2258         self.head == self.tail
2259     }
2260 }
2261
2262 #[stable(feature = "fused", since = "1.26.0")]
2263 impl<T> FusedIterator for Iter<'_, T> {}
2264
2265
2266 /// A mutable iterator over the elements of a `VecDeque`.
2267 ///
2268 /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its
2269 /// documentation for more.
2270 ///
2271 /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut
2272 /// [`VecDeque`]: struct.VecDeque.html
2273 #[stable(feature = "rust1", since = "1.0.0")]
2274 pub struct IterMut<'a, T: 'a> {
2275     ring: &'a mut [T],
2276     tail: usize,
2277     head: usize,
2278 }
2279
2280 #[stable(feature = "collection_debug", since = "1.17.0")]
2281 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
2282     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2283         let (front, back) = RingSlices::ring_slices(&*self.ring, self.head, self.tail);
2284         f.debug_tuple("IterMut")
2285             .field(&front)
2286             .field(&back)
2287             .finish()
2288     }
2289 }
2290
2291 #[stable(feature = "rust1", since = "1.0.0")]
2292 impl<'a, T> Iterator for IterMut<'a, T> {
2293     type Item = &'a mut T;
2294
2295     #[inline]
2296     fn next(&mut self) -> Option<&'a mut T> {
2297         if self.tail == self.head {
2298             return None;
2299         }
2300         let tail = self.tail;
2301         self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
2302
2303         unsafe {
2304             let elem = self.ring.get_unchecked_mut(tail);
2305             Some(&mut *(elem as *mut _))
2306         }
2307     }
2308
2309     #[inline]
2310     fn size_hint(&self) -> (usize, Option<usize>) {
2311         let len = count(self.tail, self.head, self.ring.len());
2312         (len, Some(len))
2313     }
2314
2315     fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2316         where F: FnMut(Acc, Self::Item) -> Acc
2317     {
2318         let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2319         accum = front.iter_mut().fold(accum, &mut f);
2320         back.iter_mut().fold(accum, &mut f)
2321     }
2322 }
2323
2324 #[stable(feature = "rust1", since = "1.0.0")]
2325 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2326     #[inline]
2327     fn next_back(&mut self) -> Option<&'a mut T> {
2328         if self.tail == self.head {
2329             return None;
2330         }
2331         self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
2332
2333         unsafe {
2334             let elem = self.ring.get_unchecked_mut(self.head);
2335             Some(&mut *(elem as *mut _))
2336         }
2337     }
2338
2339     fn rfold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
2340         where F: FnMut(Acc, Self::Item) -> Acc
2341     {
2342         let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
2343         accum = back.iter_mut().rfold(accum, &mut f);
2344         front.iter_mut().rfold(accum, &mut f)
2345     }
2346 }
2347
2348 #[stable(feature = "rust1", since = "1.0.0")]
2349 impl<T> ExactSizeIterator for IterMut<'_, T> {
2350     fn is_empty(&self) -> bool {
2351         self.head == self.tail
2352     }
2353 }
2354
2355 #[stable(feature = "fused", since = "1.26.0")]
2356 impl<T> FusedIterator for IterMut<'_, T> {}
2357
2358 /// An owning iterator over the elements of a `VecDeque`.
2359 ///
2360 /// This `struct` is created by the [`into_iter`] method on [`VecDeque`][`VecDeque`]
2361 /// (provided by the `IntoIterator` trait). See its documentation for more.
2362 ///
2363 /// [`into_iter`]: struct.VecDeque.html#method.into_iter
2364 /// [`VecDeque`]: struct.VecDeque.html
2365 #[derive(Clone)]
2366 #[stable(feature = "rust1", since = "1.0.0")]
2367 pub struct IntoIter<T> {
2368     inner: VecDeque<T>,
2369 }
2370
2371 #[stable(feature = "collection_debug", since = "1.17.0")]
2372 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2373     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2374         f.debug_tuple("IntoIter")
2375          .field(&self.inner)
2376          .finish()
2377     }
2378 }
2379
2380 #[stable(feature = "rust1", since = "1.0.0")]
2381 impl<T> Iterator for IntoIter<T> {
2382     type Item = T;
2383
2384     #[inline]
2385     fn next(&mut self) -> Option<T> {
2386         self.inner.pop_front()
2387     }
2388
2389     #[inline]
2390     fn size_hint(&self) -> (usize, Option<usize>) {
2391         let len = self.inner.len();
2392         (len, Some(len))
2393     }
2394 }
2395
2396 #[stable(feature = "rust1", since = "1.0.0")]
2397 impl<T> DoubleEndedIterator for IntoIter<T> {
2398     #[inline]
2399     fn next_back(&mut self) -> Option<T> {
2400         self.inner.pop_back()
2401     }
2402 }
2403
2404 #[stable(feature = "rust1", since = "1.0.0")]
2405 impl<T> ExactSizeIterator for IntoIter<T> {
2406     fn is_empty(&self) -> bool {
2407         self.inner.is_empty()
2408     }
2409 }
2410
2411 #[stable(feature = "fused", since = "1.26.0")]
2412 impl<T> FusedIterator for IntoIter<T> {}
2413
2414 /// A draining iterator over the elements of a `VecDeque`.
2415 ///
2416 /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its
2417 /// documentation for more.
2418 ///
2419 /// [`drain`]: struct.VecDeque.html#method.drain
2420 /// [`VecDeque`]: struct.VecDeque.html
2421 #[stable(feature = "drain", since = "1.6.0")]
2422 pub struct Drain<'a, T: 'a> {
2423     after_tail: usize,
2424     after_head: usize,
2425     iter: Iter<'a, T>,
2426     deque: NonNull<VecDeque<T>>,
2427 }
2428
2429 #[stable(feature = "collection_debug", since = "1.17.0")]
2430 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2431     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2432         f.debug_tuple("Drain")
2433          .field(&self.after_tail)
2434          .field(&self.after_head)
2435          .field(&self.iter)
2436          .finish()
2437     }
2438 }
2439
2440 #[stable(feature = "drain", since = "1.6.0")]
2441 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2442 #[stable(feature = "drain", since = "1.6.0")]
2443 unsafe impl<T: Send> Send for Drain<'_, T> {}
2444
2445 #[stable(feature = "drain", since = "1.6.0")]
2446 impl<T> Drop for Drain<'_, T> {
2447     fn drop(&mut self) {
2448         self.for_each(drop);
2449
2450         let source_deque = unsafe { self.deque.as_mut() };
2451
2452         // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2453         //
2454         //        T   t   h   H
2455         // [. . . o o x x o o . . .]
2456         //
2457         let orig_tail = source_deque.tail;
2458         let drain_tail = source_deque.head;
2459         let drain_head = self.after_tail;
2460         let orig_head = self.after_head;
2461
2462         let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2463         let head_len = count(drain_head, orig_head, source_deque.cap());
2464
2465         // Restore the original head value
2466         source_deque.head = orig_head;
2467
2468         match (tail_len, head_len) {
2469             (0, 0) => {
2470                 source_deque.head = 0;
2471                 source_deque.tail = 0;
2472             }
2473             (0, _) => {
2474                 source_deque.tail = drain_head;
2475             }
2476             (_, 0) => {
2477                 source_deque.head = drain_tail;
2478             }
2479             _ => unsafe {
2480                 if tail_len <= head_len {
2481                     source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2482                     source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2483                 } else {
2484                     source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2485                     source_deque.wrap_copy(drain_tail, drain_head, head_len);
2486                 }
2487             },
2488         }
2489     }
2490 }
2491
2492 #[stable(feature = "drain", since = "1.6.0")]
2493 impl<T> Iterator for Drain<'_, T> {
2494     type Item = T;
2495
2496     #[inline]
2497     fn next(&mut self) -> Option<T> {
2498         self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2499     }
2500
2501     #[inline]
2502     fn size_hint(&self) -> (usize, Option<usize>) {
2503         self.iter.size_hint()
2504     }
2505 }
2506
2507 #[stable(feature = "drain", since = "1.6.0")]
2508 impl<T> DoubleEndedIterator for Drain<'_, T> {
2509     #[inline]
2510     fn next_back(&mut self) -> Option<T> {
2511         self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2512     }
2513 }
2514
2515 #[stable(feature = "drain", since = "1.6.0")]
2516 impl<T> ExactSizeIterator for Drain<'_, T> {}
2517
2518 #[stable(feature = "fused", since = "1.26.0")]
2519 impl<T> FusedIterator for Drain<'_, T> {}
2520
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 impl<A: PartialEq> PartialEq for VecDeque<A> {
2523     fn eq(&self, other: &VecDeque<A>) -> bool {
2524         if self.len() != other.len() {
2525             return false;
2526         }
2527         let (sa, sb) = self.as_slices();
2528         let (oa, ob) = other.as_slices();
2529         if sa.len() == oa.len() {
2530             sa == oa && sb == ob
2531         } else if sa.len() < oa.len() {
2532             // Always divisible in three sections, for example:
2533             // self:  [a b c|d e f]
2534             // other: [0 1 2 3|4 5]
2535             // front = 3, mid = 1,
2536             // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2537             let front = sa.len();
2538             let mid = oa.len() - front;
2539
2540             let (oa_front, oa_mid) = oa.split_at(front);
2541             let (sb_mid, sb_back) = sb.split_at(mid);
2542             debug_assert_eq!(sa.len(), oa_front.len());
2543             debug_assert_eq!(sb_mid.len(), oa_mid.len());
2544             debug_assert_eq!(sb_back.len(), ob.len());
2545             sa == oa_front && sb_mid == oa_mid && sb_back == ob
2546         } else {
2547             let front = oa.len();
2548             let mid = sa.len() - front;
2549
2550             let (sa_front, sa_mid) = sa.split_at(front);
2551             let (ob_mid, ob_back) = ob.split_at(mid);
2552             debug_assert_eq!(sa_front.len(), oa.len());
2553             debug_assert_eq!(sa_mid.len(), ob_mid.len());
2554             debug_assert_eq!(sb.len(), ob_back.len());
2555             sa_front == oa && sa_mid == ob_mid && sb == ob_back
2556         }
2557     }
2558 }
2559
2560 #[stable(feature = "rust1", since = "1.0.0")]
2561 impl<A: Eq> Eq for VecDeque<A> {}
2562
2563 macro_rules! __impl_slice_eq1 {
2564     ($Lhs: ty, $Rhs: ty) => {
2565         __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2566     };
2567     ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2568         #[stable(feature = "vec_deque_partial_eq_slice", since = "1.17.0")]
2569         impl<A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2570             fn eq(&self, other: &$Rhs) -> bool {
2571                 if self.len() != other.len() {
2572                     return false;
2573                 }
2574                 let (sa, sb) = self.as_slices();
2575                 let (oa, ob) = other[..].split_at(sa.len());
2576                 sa == oa && sb == ob
2577             }
2578         }
2579     }
2580 }
2581
2582 __impl_slice_eq1! { VecDeque<A>, Vec<B> }
2583 __impl_slice_eq1! { VecDeque<A>, &[B] }
2584 __impl_slice_eq1! { VecDeque<A>, &mut [B] }
2585
2586 macro_rules! array_impls {
2587     ($($N: expr)+) => {
2588         $(
2589             __impl_slice_eq1! { VecDeque<A>, [B; $N] }
2590             __impl_slice_eq1! { VecDeque<A>, &[B; $N] }
2591             __impl_slice_eq1! { VecDeque<A>, &mut [B; $N] }
2592         )+
2593     }
2594 }
2595
2596 array_impls! {
2597      0  1  2  3  4  5  6  7  8  9
2598     10 11 12 13 14 15 16 17 18 19
2599     20 21 22 23 24 25 26 27 28 29
2600     30 31 32
2601 }
2602
2603 #[stable(feature = "rust1", since = "1.0.0")]
2604 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2605     fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2606         self.iter().partial_cmp(other.iter())
2607     }
2608 }
2609
2610 #[stable(feature = "rust1", since = "1.0.0")]
2611 impl<A: Ord> Ord for VecDeque<A> {
2612     #[inline]
2613     fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2614         self.iter().cmp(other.iter())
2615     }
2616 }
2617
2618 #[stable(feature = "rust1", since = "1.0.0")]
2619 impl<A: Hash> Hash for VecDeque<A> {
2620     fn hash<H: Hasher>(&self, state: &mut H) {
2621         self.len().hash(state);
2622         let (a, b) = self.as_slices();
2623         Hash::hash_slice(a, state);
2624         Hash::hash_slice(b, state);
2625     }
2626 }
2627
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 impl<A> Index<usize> for VecDeque<A> {
2630     type Output = A;
2631
2632     #[inline]
2633     fn index(&self, index: usize) -> &A {
2634         self.get(index).expect("Out of bounds access")
2635     }
2636 }
2637
2638 #[stable(feature = "rust1", since = "1.0.0")]
2639 impl<A> IndexMut<usize> for VecDeque<A> {
2640     #[inline]
2641     fn index_mut(&mut self, index: usize) -> &mut A {
2642         self.get_mut(index).expect("Out of bounds access")
2643     }
2644 }
2645
2646 #[stable(feature = "rust1", since = "1.0.0")]
2647 impl<A> FromIterator<A> for VecDeque<A> {
2648     fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2649         let iterator = iter.into_iter();
2650         let (lower, _) = iterator.size_hint();
2651         let mut deq = VecDeque::with_capacity(lower);
2652         deq.extend(iterator);
2653         deq
2654     }
2655 }
2656
2657 #[stable(feature = "rust1", since = "1.0.0")]
2658 impl<T> IntoIterator for VecDeque<T> {
2659     type Item = T;
2660     type IntoIter = IntoIter<T>;
2661
2662     /// Consumes the `VecDeque` into a front-to-back iterator yielding elements by
2663     /// value.
2664     fn into_iter(self) -> IntoIter<T> {
2665         IntoIter { inner: self }
2666     }
2667 }
2668
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2671     type Item = &'a T;
2672     type IntoIter = Iter<'a, T>;
2673
2674     fn into_iter(self) -> Iter<'a, T> {
2675         self.iter()
2676     }
2677 }
2678
2679 #[stable(feature = "rust1", since = "1.0.0")]
2680 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2681     type Item = &'a mut T;
2682     type IntoIter = IterMut<'a, T>;
2683
2684     fn into_iter(self) -> IterMut<'a, T> {
2685         self.iter_mut()
2686     }
2687 }
2688
2689 #[stable(feature = "rust1", since = "1.0.0")]
2690 impl<A> Extend<A> for VecDeque<A> {
2691     fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2692         iter.into_iter().for_each(move |elt| self.push_back(elt));
2693     }
2694 }
2695
2696 #[stable(feature = "extend_ref", since = "1.2.0")]
2697 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2698     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2699         self.extend(iter.into_iter().cloned());
2700     }
2701 }
2702
2703 #[stable(feature = "rust1", since = "1.0.0")]
2704 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2705     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2706         f.debug_list().entries(self).finish()
2707     }
2708 }
2709
2710 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2711 impl<T> From<Vec<T>> for VecDeque<T> {
2712     fn from(mut other: Vec<T>) -> Self {
2713         unsafe {
2714             let other_buf = other.as_mut_ptr();
2715             let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2716             let len = other.len();
2717             mem::forget(other);
2718
2719             // We need to extend the buf if it's not a power of two, too small
2720             // or doesn't have at least one free space
2721             if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) ||
2722                (buf.cap() == len) {
2723                 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2724                 buf.reserve_exact(len, cap - len);
2725             }
2726
2727             VecDeque {
2728                 tail: 0,
2729                 head: len,
2730                 buf,
2731             }
2732         }
2733     }
2734 }
2735
2736 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2737 impl<T> From<VecDeque<T>> for Vec<T> {
2738     fn from(other: VecDeque<T>) -> Self {
2739         unsafe {
2740             let buf = other.buf.ptr();
2741             let len = other.len();
2742             let tail = other.tail;
2743             let head = other.head;
2744             let cap = other.cap();
2745
2746             // Need to move the ring to the front of the buffer, as vec will expect this.
2747             if other.is_contiguous() {
2748                 ptr::copy(buf.add(tail), buf, len);
2749             } else {
2750                 if (tail - head) >= cmp::min(cap - tail, head) {
2751                     // There is enough free space in the centre for the shortest block so we can
2752                     // do this in at most three copy moves.
2753                     if (cap - tail) > head {
2754                         // right hand block is the long one; move that enough for the left
2755                         ptr::copy(buf.add(tail),
2756                                   buf.add(tail - head),
2757                                   cap - tail);
2758                         // copy left in the end
2759                         ptr::copy(buf, buf.add(cap - head), head);
2760                         // shift the new thing to the start
2761                         ptr::copy(buf.add(tail - head), buf, len);
2762                     } else {
2763                         // left hand block is the long one, we can do it in two!
2764                         ptr::copy(buf, buf.add(cap - tail), head);
2765                         ptr::copy(buf.add(tail), buf, cap - tail);
2766                     }
2767                 } else {
2768                     // Need to use N swaps to move the ring
2769                     // We can use the space at the end of the ring as a temp store
2770
2771                     let mut left_edge: usize = 0;
2772                     let mut right_edge: usize = tail;
2773
2774                     // The general problem looks like this
2775                     // GHIJKLM...ABCDEF - before any swaps
2776                     // ABCDEFM...GHIJKL - after 1 pass of swaps
2777                     // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2778                     //                  - then restart the algorithm with a new (smaller) store
2779                     // Sometimes the temp store is reached when the right edge is at the end
2780                     // of the buffer - this means we've hit the right order with fewer swaps!
2781                     // E.g
2782                     // EF..ABCD
2783                     // ABCDEF.. - after four only swaps we've finished
2784
2785                     while left_edge < len && right_edge != cap {
2786                         let mut right_offset = 0;
2787                         for i in left_edge..right_edge {
2788                             right_offset = (i - left_edge) % (cap - right_edge);
2789                             let src: isize = (right_edge + right_offset) as isize;
2790                             ptr::swap(buf.add(i), buf.offset(src));
2791                         }
2792                         let n_ops = right_edge - left_edge;
2793                         left_edge += n_ops;
2794                         right_edge += right_offset + 1;
2795
2796                     }
2797                 }
2798
2799             }
2800             let out = Vec::from_raw_parts(buf, len, cap);
2801             mem::forget(other);
2802             out
2803         }
2804     }
2805 }
2806
2807 #[cfg(test)]
2808 mod tests {
2809     use ::test;
2810
2811     use super::VecDeque;
2812
2813     #[bench]
2814     #[cfg(not(miri))] // Miri does not support benchmarks
2815     fn bench_push_back_100(b: &mut test::Bencher) {
2816         let mut deq = VecDeque::with_capacity(101);
2817         b.iter(|| {
2818             for i in 0..100 {
2819                 deq.push_back(i);
2820             }
2821             deq.head = 0;
2822             deq.tail = 0;
2823         })
2824     }
2825
2826     #[bench]
2827     #[cfg(not(miri))] // Miri does not support benchmarks
2828     fn bench_push_front_100(b: &mut test::Bencher) {
2829         let mut deq = VecDeque::with_capacity(101);
2830         b.iter(|| {
2831             for i in 0..100 {
2832                 deq.push_front(i);
2833             }
2834             deq.head = 0;
2835             deq.tail = 0;
2836         })
2837     }
2838
2839     #[bench]
2840     #[cfg(not(miri))] // Miri does not support benchmarks
2841     fn bench_pop_back_100(b: &mut test::Bencher) {
2842         let mut deq = VecDeque::<i32>::with_capacity(101);
2843
2844         b.iter(|| {
2845             deq.head = 100;
2846             deq.tail = 0;
2847             while !deq.is_empty() {
2848                 test::black_box(deq.pop_back());
2849             }
2850         })
2851     }
2852
2853     #[bench]
2854     #[cfg(not(miri))] // Miri does not support benchmarks
2855     fn bench_pop_front_100(b: &mut test::Bencher) {
2856         let mut deq = VecDeque::<i32>::with_capacity(101);
2857
2858         b.iter(|| {
2859             deq.head = 100;
2860             deq.tail = 0;
2861             while !deq.is_empty() {
2862                 test::black_box(deq.pop_front());
2863             }
2864         })
2865     }
2866
2867     #[test]
2868     fn test_swap_front_back_remove() {
2869         fn test(back: bool) {
2870             // This test checks that every single combination of tail position and length is tested.
2871             // Capacity 15 should be large enough to cover every case.
2872             let mut tester = VecDeque::with_capacity(15);
2873             let usable_cap = tester.capacity();
2874             let final_len = usable_cap / 2;
2875
2876             for len in 0..final_len {
2877                 let expected: VecDeque<_> = if back {
2878                     (0..len).collect()
2879                 } else {
2880                     (0..len).rev().collect()
2881                 };
2882                 for tail_pos in 0..usable_cap {
2883                     tester.tail = tail_pos;
2884                     tester.head = tail_pos;
2885                     if back {
2886                         for i in 0..len * 2 {
2887                             tester.push_front(i);
2888                         }
2889                         for i in 0..len {
2890                             assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2891                         }
2892                     } else {
2893                         for i in 0..len * 2 {
2894                             tester.push_back(i);
2895                         }
2896                         for i in 0..len {
2897                             let idx = tester.len() - 1 - i;
2898                             assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2899                         }
2900                     }
2901                     assert!(tester.tail < tester.cap());
2902                     assert!(tester.head < tester.cap());
2903                     assert_eq!(tester, expected);
2904                 }
2905             }
2906         }
2907         test(true);
2908         test(false);
2909     }
2910
2911     #[test]
2912     fn test_insert() {
2913         // This test checks that every single combination of tail position, length, and
2914         // insertion position is tested. Capacity 15 should be large enough to cover every case.
2915
2916         let mut tester = VecDeque::with_capacity(15);
2917         // can't guarantee we got 15, so have to get what we got.
2918         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2919         // this test isn't covering what it wants to
2920         let cap = tester.capacity();
2921
2922
2923         // len is the length *after* insertion
2924         for len in 1..cap {
2925             // 0, 1, 2, .., len - 1
2926             let expected = (0..).take(len).collect::<VecDeque<_>>();
2927             for tail_pos in 0..cap {
2928                 for to_insert in 0..len {
2929                     tester.tail = tail_pos;
2930                     tester.head = tail_pos;
2931                     for i in 0..len {
2932                         if i != to_insert {
2933                             tester.push_back(i);
2934                         }
2935                     }
2936                     tester.insert(to_insert, to_insert);
2937                     assert!(tester.tail < tester.cap());
2938                     assert!(tester.head < tester.cap());
2939                     assert_eq!(tester, expected);
2940                 }
2941             }
2942         }
2943     }
2944
2945     #[test]
2946     fn test_remove() {
2947         // This test checks that every single combination of tail position, length, and
2948         // removal position is tested. Capacity 15 should be large enough to cover every case.
2949
2950         let mut tester = VecDeque::with_capacity(15);
2951         // can't guarantee we got 15, so have to get what we got.
2952         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2953         // this test isn't covering what it wants to
2954         let cap = tester.capacity();
2955
2956         // len is the length *after* removal
2957         for len in 0..cap - 1 {
2958             // 0, 1, 2, .., len - 1
2959             let expected = (0..).take(len).collect::<VecDeque<_>>();
2960             for tail_pos in 0..cap {
2961                 for to_remove in 0..=len {
2962                     tester.tail = tail_pos;
2963                     tester.head = tail_pos;
2964                     for i in 0..len {
2965                         if i == to_remove {
2966                             tester.push_back(1234);
2967                         }
2968                         tester.push_back(i);
2969                     }
2970                     if to_remove == len {
2971                         tester.push_back(1234);
2972                     }
2973                     tester.remove(to_remove);
2974                     assert!(tester.tail < tester.cap());
2975                     assert!(tester.head < tester.cap());
2976                     assert_eq!(tester, expected);
2977                 }
2978             }
2979         }
2980     }
2981
2982     #[test]
2983     fn test_drain() {
2984         let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2985
2986         let cap = tester.capacity();
2987         for len in 0..=cap {
2988             for tail in 0..=cap {
2989                 for drain_start in 0..=len {
2990                     for drain_end in drain_start..=len {
2991                         tester.tail = tail;
2992                         tester.head = tail;
2993                         for i in 0..len {
2994                             tester.push_back(i);
2995                         }
2996
2997                         // Check that we drain the correct values
2998                         let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2999                         let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
3000                         assert_eq!(drained, drained_expected);
3001
3002                         // We shouldn't have changed the capacity or made the
3003                         // head or tail out of bounds
3004                         assert_eq!(tester.capacity(), cap);
3005                         assert!(tester.tail < tester.cap());
3006                         assert!(tester.head < tester.cap());
3007
3008                         // We should see the correct values in the VecDeque
3009                         let expected: VecDeque<_> = (0..drain_start)
3010                             .chain(drain_end..len)
3011                             .collect();
3012                         assert_eq!(expected, tester);
3013                     }
3014                 }
3015             }
3016         }
3017     }
3018
3019     #[test]
3020     fn test_shrink_to_fit() {
3021         // This test checks that every single combination of head and tail position,
3022         // is tested. Capacity 15 should be large enough to cover every case.
3023
3024         let mut tester = VecDeque::with_capacity(15);
3025         // can't guarantee we got 15, so have to get what we got.
3026         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
3027         // this test isn't covering what it wants to
3028         let cap = tester.capacity();
3029         tester.reserve(63);
3030         let max_cap = tester.capacity();
3031
3032         for len in 0..=cap {
3033             // 0, 1, 2, .., len - 1
3034             let expected = (0..).take(len).collect::<VecDeque<_>>();
3035             for tail_pos in 0..=max_cap {
3036                 tester.tail = tail_pos;
3037                 tester.head = tail_pos;
3038                 tester.reserve(63);
3039                 for i in 0..len {
3040                     tester.push_back(i);
3041                 }
3042                 tester.shrink_to_fit();
3043                 assert!(tester.capacity() <= cap);
3044                 assert!(tester.tail < tester.cap());
3045                 assert!(tester.head < tester.cap());
3046                 assert_eq!(tester, expected);
3047             }
3048         }
3049     }
3050
3051     #[test]
3052     fn test_split_off() {
3053         // This test checks that every single combination of tail position, length, and
3054         // split position is tested. Capacity 15 should be large enough to cover every case.
3055
3056         let mut tester = VecDeque::with_capacity(15);
3057         // can't guarantee we got 15, so have to get what we got.
3058         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
3059         // this test isn't covering what it wants to
3060         let cap = tester.capacity();
3061
3062         // len is the length *before* splitting
3063         for len in 0..cap {
3064             // index to split at
3065             for at in 0..=len {
3066                 // 0, 1, 2, .., at - 1 (may be empty)
3067                 let expected_self = (0..).take(at).collect::<VecDeque<_>>();
3068                 // at, at + 1, .., len - 1 (may be empty)
3069                 let expected_other = (at..).take(len - at).collect::<VecDeque<_>>();
3070
3071                 for tail_pos in 0..cap {
3072                     tester.tail = tail_pos;
3073                     tester.head = tail_pos;
3074                     for i in 0..len {
3075                         tester.push_back(i);
3076                     }
3077                     let result = tester.split_off(at);
3078                     assert!(tester.tail < tester.cap());
3079                     assert!(tester.head < tester.cap());
3080                     assert!(result.tail < result.cap());
3081                     assert!(result.head < result.cap());
3082                     assert_eq!(tester, expected_self);
3083                     assert_eq!(result, expected_other);
3084                 }
3085             }
3086         }
3087     }
3088
3089     #[test]
3090     fn test_from_vec() {
3091         use crate::vec::Vec;
3092         for cap in 0..35 {
3093             for len in 0..=cap {
3094                 let mut vec = Vec::with_capacity(cap);
3095                 vec.extend(0..len);
3096
3097                 let vd = VecDeque::from(vec.clone());
3098                 assert!(vd.cap().is_power_of_two());
3099                 assert_eq!(vd.len(), vec.len());
3100                 assert!(vd.into_iter().eq(vec));
3101             }
3102         }
3103     }
3104
3105     #[test]
3106     fn test_vec_from_vecdeque() {
3107         use crate::vec::Vec;
3108
3109         fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
3110             let mut vd = VecDeque::with_capacity(cap);
3111             for _ in 0..offset {
3112                 vd.push_back(0);
3113                 vd.pop_front();
3114             }
3115             vd.extend(0..len);
3116
3117             let vec: Vec<_> = Vec::from(vd.clone());
3118             assert_eq!(vec.len(), vd.len());
3119             assert!(vec.into_iter().eq(vd));
3120         }
3121
3122         #[cfg(not(miri))] // Miri is too slow
3123         let max_pwr = 7;
3124         #[cfg(miri)]
3125         let max_pwr = 5;
3126
3127         for cap_pwr in 0..max_pwr {
3128             // Make capacity as a (2^x)-1, so that the ring size is 2^x
3129             let cap = (2i32.pow(cap_pwr) - 1) as usize;
3130
3131             // In these cases there is enough free space to solve it with copies
3132             for len in 0..((cap + 1) / 2) {
3133                 // Test contiguous cases
3134                 for offset in 0..(cap - len) {
3135                     create_vec_and_test_convert(cap, offset, len)
3136                 }
3137
3138                 // Test cases where block at end of buffer is bigger than block at start
3139                 for offset in (cap - len)..(cap - (len / 2)) {
3140                     create_vec_and_test_convert(cap, offset, len)
3141                 }
3142
3143                 // Test cases where block at start of buffer is bigger than block at end
3144                 for offset in (cap - (len / 2))..cap {
3145                     create_vec_and_test_convert(cap, offset, len)
3146                 }
3147             }
3148
3149             // Now there's not (necessarily) space to straighten the ring with simple copies,
3150             // the ring will use swapping when:
3151             // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
3152             //  right block size  >   free space    &&      left block size       >    free space
3153             for len in ((cap + 1) / 2)..cap {
3154                 // Test contiguous cases
3155                 for offset in 0..(cap - len) {
3156                     create_vec_and_test_convert(cap, offset, len)
3157                 }
3158
3159                 // Test cases where block at end of buffer is bigger than block at start
3160                 for offset in (cap - len)..(cap - (len / 2)) {
3161                     create_vec_and_test_convert(cap, offset, len)
3162                 }
3163
3164                 // Test cases where block at start of buffer is bigger than block at end
3165                 for offset in (cap - (len / 2))..cap {
3166                     create_vec_and_test_convert(cap, offset, len)
3167                 }
3168             }
3169         }
3170     }
3171
3172     #[test]
3173     fn issue_53529() {
3174         use crate::boxed::Box;
3175
3176         let mut dst = VecDeque::new();
3177         dst.push_front(Box::new(1));
3178         dst.push_front(Box::new(2));
3179         assert_eq!(*dst.pop_back().unwrap(), 1);
3180
3181         let mut src = VecDeque::new();
3182         src.push_front(Box::new(2));
3183         dst.append(&mut src);
3184         for a in dst {
3185             assert_eq!(*a, 2);
3186         }
3187     }
3188
3189 }