]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec_deque.rs
rustfmt libcollections
[rust.git] / src / libcollections / 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 //! VecDeque is a double-ended queue, which is implemented with the help of a
12 //! growing ring buffer.
13 //!
14 //! This queue has `O(1)` amortized inserts and removals from both ends of the
15 //! container. It also has `O(1)` indexing like a vector. The contained elements
16 //! are not required to be copyable, and the queue will be sendable if the
17 //! contained type is sendable.
18
19 #![stable(feature = "rust1", since = "1.0.0")]
20
21 use core::cmp::Ordering;
22 use core::fmt;
23 use core::iter::{repeat, FromIterator};
24 use core::mem;
25 use core::ops::{Index, IndexMut};
26 use core::ptr;
27 use core::slice;
28 use core::usize;
29
30 use core::hash::{Hash, Hasher};
31 use core::cmp;
32
33 use alloc::raw_vec::RawVec;
34
35 use super::range::RangeArgument;
36
37 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
38 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
39 const MAXIMUM_ZST_CAPACITY: usize = 1 << (usize::BITS - 1); // Largest possible power of two
40
41 /// `VecDeque` is a growable ring buffer, which can be used as a double-ended
42 /// queue efficiently.
43 ///
44 /// The "default" usage of this type as a queue is to use `push_back` to add to
45 /// the queue, and `pop_front` to remove from the queue. `extend` and `append`
46 /// push onto the back in this manner, and iterating over `VecDeque` goes front
47 /// to back.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub struct VecDeque<T> {
50     // tail and head are pointers into the buffer. Tail always points
51     // to the first element that could be read, Head always points
52     // to where data should be written.
53     // If tail == head the buffer is empty. The length of the ringbuffer
54     // is defined as the distance between the two.
55     tail: usize,
56     head: usize,
57     buf: RawVec<T>,
58 }
59
60 #[stable(feature = "rust1", since = "1.0.0")]
61 impl<T: Clone> Clone for VecDeque<T> {
62     fn clone(&self) -> VecDeque<T> {
63         self.iter().cloned().collect()
64     }
65 }
66
67 #[stable(feature = "rust1", since = "1.0.0")]
68 impl<T> Drop for VecDeque<T> {
69     #[unsafe_destructor_blind_to_params]
70     fn drop(&mut self) {
71         self.clear();
72         // RawVec handles deallocation
73     }
74 }
75
76 #[stable(feature = "rust1", since = "1.0.0")]
77 impl<T> Default for VecDeque<T> {
78     #[inline]
79     fn default() -> VecDeque<T> {
80         VecDeque::new()
81     }
82 }
83
84 impl<T> VecDeque<T> {
85     /// Marginally more convenient
86     #[inline]
87     fn ptr(&self) -> *mut T {
88         self.buf.ptr()
89     }
90
91     /// Marginally more convenient
92     #[inline]
93     fn cap(&self) -> usize {
94         if mem::size_of::<T>() == 0 {
95             // For zero sized types, we are always at maximum capacity
96             MAXIMUM_ZST_CAPACITY
97         } else {
98             self.buf.cap()
99         }
100     }
101
102     /// Turn ptr into a slice
103     #[inline]
104     unsafe fn buffer_as_slice(&self) -> &[T] {
105         slice::from_raw_parts(self.ptr(), self.cap())
106     }
107
108     /// Turn ptr into a mut slice
109     #[inline]
110     unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
111         slice::from_raw_parts_mut(self.ptr(), self.cap())
112     }
113
114     /// Moves an element out of the buffer
115     #[inline]
116     unsafe fn buffer_read(&mut self, off: usize) -> T {
117         ptr::read(self.ptr().offset(off as isize))
118     }
119
120     /// Writes an element into the buffer, moving it.
121     #[inline]
122     unsafe fn buffer_write(&mut self, off: usize, value: T) {
123         ptr::write(self.ptr().offset(off as isize), value);
124     }
125
126     /// Returns true if and only if the buffer is at capacity
127     #[inline]
128     fn is_full(&self) -> bool {
129         self.cap() - self.len() == 1
130     }
131
132     /// Returns the index in the underlying buffer for a given logical element
133     /// index.
134     #[inline]
135     fn wrap_index(&self, idx: usize) -> usize {
136         wrap_index(idx, self.cap())
137     }
138
139     /// Returns the index in the underlying buffer for a given logical element
140     /// index + addend.
141     #[inline]
142     fn wrap_add(&self, idx: usize, addend: usize) -> usize {
143         wrap_index(idx.wrapping_add(addend), self.cap())
144     }
145
146     /// Returns the index in the underlying buffer for a given logical element
147     /// index - subtrahend.
148     #[inline]
149     fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
150         wrap_index(idx.wrapping_sub(subtrahend), self.cap())
151     }
152
153     /// Copies a contiguous block of memory len long from src to dst
154     #[inline]
155     unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
156         debug_assert!(dst + len <= self.cap(),
157                       "cpy dst={} src={} len={} cap={}",
158                       dst,
159                       src,
160                       len,
161                       self.cap());
162         debug_assert!(src + len <= self.cap(),
163                       "cpy dst={} src={} len={} cap={}",
164                       dst,
165                       src,
166                       len,
167                       self.cap());
168         ptr::copy(self.ptr().offset(src as isize),
169                   self.ptr().offset(dst as isize),
170                   len);
171     }
172
173     /// Copies a contiguous block of memory len long from src to dst
174     #[inline]
175     unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
176         debug_assert!(dst + len <= self.cap(),
177                       "cno dst={} src={} len={} cap={}",
178                       dst,
179                       src,
180                       len,
181                       self.cap());
182         debug_assert!(src + len <= self.cap(),
183                       "cno dst={} src={} len={} cap={}",
184                       dst,
185                       src,
186                       len,
187                       self.cap());
188         ptr::copy_nonoverlapping(self.ptr().offset(src as isize),
189                                  self.ptr().offset(dst as isize),
190                                  len);
191     }
192
193     /// Copies a potentially wrapping block of memory len long from src to dest.
194     /// (abs(dst - src) + len) must be no larger than cap() (There must be at
195     /// most one continuous overlapping region between src and dest).
196     unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
197         #[allow(dead_code)]
198         fn diff(a: usize, b: usize) -> usize {
199             if a <= b {
200                 b - a
201             } else {
202                 a - b
203             }
204         }
205         debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
206                       "wrc dst={} src={} len={} cap={}",
207                       dst,
208                       src,
209                       len,
210                       self.cap());
211
212         if src == dst || len == 0 {
213             return;
214         }
215
216         let dst_after_src = self.wrap_sub(dst, src) < len;
217
218         let src_pre_wrap_len = self.cap() - src;
219         let dst_pre_wrap_len = self.cap() - dst;
220         let src_wraps = src_pre_wrap_len < len;
221         let dst_wraps = dst_pre_wrap_len < len;
222
223         match (dst_after_src, src_wraps, dst_wraps) {
224             (_, false, false) => {
225                 // src doesn't wrap, dst doesn't wrap
226                 //
227                 //        S . . .
228                 // 1 [_ _ A A B B C C _]
229                 // 2 [_ _ A A A A B B _]
230                 //            D . . .
231                 //
232                 self.copy(dst, src, len);
233             }
234             (false, false, true) => {
235                 // dst before src, src doesn't wrap, dst wraps
236                 //
237                 //    S . . .
238                 // 1 [A A B B _ _ _ C C]
239                 // 2 [A A B B _ _ _ A A]
240                 // 3 [B B B B _ _ _ A A]
241                 //    . .           D .
242                 //
243                 self.copy(dst, src, dst_pre_wrap_len);
244                 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
245             }
246             (true, false, true) => {
247                 // src before dst, src doesn't wrap, dst wraps
248                 //
249                 //              S . . .
250                 // 1 [C C _ _ _ A A B B]
251                 // 2 [B B _ _ _ A A B B]
252                 // 3 [B B _ _ _ A A A A]
253                 //    . .           D .
254                 //
255                 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
256                 self.copy(dst, src, dst_pre_wrap_len);
257             }
258             (false, true, false) => {
259                 // dst before src, src wraps, dst doesn't wrap
260                 //
261                 //    . .           S .
262                 // 1 [C C _ _ _ A A B B]
263                 // 2 [C C _ _ _ B B B B]
264                 // 3 [C C _ _ _ B B C C]
265                 //              D . . .
266                 //
267                 self.copy(dst, src, src_pre_wrap_len);
268                 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
269             }
270             (true, true, false) => {
271                 // src before dst, src wraps, dst doesn't wrap
272                 //
273                 //    . .           S .
274                 // 1 [A A B B _ _ _ C C]
275                 // 2 [A A A A _ _ _ C C]
276                 // 3 [C C A A _ _ _ C C]
277                 //    D . . .
278                 //
279                 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
280                 self.copy(dst, src, src_pre_wrap_len);
281             }
282             (false, true, true) => {
283                 // dst before src, src wraps, dst wraps
284                 //
285                 //    . . .         S .
286                 // 1 [A B C D _ E F G H]
287                 // 2 [A B C D _ E G H H]
288                 // 3 [A B C D _ E G H A]
289                 // 4 [B C C D _ E G H A]
290                 //    . .         D . .
291                 //
292                 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
293                 let delta = dst_pre_wrap_len - src_pre_wrap_len;
294                 self.copy(dst, src, src_pre_wrap_len);
295                 self.copy(dst + src_pre_wrap_len, 0, delta);
296                 self.copy(0, delta, len - dst_pre_wrap_len);
297             }
298             (true, true, true) => {
299                 // src before dst, src wraps, dst wraps
300                 //
301                 //    . .         S . .
302                 // 1 [A B C D _ E F G H]
303                 // 2 [A A B D _ E F G H]
304                 // 3 [H A B D _ E F G H]
305                 // 4 [H A B D _ E F F G]
306                 //    . . .         D .
307                 //
308                 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
309                 let delta = src_pre_wrap_len - dst_pre_wrap_len;
310                 self.copy(delta, 0, len - src_pre_wrap_len);
311                 self.copy(0, self.cap() - delta, delta);
312                 self.copy(dst, src, dst_pre_wrap_len);
313             }
314         }
315     }
316
317     /// Frobs the head and tail sections around to handle the fact that we
318     /// just reallocated. Unsafe because it trusts old_cap.
319     #[inline]
320     unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
321         let new_cap = self.cap();
322
323         // Move the shortest contiguous section of the ring buffer
324         //    T             H
325         //   [o o o o o o o . ]
326         //    T             H
327         // A [o o o o o o o . . . . . . . . . ]
328         //        H T
329         //   [o o . o o o o o ]
330         //          T             H
331         // B [. . . o o o o o o o . . . . . . ]
332         //              H T
333         //   [o o o o o . o o ]
334         //              H                 T
335         // C [o o o o o . . . . . . . . . o o ]
336
337         if self.tail <= self.head {
338             // A
339             // Nop
340         } else if self.head < old_cap - self.tail {
341             // B
342             self.copy_nonoverlapping(old_cap, 0, self.head);
343             self.head += old_cap;
344             debug_assert!(self.head > self.tail);
345         } else {
346             // C
347             let new_tail = new_cap - (old_cap - self.tail);
348             self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
349             self.tail = new_tail;
350             debug_assert!(self.head < self.tail);
351         }
352         debug_assert!(self.head < self.cap());
353         debug_assert!(self.tail < self.cap());
354         debug_assert!(self.cap().count_ones() == 1);
355     }
356 }
357
358 impl<T> VecDeque<T> {
359     /// Creates an empty `VecDeque`.
360     #[stable(feature = "rust1", since = "1.0.0")]
361     pub fn new() -> VecDeque<T> {
362         VecDeque::with_capacity(INITIAL_CAPACITY)
363     }
364
365     /// Creates an empty `VecDeque` with space for at least `n` elements.
366     #[stable(feature = "rust1", since = "1.0.0")]
367     pub fn with_capacity(n: usize) -> VecDeque<T> {
368         // +1 since the ringbuffer always leaves one space empty
369         let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
370         assert!(cap > n, "capacity overflow");
371
372         VecDeque {
373             tail: 0,
374             head: 0,
375             buf: RawVec::with_capacity(cap),
376         }
377     }
378
379     /// Retrieves an element in the `VecDeque` by index.
380     ///
381     /// # Examples
382     ///
383     /// ```
384     /// use std::collections::VecDeque;
385     ///
386     /// let mut buf = VecDeque::new();
387     /// buf.push_back(3);
388     /// buf.push_back(4);
389     /// buf.push_back(5);
390     /// assert_eq!(buf.get(1), Some(&4));
391     /// ```
392     #[stable(feature = "rust1", since = "1.0.0")]
393     pub fn get(&self, index: usize) -> Option<&T> {
394         if index < self.len() {
395             let idx = self.wrap_add(self.tail, index);
396             unsafe { Some(&*self.ptr().offset(idx as isize)) }
397         } else {
398             None
399         }
400     }
401
402     /// Retrieves an element in the `VecDeque` mutably by index.
403     ///
404     /// # Examples
405     ///
406     /// ```
407     /// use std::collections::VecDeque;
408     ///
409     /// let mut buf = VecDeque::new();
410     /// buf.push_back(3);
411     /// buf.push_back(4);
412     /// buf.push_back(5);
413     /// if let Some(elem) = buf.get_mut(1) {
414     ///     *elem = 7;
415     /// }
416     ///
417     /// assert_eq!(buf[1], 7);
418     /// ```
419     #[stable(feature = "rust1", since = "1.0.0")]
420     pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
421         if index < self.len() {
422             let idx = self.wrap_add(self.tail, index);
423             unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
424         } else {
425             None
426         }
427     }
428
429     /// Swaps elements at indices `i` and `j`.
430     ///
431     /// `i` and `j` may be equal.
432     ///
433     /// Fails if there is no element with either index.
434     ///
435     /// # Examples
436     ///
437     /// ```
438     /// use std::collections::VecDeque;
439     ///
440     /// let mut buf = VecDeque::new();
441     /// buf.push_back(3);
442     /// buf.push_back(4);
443     /// buf.push_back(5);
444     /// buf.swap(0, 2);
445     /// assert_eq!(buf[0], 5);
446     /// assert_eq!(buf[2], 3);
447     /// ```
448     #[stable(feature = "rust1", since = "1.0.0")]
449     pub fn swap(&mut self, i: usize, j: usize) {
450         assert!(i < self.len());
451         assert!(j < self.len());
452         let ri = self.wrap_add(self.tail, i);
453         let rj = self.wrap_add(self.tail, j);
454         unsafe {
455             ptr::swap(self.ptr().offset(ri as isize),
456                       self.ptr().offset(rj as isize))
457         }
458     }
459
460     /// Returns the number of elements the `VecDeque` can hold without
461     /// reallocating.
462     ///
463     /// # Examples
464     ///
465     /// ```
466     /// use std::collections::VecDeque;
467     ///
468     /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
469     /// assert!(buf.capacity() >= 10);
470     /// ```
471     #[inline]
472     #[stable(feature = "rust1", since = "1.0.0")]
473     pub fn capacity(&self) -> usize {
474         self.cap() - 1
475     }
476
477     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
478     /// given `VecDeque`. Does nothing if the capacity is already sufficient.
479     ///
480     /// Note that the allocator may give the collection more space than it requests. Therefore
481     /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
482     /// insertions are expected.
483     ///
484     /// # Panics
485     ///
486     /// Panics if the new capacity overflows `usize`.
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// use std::collections::VecDeque;
492     ///
493     /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
494     /// buf.reserve_exact(10);
495     /// assert!(buf.capacity() >= 11);
496     /// ```
497     #[stable(feature = "rust1", since = "1.0.0")]
498     pub fn reserve_exact(&mut self, additional: usize) {
499         self.reserve(additional);
500     }
501
502     /// Reserves capacity for at least `additional` more elements to be inserted in the given
503     /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
504     ///
505     /// # Panics
506     ///
507     /// Panics if the new capacity overflows `usize`.
508     ///
509     /// # Examples
510     ///
511     /// ```
512     /// use std::collections::VecDeque;
513     ///
514     /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
515     /// buf.reserve(10);
516     /// assert!(buf.capacity() >= 11);
517     /// ```
518     #[stable(feature = "rust1", since = "1.0.0")]
519     pub fn reserve(&mut self, additional: usize) {
520         let old_cap = self.cap();
521         let used_cap = self.len() + 1;
522         let new_cap = used_cap.checked_add(additional)
523                               .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
524                               .expect("capacity overflow");
525
526         if new_cap > self.capacity() {
527             self.buf.reserve_exact(used_cap, new_cap - used_cap);
528             unsafe {
529                 self.handle_cap_increase(old_cap);
530             }
531         }
532     }
533
534     /// Shrinks the capacity of the `VecDeque` as much as possible.
535     ///
536     /// It will drop down as close as possible to the length but the allocator may still inform the
537     /// `VecDeque` that there is space for a few more elements.
538     ///
539     /// # Examples
540     ///
541     /// ```
542     /// use std::collections::VecDeque;
543     ///
544     /// let mut buf = VecDeque::with_capacity(15);
545     /// buf.extend(0..4);
546     /// assert_eq!(buf.capacity(), 15);
547     /// buf.shrink_to_fit();
548     /// assert!(buf.capacity() >= 4);
549     /// ```
550     #[stable(feature = "deque_extras_15", since = "1.5.0")]
551     pub fn shrink_to_fit(&mut self) {
552         // +1 since the ringbuffer always leaves one space empty
553         // len + 1 can't overflow for an existing, well-formed ringbuffer.
554         let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
555         if target_cap < self.cap() {
556             // There are three cases of interest:
557             //   All elements are out of desired bounds
558             //   Elements are contiguous, and head is out of desired bounds
559             //   Elements are discontiguous, and tail is out of desired bounds
560             //
561             // At all other times, element positions are unaffected.
562             //
563             // Indicates that elements at the head should be moved.
564             let head_outside = self.head == 0 || self.head >= target_cap;
565             // Move elements from out of desired bounds (positions after target_cap)
566             if self.tail >= target_cap && head_outside {
567                 //                    T             H
568                 //   [. . . . . . . . o o o o o o o . ]
569                 //    T             H
570                 //   [o o o o o o o . ]
571                 unsafe {
572                     self.copy_nonoverlapping(0, self.tail, self.len());
573                 }
574                 self.head = self.len();
575                 self.tail = 0;
576             } else if self.tail != 0 && self.tail < target_cap && head_outside {
577                 //          T             H
578                 //   [. . . o o o o o o o . . . . . . ]
579                 //        H T
580                 //   [o o . o o o o o ]
581                 let len = self.wrap_sub(self.head, target_cap);
582                 unsafe {
583                     self.copy_nonoverlapping(0, target_cap, len);
584                 }
585                 self.head = len;
586                 debug_assert!(self.head < self.tail);
587             } else if self.tail >= target_cap {
588                 //              H                 T
589                 //   [o o o o o . . . . . . . . . o o ]
590                 //              H T
591                 //   [o o o o o . o o ]
592                 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
593                 let len = self.cap() - self.tail;
594                 let new_tail = target_cap - len;
595                 unsafe {
596                     self.copy_nonoverlapping(new_tail, self.tail, len);
597                 }
598                 self.tail = new_tail;
599                 debug_assert!(self.head < self.tail);
600             }
601
602             self.buf.shrink_to_fit(target_cap);
603
604             debug_assert!(self.head < self.cap());
605             debug_assert!(self.tail < self.cap());
606             debug_assert!(self.cap().count_ones() == 1);
607         }
608     }
609
610     /// Shortens a `VecDeque`, dropping excess elements from the back.
611     ///
612     /// If `len` is greater than the `VecDeque`'s current length, this has no
613     /// effect.
614     ///
615     /// # Examples
616     ///
617     /// ```
618     /// #![feature(deque_extras)]
619     ///
620     /// use std::collections::VecDeque;
621     ///
622     /// let mut buf = VecDeque::new();
623     /// buf.push_back(5);
624     /// buf.push_back(10);
625     /// buf.push_back(15);
626     /// buf.truncate(1);
627     /// assert_eq!(buf.len(), 1);
628     /// assert_eq!(Some(&5), buf.get(0));
629     /// ```
630     #[unstable(feature = "deque_extras",
631                reason = "matches collection reform specification; waiting on panic semantics",
632                issue = "27788")]
633     pub fn truncate(&mut self, len: usize) {
634         for _ in len..self.len() {
635             self.pop_back();
636         }
637     }
638
639     /// Returns a front-to-back iterator.
640     ///
641     /// # Examples
642     ///
643     /// ```
644     /// use std::collections::VecDeque;
645     ///
646     /// let mut buf = VecDeque::new();
647     /// buf.push_back(5);
648     /// buf.push_back(3);
649     /// buf.push_back(4);
650     /// let b: &[_] = &[&5, &3, &4];
651     /// let c: Vec<&i32> = buf.iter().collect();
652     /// assert_eq!(&c[..], b);
653     /// ```
654     #[stable(feature = "rust1", since = "1.0.0")]
655     pub fn iter(&self) -> Iter<T> {
656         Iter {
657             tail: self.tail,
658             head: self.head,
659             ring: unsafe { self.buffer_as_slice() },
660         }
661     }
662
663     /// Returns a front-to-back iterator that returns mutable references.
664     ///
665     /// # Examples
666     ///
667     /// ```
668     /// use std::collections::VecDeque;
669     ///
670     /// let mut buf = VecDeque::new();
671     /// buf.push_back(5);
672     /// buf.push_back(3);
673     /// buf.push_back(4);
674     /// for num in buf.iter_mut() {
675     ///     *num = *num - 2;
676     /// }
677     /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
678     /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
679     /// ```
680     #[stable(feature = "rust1", since = "1.0.0")]
681     pub fn iter_mut(&mut self) -> IterMut<T> {
682         IterMut {
683             tail: self.tail,
684             head: self.head,
685             ring: unsafe { self.buffer_as_mut_slice() },
686         }
687     }
688
689     /// Returns a pair of slices which contain, in order, the contents of the
690     /// `VecDeque`.
691     #[inline]
692     #[stable(feature = "deque_extras_15", since = "1.5.0")]
693     pub fn as_slices(&self) -> (&[T], &[T]) {
694         unsafe {
695             let contiguous = self.is_contiguous();
696             let buf = self.buffer_as_slice();
697             if contiguous {
698                 let (empty, buf) = buf.split_at(0);
699                 (&buf[self.tail..self.head], empty)
700             } else {
701                 let (mid, right) = buf.split_at(self.tail);
702                 let (left, _) = mid.split_at(self.head);
703                 (right, left)
704             }
705         }
706     }
707
708     /// Returns a pair of slices which contain, in order, the contents of the
709     /// `VecDeque`.
710     #[inline]
711     #[stable(feature = "deque_extras_15", since = "1.5.0")]
712     pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
713         unsafe {
714             let contiguous = self.is_contiguous();
715             let head = self.head;
716             let tail = self.tail;
717             let buf = self.buffer_as_mut_slice();
718
719             if contiguous {
720                 let (empty, buf) = buf.split_at_mut(0);
721                 (&mut buf[tail..head], empty)
722             } else {
723                 let (mid, right) = buf.split_at_mut(tail);
724                 let (left, _) = mid.split_at_mut(head);
725
726                 (right, left)
727             }
728         }
729     }
730
731     /// Returns the number of elements in the `VecDeque`.
732     ///
733     /// # Examples
734     ///
735     /// ```
736     /// use std::collections::VecDeque;
737     ///
738     /// let mut v = VecDeque::new();
739     /// assert_eq!(v.len(), 0);
740     /// v.push_back(1);
741     /// assert_eq!(v.len(), 1);
742     /// ```
743     #[stable(feature = "rust1", since = "1.0.0")]
744     pub fn len(&self) -> usize {
745         count(self.tail, self.head, self.cap())
746     }
747
748     /// Returns true if the buffer contains no elements
749     ///
750     /// # Examples
751     ///
752     /// ```
753     /// use std::collections::VecDeque;
754     ///
755     /// let mut v = VecDeque::new();
756     /// assert!(v.is_empty());
757     /// v.push_front(1);
758     /// assert!(!v.is_empty());
759     /// ```
760     #[stable(feature = "rust1", since = "1.0.0")]
761     pub fn is_empty(&self) -> bool {
762         self.len() == 0
763     }
764
765     /// Create a draining iterator that removes the specified range in the
766     /// `VecDeque` and yields the removed items from start to end. The element
767     /// range is removed even if the iterator is not consumed until the end.
768     ///
769     /// Note: It is unspecified how many elements are removed from the deque,
770     /// if the `Drain` value is not dropped, but the borrow it holds expires
771     /// (eg. due to mem::forget).
772     ///
773     /// # Panics
774     ///
775     /// Panics if the starting point is greater than the end point or if
776     /// the end point is greater than the length of the vector.
777     ///
778     /// # Examples
779     ///
780     /// ```
781     /// #![feature(drain)]
782     ///
783     /// use std::collections::VecDeque;
784     ///
785     /// // draining using `..` clears the whole deque.
786     /// let mut v = VecDeque::new();
787     /// v.push_back(1);
788     /// assert_eq!(v.drain(..).next(), Some(1));
789     /// assert!(v.is_empty());
790     /// ```
791     #[inline]
792     #[unstable(feature = "drain",
793                reason = "matches collection reform specification, waiting for dust to settle",
794                issue = "27711")]
795     pub fn drain<R>(&mut self, range: R) -> Drain<T>
796         where R: RangeArgument<usize>
797     {
798         // Memory safety
799         //
800         // When the Drain is first created, the source deque is shortened to
801         // make sure no uninitialized or moved-from elements are accessible at
802         // all if the Drain's destructor never gets to run.
803         //
804         // Drain will ptr::read out the values to remove.
805         // When finished, the remaining data will be copied back to cover the hole,
806         // and the head/tail values will be restored correctly.
807         //
808         let len = self.len();
809         let start = *range.start().unwrap_or(&0);
810         let end = *range.end().unwrap_or(&len);
811         assert!(start <= end, "drain lower bound was too large");
812         assert!(end <= len, "drain upper bound was too large");
813
814         // The deque's elements are parted into three segments:
815         // * self.tail  -> drain_tail
816         // * drain_tail -> drain_head
817         // * drain_head -> self.head
818         //
819         // T = self.tail; H = self.head; t = drain_tail; h = drain_head
820         //
821         // We store drain_tail as self.head, and drain_head and self.head as
822         // after_tail and after_head respectively on the Drain. This also
823         // truncates the effective array such that if the Drain is leaked, we
824         // have forgotten about the potentially moved values after the start of
825         // the drain.
826         //
827         //        T   t   h   H
828         // [. . . o o x x o o . . .]
829         //
830         let drain_tail = self.wrap_add(self.tail, start);
831         let drain_head = self.wrap_add(self.tail, end);
832         let head = self.head;
833
834         // "forget" about the values after the start of the drain until after
835         // the drain is complete and the Drain destructor is run.
836         self.head = drain_tail;
837
838         Drain {
839             deque: self as *mut _,
840             after_tail: drain_head,
841             after_head: head,
842             iter: Iter {
843                 tail: drain_tail,
844                 head: drain_head,
845                 ring: unsafe { self.buffer_as_mut_slice() },
846             },
847         }
848     }
849
850     /// Clears the buffer, removing all values.
851     ///
852     /// # Examples
853     ///
854     /// ```
855     /// use std::collections::VecDeque;
856     ///
857     /// let mut v = VecDeque::new();
858     /// v.push_back(1);
859     /// v.clear();
860     /// assert!(v.is_empty());
861     /// ```
862     #[stable(feature = "rust1", since = "1.0.0")]
863     #[inline]
864     pub fn clear(&mut self) {
865         self.drain(..);
866     }
867
868     /// Provides a reference to the front element, or `None` if the sequence is
869     /// empty.
870     ///
871     /// # Examples
872     ///
873     /// ```
874     /// use std::collections::VecDeque;
875     ///
876     /// let mut d = VecDeque::new();
877     /// assert_eq!(d.front(), None);
878     ///
879     /// d.push_back(1);
880     /// d.push_back(2);
881     /// assert_eq!(d.front(), Some(&1));
882     /// ```
883     #[stable(feature = "rust1", since = "1.0.0")]
884     pub fn front(&self) -> Option<&T> {
885         if !self.is_empty() {
886             Some(&self[0])
887         } else {
888             None
889         }
890     }
891
892     /// Provides a mutable reference to the front element, or `None` if the
893     /// sequence is empty.
894     ///
895     /// # Examples
896     ///
897     /// ```
898     /// use std::collections::VecDeque;
899     ///
900     /// let mut d = VecDeque::new();
901     /// assert_eq!(d.front_mut(), None);
902     ///
903     /// d.push_back(1);
904     /// d.push_back(2);
905     /// match d.front_mut() {
906     ///     Some(x) => *x = 9,
907     ///     None => (),
908     /// }
909     /// assert_eq!(d.front(), Some(&9));
910     /// ```
911     #[stable(feature = "rust1", since = "1.0.0")]
912     pub fn front_mut(&mut self) -> Option<&mut T> {
913         if !self.is_empty() {
914             Some(&mut self[0])
915         } else {
916             None
917         }
918     }
919
920     /// Provides a reference to the back element, or `None` if the sequence is
921     /// empty.
922     ///
923     /// # Examples
924     ///
925     /// ```
926     /// use std::collections::VecDeque;
927     ///
928     /// let mut d = VecDeque::new();
929     /// assert_eq!(d.back(), None);
930     ///
931     /// d.push_back(1);
932     /// d.push_back(2);
933     /// assert_eq!(d.back(), Some(&2));
934     /// ```
935     #[stable(feature = "rust1", since = "1.0.0")]
936     pub fn back(&self) -> Option<&T> {
937         if !self.is_empty() {
938             Some(&self[self.len() - 1])
939         } else {
940             None
941         }
942     }
943
944     /// Provides a mutable reference to the back element, or `None` if the
945     /// sequence is empty.
946     ///
947     /// # Examples
948     ///
949     /// ```
950     /// use std::collections::VecDeque;
951     ///
952     /// let mut d = VecDeque::new();
953     /// assert_eq!(d.back(), None);
954     ///
955     /// d.push_back(1);
956     /// d.push_back(2);
957     /// match d.back_mut() {
958     ///     Some(x) => *x = 9,
959     ///     None => (),
960     /// }
961     /// assert_eq!(d.back(), Some(&9));
962     /// ```
963     #[stable(feature = "rust1", since = "1.0.0")]
964     pub fn back_mut(&mut self) -> Option<&mut T> {
965         let len = self.len();
966         if !self.is_empty() {
967             Some(&mut self[len - 1])
968         } else {
969             None
970         }
971     }
972
973     /// Removes the first element and returns it, or `None` if the sequence is
974     /// empty.
975     ///
976     /// # Examples
977     ///
978     /// ```
979     /// use std::collections::VecDeque;
980     ///
981     /// let mut d = VecDeque::new();
982     /// d.push_back(1);
983     /// d.push_back(2);
984     ///
985     /// assert_eq!(d.pop_front(), Some(1));
986     /// assert_eq!(d.pop_front(), Some(2));
987     /// assert_eq!(d.pop_front(), None);
988     /// ```
989     #[stable(feature = "rust1", since = "1.0.0")]
990     pub fn pop_front(&mut self) -> Option<T> {
991         if self.is_empty() {
992             None
993         } else {
994             let tail = self.tail;
995             self.tail = self.wrap_add(self.tail, 1);
996             unsafe { Some(self.buffer_read(tail)) }
997         }
998     }
999
1000     /// Inserts an element first in the sequence.
1001     ///
1002     /// # Examples
1003     ///
1004     /// ```
1005     /// use std::collections::VecDeque;
1006     ///
1007     /// let mut d = VecDeque::new();
1008     /// d.push_front(1);
1009     /// d.push_front(2);
1010     /// assert_eq!(d.front(), Some(&2));
1011     /// ```
1012     #[stable(feature = "rust1", since = "1.0.0")]
1013     pub fn push_front(&mut self, value: T) {
1014         if self.is_full() {
1015             let old_cap = self.cap();
1016             self.buf.double();
1017             unsafe {
1018                 self.handle_cap_increase(old_cap);
1019             }
1020             debug_assert!(!self.is_full());
1021         }
1022
1023         self.tail = self.wrap_sub(self.tail, 1);
1024         let tail = self.tail;
1025         unsafe {
1026             self.buffer_write(tail, value);
1027         }
1028     }
1029
1030     /// Appends an element to the back of a buffer
1031     ///
1032     /// # Examples
1033     ///
1034     /// ```
1035     /// use std::collections::VecDeque;
1036     ///
1037     /// let mut buf = VecDeque::new();
1038     /// buf.push_back(1);
1039     /// buf.push_back(3);
1040     /// assert_eq!(3, *buf.back().unwrap());
1041     /// ```
1042     #[stable(feature = "rust1", since = "1.0.0")]
1043     pub fn push_back(&mut self, value: T) {
1044         if self.is_full() {
1045             let old_cap = self.cap();
1046             self.buf.double();
1047             unsafe {
1048                 self.handle_cap_increase(old_cap);
1049             }
1050             debug_assert!(!self.is_full());
1051         }
1052
1053         let head = self.head;
1054         self.head = self.wrap_add(self.head, 1);
1055         unsafe { self.buffer_write(head, value) }
1056     }
1057
1058     /// Removes the last element from a buffer and returns it, or `None` if
1059     /// it is empty.
1060     ///
1061     /// # Examples
1062     ///
1063     /// ```
1064     /// use std::collections::VecDeque;
1065     ///
1066     /// let mut buf = VecDeque::new();
1067     /// assert_eq!(buf.pop_back(), None);
1068     /// buf.push_back(1);
1069     /// buf.push_back(3);
1070     /// assert_eq!(buf.pop_back(), Some(3));
1071     /// ```
1072     #[stable(feature = "rust1", since = "1.0.0")]
1073     pub fn pop_back(&mut self) -> Option<T> {
1074         if self.is_empty() {
1075             None
1076         } else {
1077             self.head = self.wrap_sub(self.head, 1);
1078             let head = self.head;
1079             unsafe { Some(self.buffer_read(head)) }
1080         }
1081     }
1082
1083     #[inline]
1084     fn is_contiguous(&self) -> bool {
1085         self.tail <= self.head
1086     }
1087
1088     /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1089     /// last element.
1090     ///
1091     /// This does not preserve ordering, but is O(1).
1092     ///
1093     /// Returns `None` if `index` is out of bounds.
1094     ///
1095     /// # Examples
1096     ///
1097     /// ```
1098     /// use std::collections::VecDeque;
1099     ///
1100     /// let mut buf = VecDeque::new();
1101     /// assert_eq!(buf.swap_remove_back(0), None);
1102     /// buf.push_back(1);
1103     /// buf.push_back(2);
1104     /// buf.push_back(3);
1105     ///
1106     /// assert_eq!(buf.swap_remove_back(0), Some(1));
1107     /// assert_eq!(buf.len(), 2);
1108     /// assert_eq!(buf[0], 3);
1109     /// assert_eq!(buf[1], 2);
1110     /// ```
1111     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1112     pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1113         let length = self.len();
1114         if length > 0 && index < length - 1 {
1115             self.swap(index, length - 1);
1116         } else if index >= length {
1117             return None;
1118         }
1119         self.pop_back()
1120     }
1121
1122     /// deprecated
1123     #[unstable(feature = "deque_extras",
1124                reason = "the naming of this function may be altered",
1125                issue = "27788")]
1126     #[deprecated(since = "1.5.0", reason = "renamed to swap_remove_back")]
1127     pub fn swap_back_remove(&mut self, index: usize) -> Option<T> {
1128         self.swap_remove_back(index)
1129     }
1130
1131     /// Removes an element from anywhere in the `VecDeque` and returns it,
1132     /// replacing it with the first element.
1133     ///
1134     /// This does not preserve ordering, but is O(1).
1135     ///
1136     /// Returns `None` if `index` is out of bounds.
1137     ///
1138     /// # Examples
1139     ///
1140     /// ```
1141     /// use std::collections::VecDeque;
1142     ///
1143     /// let mut buf = VecDeque::new();
1144     /// assert_eq!(buf.swap_remove_front(0), None);
1145     /// buf.push_back(1);
1146     /// buf.push_back(2);
1147     /// buf.push_back(3);
1148     ///
1149     /// assert_eq!(buf.swap_remove_front(2), Some(3));
1150     /// assert_eq!(buf.len(), 2);
1151     /// assert_eq!(buf[0], 2);
1152     /// assert_eq!(buf[1], 1);
1153     /// ```
1154     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1155     pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1156         let length = self.len();
1157         if length > 0 && index < length && index != 0 {
1158             self.swap(index, 0);
1159         } else if index >= length {
1160             return None;
1161         }
1162         self.pop_front()
1163     }
1164
1165     /// deprecated
1166     #[unstable(feature = "deque_extras",
1167                reason = "the naming of this function may be altered",
1168                issue = "27788")]
1169     #[deprecated(since = "1.5.0", reason = "renamed to swap_remove_front")]
1170     pub fn swap_front_remove(&mut self, index: usize) -> Option<T> {
1171         self.swap_remove_front(index)
1172     }
1173
1174     /// Inserts an element at `index` within the `VecDeque`. Whichever
1175     /// end is closer to the insertion point will be moved to make room,
1176     /// and all the affected elements will be moved to new positions.
1177     ///
1178     /// # Panics
1179     ///
1180     /// Panics if `index` is greater than `VecDeque`'s length
1181     ///
1182     /// # Examples
1183     /// ```
1184     /// use std::collections::VecDeque;
1185     ///
1186     /// let mut buf = VecDeque::new();
1187     /// buf.push_back(10);
1188     /// buf.push_back(12);
1189     /// buf.insert(1, 11);
1190     /// assert_eq!(Some(&11), buf.get(1));
1191     /// ```
1192     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1193     pub fn insert(&mut self, index: usize, value: T) {
1194         assert!(index <= self.len(), "index out of bounds");
1195         if self.is_full() {
1196             let old_cap = self.cap();
1197             self.buf.double();
1198             unsafe {
1199                 self.handle_cap_increase(old_cap);
1200             }
1201             debug_assert!(!self.is_full());
1202         }
1203
1204         // Move the least number of elements in the ring buffer and insert
1205         // the given object
1206         //
1207         // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1208         //
1209         // There are three main cases:
1210         //  Elements are contiguous
1211         //      - special case when tail is 0
1212         //  Elements are discontiguous and the insert is in the tail section
1213         //  Elements are discontiguous and the insert is in the head section
1214         //
1215         // For each of those there are two more cases:
1216         //  Insert is closer to tail
1217         //  Insert is closer to head
1218         //
1219         // Key: H - self.head
1220         //      T - self.tail
1221         //      o - Valid element
1222         //      I - Insertion element
1223         //      A - The element that should be after the insertion point
1224         //      M - Indicates element was moved
1225
1226         let idx = self.wrap_add(self.tail, index);
1227
1228         let distance_to_tail = index;
1229         let distance_to_head = self.len() - index;
1230
1231         let contiguous = self.is_contiguous();
1232
1233         match (contiguous,
1234                distance_to_tail <= distance_to_head,
1235                idx >= self.tail) {
1236             (true, true, _) if index == 0 => {
1237                 // push_front
1238                 //
1239                 //       T
1240                 //       I             H
1241                 //      [A o o o o o o . . . . . . . . .]
1242                 //
1243                 //                       H         T
1244                 //      [A o o o o o o o . . . . . I]
1245                 //
1246
1247                 self.tail = self.wrap_sub(self.tail, 1);
1248             }
1249             (true, true, _) => {
1250                 unsafe {
1251                     // contiguous, insert closer to tail:
1252                     //
1253                     //             T   I         H
1254                     //      [. . . o o A o o o o . . . . . .]
1255                     //
1256                     //           T               H
1257                     //      [. . o o I A o o o o . . . . . .]
1258                     //           M M
1259                     //
1260                     // contiguous, insert closer to tail and tail is 0:
1261                     //
1262                     //
1263                     //       T   I         H
1264                     //      [o o A o o o o . . . . . . . . .]
1265                     //
1266                     //                       H             T
1267                     //      [o I A o o o o o . . . . . . . o]
1268                     //       M                             M
1269
1270                     let new_tail = self.wrap_sub(self.tail, 1);
1271
1272                     self.copy(new_tail, self.tail, 1);
1273                     // Already moved the tail, so we only copy `index - 1` elements.
1274                     self.copy(self.tail, self.tail + 1, index - 1);
1275
1276                     self.tail = new_tail;
1277                 }
1278             }
1279             (true, false, _) => {
1280                 unsafe {
1281                     //  contiguous, insert closer to head:
1282                     //
1283                     //             T       I     H
1284                     //      [. . . o o o o A o o . . . . . .]
1285                     //
1286                     //             T               H
1287                     //      [. . . o o o o I A o o . . . . .]
1288                     //                       M M M
1289
1290                     self.copy(idx + 1, idx, self.head - idx);
1291                     self.head = self.wrap_add(self.head, 1);
1292                 }
1293             }
1294             (false, true, true) => {
1295                 unsafe {
1296                     // discontiguous, insert closer to tail, tail section:
1297                     //
1298                     //                   H         T   I
1299                     //      [o o o o o o . . . . . o o A o o]
1300                     //
1301                     //                   H       T
1302                     //      [o o o o o o . . . . o o I A o o]
1303                     //                           M M
1304
1305                     self.copy(self.tail - 1, self.tail, index);
1306                     self.tail -= 1;
1307                 }
1308             }
1309             (false, false, true) => {
1310                 unsafe {
1311                     // discontiguous, insert closer to head, tail section:
1312                     //
1313                     //           H             T         I
1314                     //      [o o . . . . . . . o o o o o A o]
1315                     //
1316                     //             H           T
1317                     //      [o o o . . . . . . o o o o o I A]
1318                     //       M M M                         M
1319
1320                     // copy elements up to new head
1321                     self.copy(1, 0, self.head);
1322
1323                     // copy last element into empty spot at bottom of buffer
1324                     self.copy(0, self.cap() - 1, 1);
1325
1326                     // move elements from idx to end forward not including ^ element
1327                     self.copy(idx + 1, idx, self.cap() - 1 - idx);
1328
1329                     self.head += 1;
1330                 }
1331             }
1332             (false, true, false) if idx == 0 => {
1333                 unsafe {
1334                     // discontiguous, insert is closer to tail, head section,
1335                     // and is at index zero in the internal buffer:
1336                     //
1337                     //       I                   H     T
1338                     //      [A o o o o o o o o o . . . o o o]
1339                     //
1340                     //                           H   T
1341                     //      [A o o o o o o o o o . . o o o I]
1342                     //                               M M M
1343
1344                     // copy elements up to new tail
1345                     self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1346
1347                     // copy last element into empty spot at bottom of buffer
1348                     self.copy(self.cap() - 1, 0, 1);
1349
1350                     self.tail -= 1;
1351                 }
1352             }
1353             (false, true, false) => {
1354                 unsafe {
1355                     // discontiguous, insert closer to tail, head section:
1356                     //
1357                     //             I             H     T
1358                     //      [o o o A o o o o o o . . . o o o]
1359                     //
1360                     //                           H   T
1361                     //      [o o I A o o o o o o . . o o o o]
1362                     //       M M                     M M M M
1363
1364                     // copy elements up to new tail
1365                     self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1366
1367                     // copy last element into empty spot at bottom of buffer
1368                     self.copy(self.cap() - 1, 0, 1);
1369
1370                     // move elements from idx-1 to end forward not including ^ element
1371                     self.copy(0, 1, idx - 1);
1372
1373                     self.tail -= 1;
1374                 }
1375             }
1376             (false, false, false) => {
1377                 unsafe {
1378                     // discontiguous, insert closer to head, head section:
1379                     //
1380                     //               I     H           T
1381                     //      [o o o o A o o . . . . . . o o o]
1382                     //
1383                     //                     H           T
1384                     //      [o o o o I A o o . . . . . o o o]
1385                     //                 M M M
1386
1387                     self.copy(idx + 1, idx, self.head - idx);
1388                     self.head += 1;
1389                 }
1390             }
1391         }
1392
1393         // tail might've been changed so we need to recalculate
1394         let new_idx = self.wrap_add(self.tail, index);
1395         unsafe {
1396             self.buffer_write(new_idx, value);
1397         }
1398     }
1399
1400     /// Removes and returns the element at `index` from the `VecDeque`.
1401     /// Whichever end is closer to the removal point will be moved to make
1402     /// room, and all the affected elements will be moved to new positions.
1403     /// Returns `None` if `index` is out of bounds.
1404     ///
1405     /// # Examples
1406     /// ```
1407     /// use std::collections::VecDeque;
1408     ///
1409     /// let mut buf = VecDeque::new();
1410     /// buf.push_back(1);
1411     /// buf.push_back(2);
1412     /// buf.push_back(3);
1413     ///
1414     /// assert_eq!(buf.remove(1), Some(2));
1415     /// assert_eq!(buf.get(1), Some(&3));
1416     /// ```
1417     #[stable(feature = "rust1", since = "1.0.0")]
1418     pub fn remove(&mut self, index: usize) -> Option<T> {
1419         if self.is_empty() || self.len() <= index {
1420             return None;
1421         }
1422
1423         // There are three main cases:
1424         //  Elements are contiguous
1425         //  Elements are discontiguous and the removal is in the tail section
1426         //  Elements are discontiguous and the removal is in the head section
1427         //      - special case when elements are technically contiguous,
1428         //        but self.head = 0
1429         //
1430         // For each of those there are two more cases:
1431         //  Insert is closer to tail
1432         //  Insert is closer to head
1433         //
1434         // Key: H - self.head
1435         //      T - self.tail
1436         //      o - Valid element
1437         //      x - Element marked for removal
1438         //      R - Indicates element that is being removed
1439         //      M - Indicates element was moved
1440
1441         let idx = self.wrap_add(self.tail, index);
1442
1443         let elem = unsafe { Some(self.buffer_read(idx)) };
1444
1445         let distance_to_tail = index;
1446         let distance_to_head = self.len() - index;
1447
1448         let contiguous = self.is_contiguous();
1449
1450         match (contiguous,
1451                distance_to_tail <= distance_to_head,
1452                idx >= self.tail) {
1453             (true, true, _) => {
1454                 unsafe {
1455                     // contiguous, remove closer to tail:
1456                     //
1457                     //             T   R         H
1458                     //      [. . . o o x o o o o . . . . . .]
1459                     //
1460                     //               T           H
1461                     //      [. . . . o o o o o o . . . . . .]
1462                     //               M M
1463
1464                     self.copy(self.tail + 1, self.tail, index);
1465                     self.tail += 1;
1466                 }
1467             }
1468             (true, false, _) => {
1469                 unsafe {
1470                     // contiguous, remove closer to head:
1471                     //
1472                     //             T       R     H
1473                     //      [. . . o o o o x o o . . . . . .]
1474                     //
1475                     //             T           H
1476                     //      [. . . o o o o o o . . . . . . .]
1477                     //                     M M
1478
1479                     self.copy(idx, idx + 1, self.head - idx - 1);
1480                     self.head -= 1;
1481                 }
1482             }
1483             (false, true, true) => {
1484                 unsafe {
1485                     // discontiguous, remove closer to tail, tail section:
1486                     //
1487                     //                   H         T   R
1488                     //      [o o o o o o . . . . . o o x o o]
1489                     //
1490                     //                   H           T
1491                     //      [o o o o o o . . . . . . o o o o]
1492                     //                               M M
1493
1494                     self.copy(self.tail + 1, self.tail, index);
1495                     self.tail = self.wrap_add(self.tail, 1);
1496                 }
1497             }
1498             (false, false, false) => {
1499                 unsafe {
1500                     // discontiguous, remove closer to head, head section:
1501                     //
1502                     //               R     H           T
1503                     //      [o o o o x o o . . . . . . o o o]
1504                     //
1505                     //                   H             T
1506                     //      [o o o o o o . . . . . . . o o o]
1507                     //               M M
1508
1509                     self.copy(idx, idx + 1, self.head - idx - 1);
1510                     self.head -= 1;
1511                 }
1512             }
1513             (false, false, true) => {
1514                 unsafe {
1515                     // discontiguous, remove closer to head, tail section:
1516                     //
1517                     //             H           T         R
1518                     //      [o o o . . . . . . o o o o o x o]
1519                     //
1520                     //           H             T
1521                     //      [o o . . . . . . . o o o o o o o]
1522                     //       M M                         M M
1523                     //
1524                     // or quasi-discontiguous, remove next to head, tail section:
1525                     //
1526                     //       H                 T         R
1527                     //      [. . . . . . . . . o o o o o x o]
1528                     //
1529                     //                         T           H
1530                     //      [. . . . . . . . . o o o o o o .]
1531                     //                                   M
1532
1533                     // draw in elements in the tail section
1534                     self.copy(idx, idx + 1, self.cap() - idx - 1);
1535
1536                     // Prevents underflow.
1537                     if self.head != 0 {
1538                         // copy first element into empty spot
1539                         self.copy(self.cap() - 1, 0, 1);
1540
1541                         // move elements in the head section backwards
1542                         self.copy(0, 1, self.head - 1);
1543                     }
1544
1545                     self.head = self.wrap_sub(self.head, 1);
1546                 }
1547             }
1548             (false, true, false) => {
1549                 unsafe {
1550                     // discontiguous, remove closer to tail, head section:
1551                     //
1552                     //           R               H     T
1553                     //      [o o x o o o o o o o . . . o o o]
1554                     //
1555                     //                           H       T
1556                     //      [o o o o o o o o o o . . . . o o]
1557                     //       M M M                       M M
1558
1559                     // draw in elements up to idx
1560                     self.copy(1, 0, idx);
1561
1562                     // copy last element into empty spot
1563                     self.copy(0, self.cap() - 1, 1);
1564
1565                     // move elements from tail to end forward, excluding the last one
1566                     self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1567
1568                     self.tail = self.wrap_add(self.tail, 1);
1569                 }
1570             }
1571         }
1572
1573         return elem;
1574     }
1575
1576     /// Splits the collection into two at the given index.
1577     ///
1578     /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1579     /// and the returned `Self` contains elements `[at, len)`.
1580     ///
1581     /// Note that the capacity of `self` does not change.
1582     ///
1583     /// # Panics
1584     ///
1585     /// Panics if `at > len`
1586     ///
1587     /// # Examples
1588     ///
1589     /// ```
1590     /// use std::collections::VecDeque;
1591     ///
1592     /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1593     /// let buf2 = buf.split_off(1);
1594     /// // buf = [1], buf2 = [2, 3]
1595     /// assert_eq!(buf.len(), 1);
1596     /// assert_eq!(buf2.len(), 2);
1597     /// ```
1598     #[inline]
1599     #[stable(feature = "split_off", since = "1.4.0")]
1600     pub fn split_off(&mut self, at: usize) -> Self {
1601         let len = self.len();
1602         assert!(at <= len, "`at` out of bounds");
1603
1604         let other_len = len - at;
1605         let mut other = VecDeque::with_capacity(other_len);
1606
1607         unsafe {
1608             let (first_half, second_half) = self.as_slices();
1609
1610             let first_len = first_half.len();
1611             let second_len = second_half.len();
1612             if at < first_len {
1613                 // `at` lies in the first half.
1614                 let amount_in_first = first_len - at;
1615
1616                 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1617                                          other.ptr(),
1618                                          amount_in_first);
1619
1620                 // just take all of the second half.
1621                 ptr::copy_nonoverlapping(second_half.as_ptr(),
1622                                          other.ptr().offset(amount_in_first as isize),
1623                                          second_len);
1624             } else {
1625                 // `at` lies in the second half, need to factor in the elements we skipped
1626                 // in the first half.
1627                 let offset = at - first_len;
1628                 let amount_in_second = second_len - offset;
1629                 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1630                                          other.ptr(),
1631                                          amount_in_second);
1632             }
1633         }
1634
1635         // Cleanup where the ends of the buffers are
1636         self.head = self.wrap_sub(self.head, other_len);
1637         other.head = other.wrap_index(other_len);
1638
1639         other
1640     }
1641
1642     /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1643     ///
1644     /// # Panics
1645     ///
1646     /// Panics if the new number of elements in self overflows a `usize`.
1647     ///
1648     /// # Examples
1649     ///
1650     /// ```
1651     /// use std::collections::VecDeque;
1652     ///
1653     /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1654     /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
1655     /// buf.append(&mut buf2);
1656     /// assert_eq!(buf.len(), 6);
1657     /// assert_eq!(buf2.len(), 0);
1658     /// ```
1659     #[inline]
1660     #[stable(feature = "append", since = "1.4.0")]
1661     pub fn append(&mut self, other: &mut Self) {
1662         // naive impl
1663         self.extend(other.drain(..));
1664     }
1665
1666     /// Retains only the elements specified by the predicate.
1667     ///
1668     /// In other words, remove all elements `e` such that `f(&e)` returns false.
1669     /// This method operates in place and preserves the order of the retained
1670     /// elements.
1671     ///
1672     /// # Examples
1673     ///
1674     /// ```
1675     /// use std::collections::VecDeque;
1676     ///
1677     /// let mut buf = VecDeque::new();
1678     /// buf.extend(1..5);
1679     /// buf.retain(|&x| x%2 == 0);
1680     ///
1681     /// let v: Vec<_> = buf.into_iter().collect();
1682     /// assert_eq!(&v[..], &[2, 4]);
1683     /// ```
1684     #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1685     pub fn retain<F>(&mut self, mut f: F)
1686         where F: FnMut(&T) -> bool
1687     {
1688         let len = self.len();
1689         let mut del = 0;
1690         for i in 0..len {
1691             if !f(&self[i]) {
1692                 del += 1;
1693             } else if del > 0 {
1694                 self.swap(i - del, i);
1695             }
1696         }
1697         if del > 0 {
1698             self.truncate(len - del);
1699         }
1700     }
1701 }
1702
1703 impl<T: Clone> VecDeque<T> {
1704     /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1705     /// either by removing excess elements or by appending copies of a value to the back.
1706     ///
1707     /// # Examples
1708     ///
1709     /// ```
1710     /// #![feature(deque_extras)]
1711     ///
1712     /// use std::collections::VecDeque;
1713     ///
1714     /// let mut buf = VecDeque::new();
1715     /// buf.push_back(5);
1716     /// buf.push_back(10);
1717     /// buf.push_back(15);
1718     /// buf.resize(2, 0);
1719     /// buf.resize(6, 20);
1720     /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
1721     ///     assert_eq!(a, b);
1722     /// }
1723     /// ```
1724     #[unstable(feature = "deque_extras",
1725                reason = "matches collection reform specification; waiting on panic semantics",
1726                issue = "27788")]
1727     pub fn resize(&mut self, new_len: usize, value: T) {
1728         let len = self.len();
1729
1730         if new_len > len {
1731             self.extend(repeat(value).take(new_len - len))
1732         } else {
1733             self.truncate(new_len);
1734         }
1735     }
1736 }
1737
1738 /// Returns the index in the underlying buffer for a given logical element index.
1739 #[inline]
1740 fn wrap_index(index: usize, size: usize) -> usize {
1741     // size is always a power of 2
1742     debug_assert!(size.is_power_of_two());
1743     index & (size - 1)
1744 }
1745
1746 /// Calculate the number of elements left to be read in the buffer
1747 #[inline]
1748 fn count(tail: usize, head: usize, size: usize) -> usize {
1749     // size is always a power of 2
1750     (head.wrapping_sub(tail)) & (size - 1)
1751 }
1752
1753 /// `VecDeque` iterator.
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 pub struct Iter<'a, T: 'a> {
1756     ring: &'a [T],
1757     tail: usize,
1758     head: usize,
1759 }
1760
1761 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl<'a, T> Clone for Iter<'a, T> {
1764     fn clone(&self) -> Iter<'a, T> {
1765         Iter {
1766             ring: self.ring,
1767             tail: self.tail,
1768             head: self.head,
1769         }
1770     }
1771 }
1772
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 impl<'a, T> Iterator for Iter<'a, T> {
1775     type Item = &'a T;
1776
1777     #[inline]
1778     fn next(&mut self) -> Option<&'a T> {
1779         if self.tail == self.head {
1780             return None;
1781         }
1782         let tail = self.tail;
1783         self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1784         unsafe { Some(self.ring.get_unchecked(tail)) }
1785     }
1786
1787     #[inline]
1788     fn size_hint(&self) -> (usize, Option<usize>) {
1789         let len = count(self.tail, self.head, self.ring.len());
1790         (len, Some(len))
1791     }
1792 }
1793
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1796     #[inline]
1797     fn next_back(&mut self) -> Option<&'a T> {
1798         if self.tail == self.head {
1799             return None;
1800         }
1801         self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1802         unsafe { Some(self.ring.get_unchecked(self.head)) }
1803     }
1804 }
1805
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1808
1809 /// `VecDeque` mutable iterator.
1810 #[stable(feature = "rust1", since = "1.0.0")]
1811 pub struct IterMut<'a, T: 'a> {
1812     ring: &'a mut [T],
1813     tail: usize,
1814     head: usize,
1815 }
1816
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 impl<'a, T> Iterator for IterMut<'a, T> {
1819     type Item = &'a mut T;
1820
1821     #[inline]
1822     fn next(&mut self) -> Option<&'a mut T> {
1823         if self.tail == self.head {
1824             return None;
1825         }
1826         let tail = self.tail;
1827         self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1828
1829         unsafe {
1830             let elem = self.ring.get_unchecked_mut(tail);
1831             Some(&mut *(elem as *mut _))
1832         }
1833     }
1834
1835     #[inline]
1836     fn size_hint(&self) -> (usize, Option<usize>) {
1837         let len = count(self.tail, self.head, self.ring.len());
1838         (len, Some(len))
1839     }
1840 }
1841
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1844     #[inline]
1845     fn next_back(&mut self) -> Option<&'a mut T> {
1846         if self.tail == self.head {
1847             return None;
1848         }
1849         self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1850
1851         unsafe {
1852             let elem = self.ring.get_unchecked_mut(self.head);
1853             Some(&mut *(elem as *mut _))
1854         }
1855     }
1856 }
1857
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1860
1861 /// A by-value VecDeque iterator
1862 #[derive(Clone)]
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 pub struct IntoIter<T> {
1865     inner: VecDeque<T>,
1866 }
1867
1868 #[stable(feature = "rust1", since = "1.0.0")]
1869 impl<T> Iterator for IntoIter<T> {
1870     type Item = T;
1871
1872     #[inline]
1873     fn next(&mut self) -> Option<T> {
1874         self.inner.pop_front()
1875     }
1876
1877     #[inline]
1878     fn size_hint(&self) -> (usize, Option<usize>) {
1879         let len = self.inner.len();
1880         (len, Some(len))
1881     }
1882 }
1883
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 impl<T> DoubleEndedIterator for IntoIter<T> {
1886     #[inline]
1887     fn next_back(&mut self) -> Option<T> {
1888         self.inner.pop_back()
1889     }
1890 }
1891
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 impl<T> ExactSizeIterator for IntoIter<T> {}
1894
1895 /// A draining VecDeque iterator
1896 #[unstable(feature = "drain",
1897            reason = "matches collection reform specification, waiting for dust to settle",
1898            issue = "27711")]
1899 pub struct Drain<'a, T: 'a> {
1900     after_tail: usize,
1901     after_head: usize,
1902     iter: Iter<'a, T>,
1903     deque: *mut VecDeque<T>,
1904 }
1905
1906 #[unstable(feature = "drain", issue = "27711")]
1907 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1908 #[unstable(feature = "drain", issue = "27711")]
1909 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1910
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 impl<'a, T: 'a> Drop for Drain<'a, T> {
1913     fn drop(&mut self) {
1914         for _ in self.by_ref() {}
1915
1916         let source_deque = unsafe { &mut *self.deque };
1917
1918         // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
1919         //
1920         //        T   t   h   H
1921         // [. . . o o x x o o . . .]
1922         //
1923         let orig_tail = source_deque.tail;
1924         let drain_tail = source_deque.head;
1925         let drain_head = self.after_tail;
1926         let orig_head = self.after_head;
1927
1928         let tail_len = count(orig_tail, drain_tail, source_deque.cap());
1929         let head_len = count(drain_head, orig_head, source_deque.cap());
1930
1931         // Restore the original head value
1932         source_deque.head = orig_head;
1933
1934         match (tail_len, head_len) {
1935             (0, 0) => {
1936                 source_deque.head = 0;
1937                 source_deque.tail = 0;
1938             }
1939             (0, _) => {
1940                 source_deque.tail = drain_head;
1941             }
1942             (_, 0) => {
1943                 source_deque.head = drain_tail;
1944             }
1945             _ => {
1946                 unsafe {
1947                     if tail_len <= head_len {
1948                         source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
1949                         source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
1950                     } else {
1951                         source_deque.head = source_deque.wrap_add(drain_tail, head_len);
1952                         source_deque.wrap_copy(drain_tail, drain_head, head_len);
1953                     }
1954                 }
1955             }
1956         }
1957     }
1958 }
1959
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1962     type Item = T;
1963
1964     #[inline]
1965     fn next(&mut self) -> Option<T> {
1966         self.iter.next().map(|elt| unsafe { ptr::read(elt) })
1967     }
1968
1969     #[inline]
1970     fn size_hint(&self) -> (usize, Option<usize>) {
1971         self.iter.size_hint()
1972     }
1973 }
1974
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1977     #[inline]
1978     fn next_back(&mut self) -> Option<T> {
1979         self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
1980     }
1981 }
1982
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1985
1986 #[stable(feature = "rust1", since = "1.0.0")]
1987 impl<A: PartialEq> PartialEq for VecDeque<A> {
1988     fn eq(&self, other: &VecDeque<A>) -> bool {
1989         self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a.eq(b))
1990     }
1991 }
1992
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 impl<A: Eq> Eq for VecDeque<A> {}
1995
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
1998     fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
1999         self.iter().partial_cmp(other.iter())
2000     }
2001 }
2002
2003 #[stable(feature = "rust1", since = "1.0.0")]
2004 impl<A: Ord> Ord for VecDeque<A> {
2005     #[inline]
2006     fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2007         self.iter().cmp(other.iter())
2008     }
2009 }
2010
2011 #[stable(feature = "rust1", since = "1.0.0")]
2012 impl<A: Hash> Hash for VecDeque<A> {
2013     fn hash<H: Hasher>(&self, state: &mut H) {
2014         self.len().hash(state);
2015         for elt in self {
2016             elt.hash(state);
2017         }
2018     }
2019 }
2020
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 impl<A> Index<usize> for VecDeque<A> {
2023     type Output = A;
2024
2025     #[inline]
2026     fn index(&self, index: usize) -> &A {
2027         self.get(index).expect("Out of bounds access")
2028     }
2029 }
2030
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 impl<A> IndexMut<usize> for VecDeque<A> {
2033     #[inline]
2034     fn index_mut(&mut self, index: usize) -> &mut A {
2035         self.get_mut(index).expect("Out of bounds access")
2036     }
2037 }
2038
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 impl<A> FromIterator<A> for VecDeque<A> {
2041     fn from_iter<T: IntoIterator<Item = A>>(iterable: T) -> VecDeque<A> {
2042         let iterator = iterable.into_iter();
2043         let (lower, _) = iterator.size_hint();
2044         let mut deq = VecDeque::with_capacity(lower);
2045         deq.extend(iterator);
2046         deq
2047     }
2048 }
2049
2050 #[stable(feature = "rust1", since = "1.0.0")]
2051 impl<T> IntoIterator for VecDeque<T> {
2052     type Item = T;
2053     type IntoIter = IntoIter<T>;
2054
2055     /// Consumes the list into a front-to-back iterator yielding elements by
2056     /// value.
2057     fn into_iter(self) -> IntoIter<T> {
2058         IntoIter { inner: self }
2059     }
2060 }
2061
2062 #[stable(feature = "rust1", since = "1.0.0")]
2063 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2064     type Item = &'a T;
2065     type IntoIter = Iter<'a, T>;
2066
2067     fn into_iter(self) -> Iter<'a, T> {
2068         self.iter()
2069     }
2070 }
2071
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2074     type Item = &'a mut T;
2075     type IntoIter = IterMut<'a, T>;
2076
2077     fn into_iter(mut self) -> IterMut<'a, T> {
2078         self.iter_mut()
2079     }
2080 }
2081
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 impl<A> Extend<A> for VecDeque<A> {
2084     fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2085         for elt in iter {
2086             self.push_back(elt);
2087         }
2088     }
2089 }
2090
2091 #[stable(feature = "extend_ref", since = "1.2.0")]
2092 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2093     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2094         self.extend(iter.into_iter().cloned());
2095     }
2096 }
2097
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2100     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2101         f.debug_list().entries(self).finish()
2102     }
2103 }
2104
2105 #[cfg(test)]
2106 mod tests {
2107     use core::iter::Iterator;
2108     use core::option::Option::Some;
2109
2110     use test;
2111
2112     use super::VecDeque;
2113
2114     #[bench]
2115     fn bench_push_back_100(b: &mut test::Bencher) {
2116         let mut deq = VecDeque::with_capacity(101);
2117         b.iter(|| {
2118             for i in 0..100 {
2119                 deq.push_back(i);
2120             }
2121             deq.head = 0;
2122             deq.tail = 0;
2123         })
2124     }
2125
2126     #[bench]
2127     fn bench_push_front_100(b: &mut test::Bencher) {
2128         let mut deq = VecDeque::with_capacity(101);
2129         b.iter(|| {
2130             for i in 0..100 {
2131                 deq.push_front(i);
2132             }
2133             deq.head = 0;
2134             deq.tail = 0;
2135         })
2136     }
2137
2138     #[bench]
2139     fn bench_pop_back_100(b: &mut test::Bencher) {
2140         let mut deq = VecDeque::<i32>::with_capacity(101);
2141
2142         b.iter(|| {
2143             deq.head = 100;
2144             deq.tail = 0;
2145             while !deq.is_empty() {
2146                 test::black_box(deq.pop_back());
2147             }
2148         })
2149     }
2150
2151     #[bench]
2152     fn bench_pop_front_100(b: &mut test::Bencher) {
2153         let mut deq = VecDeque::<i32>::with_capacity(101);
2154
2155         b.iter(|| {
2156             deq.head = 100;
2157             deq.tail = 0;
2158             while !deq.is_empty() {
2159                 test::black_box(deq.pop_front());
2160             }
2161         })
2162     }
2163
2164     #[test]
2165     fn test_swap_front_back_remove() {
2166         fn test(back: bool) {
2167             // This test checks that every single combination of tail position and length is tested.
2168             // Capacity 15 should be large enough to cover every case.
2169             let mut tester = VecDeque::with_capacity(15);
2170             let usable_cap = tester.capacity();
2171             let final_len = usable_cap / 2;
2172
2173             for len in 0..final_len {
2174                 let expected = if back {
2175                     (0..len).collect()
2176                 } else {
2177                     (0..len).rev().collect()
2178                 };
2179                 for tail_pos in 0..usable_cap {
2180                     tester.tail = tail_pos;
2181                     tester.head = tail_pos;
2182                     if back {
2183                         for i in 0..len * 2 {
2184                             tester.push_front(i);
2185                         }
2186                         for i in 0..len {
2187                             assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
2188                         }
2189                     } else {
2190                         for i in 0..len * 2 {
2191                             tester.push_back(i);
2192                         }
2193                         for i in 0..len {
2194                             let idx = tester.len() - 1 - i;
2195                             assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
2196                         }
2197                     }
2198                     assert!(tester.tail < tester.cap());
2199                     assert!(tester.head < tester.cap());
2200                     assert_eq!(tester, expected);
2201                 }
2202             }
2203         }
2204         test(true);
2205         test(false);
2206     }
2207
2208     #[test]
2209     fn test_insert() {
2210         // This test checks that every single combination of tail position, length, and
2211         // insertion position is tested. Capacity 15 should be large enough to cover every case.
2212
2213         let mut tester = VecDeque::with_capacity(15);
2214         // can't guarantee we got 15, so have to get what we got.
2215         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2216         // this test isn't covering what it wants to
2217         let cap = tester.capacity();
2218
2219
2220         // len is the length *after* insertion
2221         for len in 1..cap {
2222             // 0, 1, 2, .., len - 1
2223             let expected = (0..).take(len).collect();
2224             for tail_pos in 0..cap {
2225                 for to_insert in 0..len {
2226                     tester.tail = tail_pos;
2227                     tester.head = tail_pos;
2228                     for i in 0..len {
2229                         if i != to_insert {
2230                             tester.push_back(i);
2231                         }
2232                     }
2233                     tester.insert(to_insert, to_insert);
2234                     assert!(tester.tail < tester.cap());
2235                     assert!(tester.head < tester.cap());
2236                     assert_eq!(tester, expected);
2237                 }
2238             }
2239         }
2240     }
2241
2242     #[test]
2243     fn test_remove() {
2244         // This test checks that every single combination of tail position, length, and
2245         // removal position is tested. Capacity 15 should be large enough to cover every case.
2246
2247         let mut tester = VecDeque::with_capacity(15);
2248         // can't guarantee we got 15, so have to get what we got.
2249         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2250         // this test isn't covering what it wants to
2251         let cap = tester.capacity();
2252
2253         // len is the length *after* removal
2254         for len in 0..cap - 1 {
2255             // 0, 1, 2, .., len - 1
2256             let expected = (0..).take(len).collect();
2257             for tail_pos in 0..cap {
2258                 for to_remove in 0..len + 1 {
2259                     tester.tail = tail_pos;
2260                     tester.head = tail_pos;
2261                     for i in 0..len {
2262                         if i == to_remove {
2263                             tester.push_back(1234);
2264                         }
2265                         tester.push_back(i);
2266                     }
2267                     if to_remove == len {
2268                         tester.push_back(1234);
2269                     }
2270                     tester.remove(to_remove);
2271                     assert!(tester.tail < tester.cap());
2272                     assert!(tester.head < tester.cap());
2273                     assert_eq!(tester, expected);
2274                 }
2275             }
2276         }
2277     }
2278
2279     #[test]
2280     fn test_drain() {
2281         let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2282
2283         let cap = tester.capacity();
2284         for len in 0..cap + 1 {
2285             for tail in 0..cap + 1 {
2286                 for drain_start in 0..len + 1 {
2287                     for drain_end in drain_start..len + 1 {
2288                         tester.tail = tail;
2289                         tester.head = tail;
2290                         for i in 0..len {
2291                             tester.push_back(i);
2292                         }
2293
2294                         // Check that we drain the correct values
2295                         let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2296                         let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2297                         assert_eq!(drained, drained_expected);
2298
2299                         // We shouldn't have changed the capacity or made the
2300                         // head or tail out of bounds
2301                         assert_eq!(tester.capacity(), cap);
2302                         assert!(tester.tail < tester.cap());
2303                         assert!(tester.head < tester.cap());
2304
2305                         // We should see the correct values in the VecDeque
2306                         let expected: VecDeque<_> = (0..drain_start)
2307                                                         .chain(drain_end..len)
2308                                                         .collect();
2309                         assert_eq!(expected, tester);
2310                     }
2311                 }
2312             }
2313         }
2314     }
2315
2316     #[test]
2317     fn test_shrink_to_fit() {
2318         // This test checks that every single combination of head and tail position,
2319         // is tested. Capacity 15 should be large enough to cover every case.
2320
2321         let mut tester = VecDeque::with_capacity(15);
2322         // can't guarantee we got 15, so have to get what we got.
2323         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2324         // this test isn't covering what it wants to
2325         let cap = tester.capacity();
2326         tester.reserve(63);
2327         let max_cap = tester.capacity();
2328
2329         for len in 0..cap + 1 {
2330             // 0, 1, 2, .., len - 1
2331             let expected = (0..).take(len).collect();
2332             for tail_pos in 0..max_cap + 1 {
2333                 tester.tail = tail_pos;
2334                 tester.head = tail_pos;
2335                 tester.reserve(63);
2336                 for i in 0..len {
2337                     tester.push_back(i);
2338                 }
2339                 tester.shrink_to_fit();
2340                 assert!(tester.capacity() <= cap);
2341                 assert!(tester.tail < tester.cap());
2342                 assert!(tester.head < tester.cap());
2343                 assert_eq!(tester, expected);
2344             }
2345         }
2346     }
2347
2348     #[test]
2349     fn test_split_off() {
2350         // This test checks that every single combination of tail position, length, and
2351         // split position is tested. Capacity 15 should be large enough to cover every case.
2352
2353         let mut tester = VecDeque::with_capacity(15);
2354         // can't guarantee we got 15, so have to get what we got.
2355         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2356         // this test isn't covering what it wants to
2357         let cap = tester.capacity();
2358
2359         // len is the length *before* splitting
2360         for len in 0..cap {
2361             // index to split at
2362             for at in 0..len + 1 {
2363                 // 0, 1, 2, .., at - 1 (may be empty)
2364                 let expected_self = (0..).take(at).collect();
2365                 // at, at + 1, .., len - 1 (may be empty)
2366                 let expected_other = (at..).take(len - at).collect();
2367
2368                 for tail_pos in 0..cap {
2369                     tester.tail = tail_pos;
2370                     tester.head = tail_pos;
2371                     for i in 0..len {
2372                         tester.push_back(i);
2373                     }
2374                     let result = tester.split_off(at);
2375                     assert!(tester.tail < tester.cap());
2376                     assert!(tester.head < tester.cap());
2377                     assert!(result.tail < result.cap());
2378                     assert!(result.head < result.cap());
2379                     assert_eq!(tester, expected_self);
2380                     assert_eq!(result, expected_other);
2381                 }
2382             }
2383         }
2384     }
2385
2386     #[test]
2387     fn test_zst_push() {
2388         const N: usize = 8;
2389
2390         // Zero sized type
2391         struct Zst;
2392
2393         // Test that for all possible sequences of push_front / push_back,
2394         // we end up with a deque of the correct size
2395
2396         for len in 0..N {
2397             let mut tester = VecDeque::with_capacity(len);
2398             assert_eq!(tester.len(), 0);
2399             assert!(tester.capacity() >= len);
2400             for case in 0..(1 << len) {
2401                 assert_eq!(tester.len(), 0);
2402                 for bit in 0..len {
2403                     if case & (1 << bit) != 0 {
2404                         tester.push_front(Zst);
2405                     } else {
2406                         tester.push_back(Zst);
2407                     }
2408                 }
2409                 assert_eq!(tester.len(), len);
2410                 assert_eq!(tester.iter().count(), len);
2411                 tester.clear();
2412             }
2413         }
2414     }
2415 }