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