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