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