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