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