]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec_deque.rs
Auto merge of #38581 - frewsxcv:vecdequeue-insert, r=GuillaumeGomez
[rust.git] / src / libcollections / vec_deque.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! VecDeque is a double-ended queue, which is implemented with the help of a
12 //! growing ring buffer.
13 //!
14 //! This queue has `O(1)` amortized inserts and removals from both ends of the
15 //! container. It also has `O(1)` indexing like a vector. The contained elements
16 //! are not required to be copyable, and the queue will be sendable if the
17 //! contained type is sendable.
18
19 #![stable(feature = "rust1", since = "1.0.0")]
20
21 use core::cmp::Ordering;
22 use core::fmt;
23 use core::iter::{repeat, FromIterator, FusedIterator};
24 use core::mem;
25 use core::ops::{Index, IndexMut};
26 use core::ptr;
27 use core::ptr::Shared;
28 use core::slice;
29
30 use core::hash::{Hash, Hasher};
31 use core::cmp;
32
33 use alloc::raw_vec::RawVec;
34
35 use super::range::RangeArgument;
36 use super::vec::Vec;
37
38 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
39 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
40 #[cfg(target_pointer_width = "32")]
41 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
42 #[cfg(target_pointer_width = "64")]
43 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
44
45 /// `VecDeque` is a growable ring buffer, which can be used as a double-ended
46 /// queue efficiently.
47 ///
48 /// The "default" usage of this type as a queue is to use `push_back` to add to
49 /// the queue, and `pop_front` to remove from the queue. `extend` and `append`
50 /// push onto the back in this manner, and iterating over `VecDeque` goes front
51 /// to back.
52 #[stable(feature = "rust1", since = "1.0.0")]
53 pub struct VecDeque<T> {
54     // tail and head are pointers into the buffer. Tail always points
55     // to the first element that could be read, Head always points
56     // to where data should be written.
57     // If tail == head the buffer is empty. The length of the ringbuffer
58     // is defined as the distance between the two.
59     tail: usize,
60     head: usize,
61     buf: RawVec<T>,
62 }
63
64 #[stable(feature = "rust1", since = "1.0.0")]
65 impl<T: Clone> Clone for VecDeque<T> {
66     fn clone(&self) -> VecDeque<T> {
67         self.iter().cloned().collect()
68     }
69 }
70
71 #[stable(feature = "rust1", since = "1.0.0")]
72 impl<T> Drop for VecDeque<T> {
73     #[unsafe_destructor_blind_to_params]
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 = *range.start().unwrap_or(&0);
857         let end = *range.end().unwrap_or(&len);
858         assert!(start <= end, "drain lower bound was too large");
859         assert!(end <= len, "drain upper bound was too large");
860
861         // The deque's elements are parted into three segments:
862         // * self.tail  -> drain_tail
863         // * drain_tail -> drain_head
864         // * drain_head -> self.head
865         //
866         // T = self.tail; H = self.head; t = drain_tail; h = drain_head
867         //
868         // We store drain_tail as self.head, and drain_head and self.head as
869         // after_tail and after_head respectively on the Drain. This also
870         // truncates the effective array such that if the Drain is leaked, we
871         // have forgotten about the potentially moved values after the start of
872         // the drain.
873         //
874         //        T   t   h   H
875         // [. . . o o x x o o . . .]
876         //
877         let drain_tail = self.wrap_add(self.tail, start);
878         let drain_head = self.wrap_add(self.tail, end);
879         let head = self.head;
880
881         // "forget" about the values after the start of the drain until after
882         // the drain is complete and the Drain destructor is run.
883         self.head = drain_tail;
884
885         Drain {
886             deque: unsafe { Shared::new(self as *mut _) },
887             after_tail: drain_head,
888             after_head: head,
889             iter: Iter {
890                 tail: drain_tail,
891                 head: drain_head,
892                 ring: unsafe { self.buffer_as_mut_slice() },
893             },
894         }
895     }
896
897     /// Clears the buffer, removing all values.
898     ///
899     /// # Examples
900     ///
901     /// ```
902     /// use std::collections::VecDeque;
903     ///
904     /// let mut v = VecDeque::new();
905     /// v.push_back(1);
906     /// v.clear();
907     /// assert!(v.is_empty());
908     /// ```
909     #[stable(feature = "rust1", since = "1.0.0")]
910     #[inline]
911     pub fn clear(&mut self) {
912         self.drain(..);
913     }
914
915     /// Returns `true` if the `VecDeque` contains an element equal to the
916     /// given value.
917     ///
918     /// # Examples
919     ///
920     /// ```
921     /// use std::collections::VecDeque;
922     ///
923     /// let mut vector: VecDeque<u32> = VecDeque::new();
924     ///
925     /// vector.push_back(0);
926     /// vector.push_back(1);
927     ///
928     /// assert_eq!(vector.contains(&1), true);
929     /// assert_eq!(vector.contains(&10), false);
930     /// ```
931     #[stable(feature = "vec_deque_contains", since = "1.12.0")]
932     pub fn contains(&self, x: &T) -> bool
933         where T: PartialEq<T>
934     {
935         let (a, b) = self.as_slices();
936         a.contains(x) || b.contains(x)
937     }
938
939     /// Provides a reference to the front element, or `None` if the sequence is
940     /// empty.
941     ///
942     /// # Examples
943     ///
944     /// ```
945     /// use std::collections::VecDeque;
946     ///
947     /// let mut d = VecDeque::new();
948     /// assert_eq!(d.front(), None);
949     ///
950     /// d.push_back(1);
951     /// d.push_back(2);
952     /// assert_eq!(d.front(), Some(&1));
953     /// ```
954     #[stable(feature = "rust1", since = "1.0.0")]
955     pub fn front(&self) -> Option<&T> {
956         if !self.is_empty() {
957             Some(&self[0])
958         } else {
959             None
960         }
961     }
962
963     /// Provides a mutable reference to the front element, or `None` if the
964     /// sequence is empty.
965     ///
966     /// # Examples
967     ///
968     /// ```
969     /// use std::collections::VecDeque;
970     ///
971     /// let mut d = VecDeque::new();
972     /// assert_eq!(d.front_mut(), None);
973     ///
974     /// d.push_back(1);
975     /// d.push_back(2);
976     /// match d.front_mut() {
977     ///     Some(x) => *x = 9,
978     ///     None => (),
979     /// }
980     /// assert_eq!(d.front(), Some(&9));
981     /// ```
982     #[stable(feature = "rust1", since = "1.0.0")]
983     pub fn front_mut(&mut self) -> Option<&mut T> {
984         if !self.is_empty() {
985             Some(&mut self[0])
986         } else {
987             None
988         }
989     }
990
991     /// Provides a reference to the back element, or `None` if the sequence is
992     /// empty.
993     ///
994     /// # Examples
995     ///
996     /// ```
997     /// use std::collections::VecDeque;
998     ///
999     /// let mut d = VecDeque::new();
1000     /// assert_eq!(d.back(), None);
1001     ///
1002     /// d.push_back(1);
1003     /// d.push_back(2);
1004     /// assert_eq!(d.back(), Some(&2));
1005     /// ```
1006     #[stable(feature = "rust1", since = "1.0.0")]
1007     pub fn back(&self) -> Option<&T> {
1008         if !self.is_empty() {
1009             Some(&self[self.len() - 1])
1010         } else {
1011             None
1012         }
1013     }
1014
1015     /// Provides a mutable reference to the back element, or `None` if the
1016     /// sequence is empty.
1017     ///
1018     /// # Examples
1019     ///
1020     /// ```
1021     /// use std::collections::VecDeque;
1022     ///
1023     /// let mut d = VecDeque::new();
1024     /// assert_eq!(d.back(), None);
1025     ///
1026     /// d.push_back(1);
1027     /// d.push_back(2);
1028     /// match d.back_mut() {
1029     ///     Some(x) => *x = 9,
1030     ///     None => (),
1031     /// }
1032     /// assert_eq!(d.back(), Some(&9));
1033     /// ```
1034     #[stable(feature = "rust1", since = "1.0.0")]
1035     pub fn back_mut(&mut self) -> Option<&mut T> {
1036         let len = self.len();
1037         if !self.is_empty() {
1038             Some(&mut self[len - 1])
1039         } else {
1040             None
1041         }
1042     }
1043
1044     /// Removes the first element and returns it, or `None` if the sequence is
1045     /// empty.
1046     ///
1047     /// # Examples
1048     ///
1049     /// ```
1050     /// use std::collections::VecDeque;
1051     ///
1052     /// let mut d = VecDeque::new();
1053     /// d.push_back(1);
1054     /// d.push_back(2);
1055     ///
1056     /// assert_eq!(d.pop_front(), Some(1));
1057     /// assert_eq!(d.pop_front(), Some(2));
1058     /// assert_eq!(d.pop_front(), None);
1059     /// ```
1060     #[stable(feature = "rust1", since = "1.0.0")]
1061     pub fn pop_front(&mut self) -> Option<T> {
1062         if self.is_empty() {
1063             None
1064         } else {
1065             let tail = self.tail;
1066             self.tail = self.wrap_add(self.tail, 1);
1067             unsafe { Some(self.buffer_read(tail)) }
1068         }
1069     }
1070
1071     /// Inserts an element first in the sequence.
1072     ///
1073     /// # Examples
1074     ///
1075     /// ```
1076     /// use std::collections::VecDeque;
1077     ///
1078     /// let mut d = VecDeque::new();
1079     /// d.push_front(1);
1080     /// d.push_front(2);
1081     /// assert_eq!(d.front(), Some(&2));
1082     /// ```
1083     #[stable(feature = "rust1", since = "1.0.0")]
1084     pub fn push_front(&mut self, value: T) {
1085         if self.is_full() {
1086             let old_cap = self.cap();
1087             self.buf.double();
1088             unsafe {
1089                 self.handle_cap_increase(old_cap);
1090             }
1091             debug_assert!(!self.is_full());
1092         }
1093
1094         self.tail = self.wrap_sub(self.tail, 1);
1095         let tail = self.tail;
1096         unsafe {
1097             self.buffer_write(tail, value);
1098         }
1099     }
1100
1101     /// Appends an element to the back of a buffer
1102     ///
1103     /// # Examples
1104     ///
1105     /// ```
1106     /// use std::collections::VecDeque;
1107     ///
1108     /// let mut buf = VecDeque::new();
1109     /// buf.push_back(1);
1110     /// buf.push_back(3);
1111     /// assert_eq!(3, *buf.back().unwrap());
1112     /// ```
1113     #[stable(feature = "rust1", since = "1.0.0")]
1114     pub fn push_back(&mut self, value: T) {
1115         if self.is_full() {
1116             let old_cap = self.cap();
1117             self.buf.double();
1118             unsafe {
1119                 self.handle_cap_increase(old_cap);
1120             }
1121             debug_assert!(!self.is_full());
1122         }
1123
1124         let head = self.head;
1125         self.head = self.wrap_add(self.head, 1);
1126         unsafe { self.buffer_write(head, value) }
1127     }
1128
1129     /// Removes the last element from a buffer and returns it, or `None` if
1130     /// it is empty.
1131     ///
1132     /// # Examples
1133     ///
1134     /// ```
1135     /// use std::collections::VecDeque;
1136     ///
1137     /// let mut buf = VecDeque::new();
1138     /// assert_eq!(buf.pop_back(), None);
1139     /// buf.push_back(1);
1140     /// buf.push_back(3);
1141     /// assert_eq!(buf.pop_back(), Some(3));
1142     /// ```
1143     #[stable(feature = "rust1", since = "1.0.0")]
1144     pub fn pop_back(&mut self) -> Option<T> {
1145         if self.is_empty() {
1146             None
1147         } else {
1148             self.head = self.wrap_sub(self.head, 1);
1149             let head = self.head;
1150             unsafe { Some(self.buffer_read(head)) }
1151         }
1152     }
1153
1154     #[inline]
1155     fn is_contiguous(&self) -> bool {
1156         self.tail <= self.head
1157     }
1158
1159     /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1160     /// last element.
1161     ///
1162     /// This does not preserve ordering, but is O(1).
1163     ///
1164     /// Returns `None` if `index` is out of bounds.
1165     ///
1166     /// Element at index 0 is the front of the queue.
1167     ///
1168     /// # Examples
1169     ///
1170     /// ```
1171     /// use std::collections::VecDeque;
1172     ///
1173     /// let mut buf = VecDeque::new();
1174     /// assert_eq!(buf.swap_remove_back(0), None);
1175     /// buf.push_back(1);
1176     /// buf.push_back(2);
1177     /// buf.push_back(3);
1178     ///
1179     /// assert_eq!(buf.swap_remove_back(0), Some(1));
1180     /// assert_eq!(buf.len(), 2);
1181     /// assert_eq!(buf[0], 3);
1182     /// assert_eq!(buf[1], 2);
1183     /// ```
1184     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1185     pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1186         let length = self.len();
1187         if length > 0 && index < length - 1 {
1188             self.swap(index, length - 1);
1189         } else if index >= length {
1190             return None;
1191         }
1192         self.pop_back()
1193     }
1194
1195     /// Removes an element from anywhere in the `VecDeque` and returns it,
1196     /// replacing it with the first element.
1197     ///
1198     /// This does not preserve ordering, but is O(1).
1199     ///
1200     /// Returns `None` if `index` is out of bounds.
1201     ///
1202     /// Element at index 0 is the front of the queue.
1203     ///
1204     /// # Examples
1205     ///
1206     /// ```
1207     /// use std::collections::VecDeque;
1208     ///
1209     /// let mut buf = VecDeque::new();
1210     /// assert_eq!(buf.swap_remove_front(0), None);
1211     /// buf.push_back(1);
1212     /// buf.push_back(2);
1213     /// buf.push_back(3);
1214     ///
1215     /// assert_eq!(buf.swap_remove_front(2), Some(3));
1216     /// assert_eq!(buf.len(), 2);
1217     /// assert_eq!(buf[0], 2);
1218     /// assert_eq!(buf[1], 1);
1219     /// ```
1220     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1221     pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1222         let length = self.len();
1223         if length > 0 && index < length && index != 0 {
1224             self.swap(index, 0);
1225         } else if index >= length {
1226             return None;
1227         }
1228         self.pop_front()
1229     }
1230
1231     /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices
1232     /// greater than or equal to `index` towards the back.
1233     ///
1234     /// Element at index 0 is the front of the queue.
1235     ///
1236     /// # Panics
1237     ///
1238     /// Panics if `index` is greater than `VecDeque`'s length
1239     ///
1240     /// # Examples
1241     ///
1242     /// ```
1243     /// use std::collections::VecDeque;
1244     ///
1245     /// let mut vec_deque = VecDeque::new();
1246     /// vec_deque.push_back('a');
1247     /// vec_deque.push_back('b');
1248     /// vec_deque.push_back('c');
1249     ///
1250     /// vec_deque.insert(1, 'd');
1251     ///
1252     /// let vec = vec_deque.into_iter().collect::<Vec<_>>();
1253     /// assert_eq!(vec, ['a', 'd', 'b', 'c']);
1254     /// ```
1255     #[stable(feature = "deque_extras_15", since = "1.5.0")]
1256     pub fn insert(&mut self, index: usize, value: T) {
1257         assert!(index <= self.len(), "index out of bounds");
1258         if self.is_full() {
1259             let old_cap = self.cap();
1260             self.buf.double();
1261             unsafe {
1262                 self.handle_cap_increase(old_cap);
1263             }
1264             debug_assert!(!self.is_full());
1265         }
1266
1267         // Move the least number of elements in the ring buffer and insert
1268         // the given object
1269         //
1270         // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1271         //
1272         // There are three main cases:
1273         //  Elements are contiguous
1274         //      - special case when tail is 0
1275         //  Elements are discontiguous and the insert is in the tail section
1276         //  Elements are discontiguous and the insert is in the head section
1277         //
1278         // For each of those there are two more cases:
1279         //  Insert is closer to tail
1280         //  Insert is closer to head
1281         //
1282         // Key: H - self.head
1283         //      T - self.tail
1284         //      o - Valid element
1285         //      I - Insertion element
1286         //      A - The element that should be after the insertion point
1287         //      M - Indicates element was moved
1288
1289         let idx = self.wrap_add(self.tail, index);
1290
1291         let distance_to_tail = index;
1292         let distance_to_head = self.len() - index;
1293
1294         let contiguous = self.is_contiguous();
1295
1296         match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1297             (true, true, _) if index == 0 => {
1298                 // push_front
1299                 //
1300                 //       T
1301                 //       I             H
1302                 //      [A o o o o o o . . . . . . . . .]
1303                 //
1304                 //                       H         T
1305                 //      [A o o o o o o o . . . . . I]
1306                 //
1307
1308                 self.tail = self.wrap_sub(self.tail, 1);
1309             }
1310             (true, true, _) => {
1311                 unsafe {
1312                     // contiguous, insert closer to tail:
1313                     //
1314                     //             T   I         H
1315                     //      [. . . o o A o o o o . . . . . .]
1316                     //
1317                     //           T               H
1318                     //      [. . o o I A o o o o . . . . . .]
1319                     //           M M
1320                     //
1321                     // contiguous, insert closer to tail and tail is 0:
1322                     //
1323                     //
1324                     //       T   I         H
1325                     //      [o o A o o o o . . . . . . . . .]
1326                     //
1327                     //                       H             T
1328                     //      [o I A o o o o o . . . . . . . o]
1329                     //       M                             M
1330
1331                     let new_tail = self.wrap_sub(self.tail, 1);
1332
1333                     self.copy(new_tail, self.tail, 1);
1334                     // Already moved the tail, so we only copy `index - 1` elements.
1335                     self.copy(self.tail, self.tail + 1, index - 1);
1336
1337                     self.tail = new_tail;
1338                 }
1339             }
1340             (true, false, _) => {
1341                 unsafe {
1342                     //  contiguous, insert closer to head:
1343                     //
1344                     //             T       I     H
1345                     //      [. . . o o o o A o o . . . . . .]
1346                     //
1347                     //             T               H
1348                     //      [. . . o o o o I A o o . . . . .]
1349                     //                       M M M
1350
1351                     self.copy(idx + 1, idx, self.head - idx);
1352                     self.head = self.wrap_add(self.head, 1);
1353                 }
1354             }
1355             (false, true, true) => {
1356                 unsafe {
1357                     // discontiguous, insert closer to tail, tail section:
1358                     //
1359                     //                   H         T   I
1360                     //      [o o o o o o . . . . . o o A o o]
1361                     //
1362                     //                   H       T
1363                     //      [o o o o o o . . . . o o I A o o]
1364                     //                           M M
1365
1366                     self.copy(self.tail - 1, self.tail, index);
1367                     self.tail -= 1;
1368                 }
1369             }
1370             (false, false, true) => {
1371                 unsafe {
1372                     // discontiguous, insert closer to head, tail section:
1373                     //
1374                     //           H             T         I
1375                     //      [o o . . . . . . . o o o o o A o]
1376                     //
1377                     //             H           T
1378                     //      [o o o . . . . . . o o o o o I A]
1379                     //       M M M                         M
1380
1381                     // copy elements up to new head
1382                     self.copy(1, 0, self.head);
1383
1384                     // copy last element into empty spot at bottom of buffer
1385                     self.copy(0, self.cap() - 1, 1);
1386
1387                     // move elements from idx to end forward not including ^ element
1388                     self.copy(idx + 1, idx, self.cap() - 1 - idx);
1389
1390                     self.head += 1;
1391                 }
1392             }
1393             (false, true, false) if idx == 0 => {
1394                 unsafe {
1395                     // discontiguous, insert is closer to tail, head section,
1396                     // and is at index zero in the internal buffer:
1397                     //
1398                     //       I                   H     T
1399                     //      [A o o o o o o o o o . . . o o o]
1400                     //
1401                     //                           H   T
1402                     //      [A o o o o o o o o o . . o o o I]
1403                     //                               M M M
1404
1405                     // copy elements up to new tail
1406                     self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1407
1408                     // copy last element into empty spot at bottom of buffer
1409                     self.copy(self.cap() - 1, 0, 1);
1410
1411                     self.tail -= 1;
1412                 }
1413             }
1414             (false, true, false) => {
1415                 unsafe {
1416                     // discontiguous, insert closer to tail, head section:
1417                     //
1418                     //             I             H     T
1419                     //      [o o o A o o o o o o . . . o o o]
1420                     //
1421                     //                           H   T
1422                     //      [o o I A o o o o o o . . o o o o]
1423                     //       M M                     M M M M
1424
1425                     // copy elements up to new tail
1426                     self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1427
1428                     // copy last element into empty spot at bottom of buffer
1429                     self.copy(self.cap() - 1, 0, 1);
1430
1431                     // move elements from idx-1 to end forward not including ^ element
1432                     self.copy(0, 1, idx - 1);
1433
1434                     self.tail -= 1;
1435                 }
1436             }
1437             (false, false, false) => {
1438                 unsafe {
1439                     // discontiguous, insert closer to head, head section:
1440                     //
1441                     //               I     H           T
1442                     //      [o o o o A o o . . . . . . o o o]
1443                     //
1444                     //                     H           T
1445                     //      [o o o o I A o o . . . . . o o o]
1446                     //                 M M M
1447
1448                     self.copy(idx + 1, idx, self.head - idx);
1449                     self.head += 1;
1450                 }
1451             }
1452         }
1453
1454         // tail might've been changed so we need to recalculate
1455         let new_idx = self.wrap_add(self.tail, index);
1456         unsafe {
1457             self.buffer_write(new_idx, value);
1458         }
1459     }
1460
1461     /// Removes and returns the element at `index` from the `VecDeque`.
1462     /// Whichever end is closer to the removal point will be moved to make
1463     /// room, and all the affected elements will be moved to new positions.
1464     /// Returns `None` if `index` is out of bounds.
1465     ///
1466     /// Element at index 0 is the front of the queue.
1467     ///
1468     /// # Examples
1469     ///
1470     /// ```
1471     /// use std::collections::VecDeque;
1472     ///
1473     /// let mut buf = VecDeque::new();
1474     /// buf.push_back(1);
1475     /// buf.push_back(2);
1476     /// buf.push_back(3);
1477     ///
1478     /// assert_eq!(buf.remove(1), Some(2));
1479     /// assert_eq!(buf.get(1), Some(&3));
1480     /// ```
1481     #[stable(feature = "rust1", since = "1.0.0")]
1482     pub fn remove(&mut self, index: usize) -> Option<T> {
1483         if self.is_empty() || self.len() <= index {
1484             return None;
1485         }
1486
1487         // There are three main cases:
1488         //  Elements are contiguous
1489         //  Elements are discontiguous and the removal is in the tail section
1490         //  Elements are discontiguous and the removal is in the head section
1491         //      - special case when elements are technically contiguous,
1492         //        but self.head = 0
1493         //
1494         // For each of those there are two more cases:
1495         //  Insert is closer to tail
1496         //  Insert is closer to head
1497         //
1498         // Key: H - self.head
1499         //      T - self.tail
1500         //      o - Valid element
1501         //      x - Element marked for removal
1502         //      R - Indicates element that is being removed
1503         //      M - Indicates element was moved
1504
1505         let idx = self.wrap_add(self.tail, index);
1506
1507         let elem = unsafe { Some(self.buffer_read(idx)) };
1508
1509         let distance_to_tail = index;
1510         let distance_to_head = self.len() - index;
1511
1512         let contiguous = self.is_contiguous();
1513
1514         match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1515             (true, true, _) => {
1516                 unsafe {
1517                     // contiguous, remove closer to tail:
1518                     //
1519                     //             T   R         H
1520                     //      [. . . o o x o o o o . . . . . .]
1521                     //
1522                     //               T           H
1523                     //      [. . . . o o o o o o . . . . . .]
1524                     //               M M
1525
1526                     self.copy(self.tail + 1, self.tail, index);
1527                     self.tail += 1;
1528                 }
1529             }
1530             (true, false, _) => {
1531                 unsafe {
1532                     // contiguous, remove closer to head:
1533                     //
1534                     //             T       R     H
1535                     //      [. . . o o o o x o o . . . . . .]
1536                     //
1537                     //             T           H
1538                     //      [. . . o o o o o o . . . . . . .]
1539                     //                     M M
1540
1541                     self.copy(idx, idx + 1, self.head - idx - 1);
1542                     self.head -= 1;
1543                 }
1544             }
1545             (false, true, true) => {
1546                 unsafe {
1547                     // discontiguous, remove closer to tail, tail section:
1548                     //
1549                     //                   H         T   R
1550                     //      [o o o o o o . . . . . o o x o o]
1551                     //
1552                     //                   H           T
1553                     //      [o o o o o o . . . . . . o o o o]
1554                     //                               M M
1555
1556                     self.copy(self.tail + 1, self.tail, index);
1557                     self.tail = self.wrap_add(self.tail, 1);
1558                 }
1559             }
1560             (false, false, false) => {
1561                 unsafe {
1562                     // discontiguous, remove closer to head, head section:
1563                     //
1564                     //               R     H           T
1565                     //      [o o o o x o o . . . . . . o o o]
1566                     //
1567                     //                   H             T
1568                     //      [o o o o o o . . . . . . . o o o]
1569                     //               M M
1570
1571                     self.copy(idx, idx + 1, self.head - idx - 1);
1572                     self.head -= 1;
1573                 }
1574             }
1575             (false, false, true) => {
1576                 unsafe {
1577                     // discontiguous, remove closer to head, tail section:
1578                     //
1579                     //             H           T         R
1580                     //      [o o o . . . . . . o o o o o x o]
1581                     //
1582                     //           H             T
1583                     //      [o o . . . . . . . o o o o o o o]
1584                     //       M M                         M M
1585                     //
1586                     // or quasi-discontiguous, remove next to head, tail section:
1587                     //
1588                     //       H                 T         R
1589                     //      [. . . . . . . . . o o o o o x o]
1590                     //
1591                     //                         T           H
1592                     //      [. . . . . . . . . o o o o o o .]
1593                     //                                   M
1594
1595                     // draw in elements in the tail section
1596                     self.copy(idx, idx + 1, self.cap() - idx - 1);
1597
1598                     // Prevents underflow.
1599                     if self.head != 0 {
1600                         // copy first element into empty spot
1601                         self.copy(self.cap() - 1, 0, 1);
1602
1603                         // move elements in the head section backwards
1604                         self.copy(0, 1, self.head - 1);
1605                     }
1606
1607                     self.head = self.wrap_sub(self.head, 1);
1608                 }
1609             }
1610             (false, true, false) => {
1611                 unsafe {
1612                     // discontiguous, remove closer to tail, head section:
1613                     //
1614                     //           R               H     T
1615                     //      [o o x o o o o o o o . . . o o o]
1616                     //
1617                     //                           H       T
1618                     //      [o o o o o o o o o o . . . . o o]
1619                     //       M M M                       M M
1620
1621                     // draw in elements up to idx
1622                     self.copy(1, 0, idx);
1623
1624                     // copy last element into empty spot
1625                     self.copy(0, self.cap() - 1, 1);
1626
1627                     // move elements from tail to end forward, excluding the last one
1628                     self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1629
1630                     self.tail = self.wrap_add(self.tail, 1);
1631                 }
1632             }
1633         }
1634
1635         return elem;
1636     }
1637
1638     /// Splits the collection into two at the given index.
1639     ///
1640     /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1641     /// and the returned `Self` contains elements `[at, len)`.
1642     ///
1643     /// Note that the capacity of `self` does not change.
1644     ///
1645     /// Element at index 0 is the front of the queue.
1646     ///
1647     /// # Panics
1648     ///
1649     /// Panics if `at > len`
1650     ///
1651     /// # Examples
1652     ///
1653     /// ```
1654     /// use std::collections::VecDeque;
1655     ///
1656     /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1657     /// let buf2 = buf.split_off(1);
1658     /// // buf = [1], buf2 = [2, 3]
1659     /// assert_eq!(buf.len(), 1);
1660     /// assert_eq!(buf2.len(), 2);
1661     /// ```
1662     #[inline]
1663     #[stable(feature = "split_off", since = "1.4.0")]
1664     pub fn split_off(&mut self, at: usize) -> Self {
1665         let len = self.len();
1666         assert!(at <= len, "`at` out of bounds");
1667
1668         let other_len = len - at;
1669         let mut other = VecDeque::with_capacity(other_len);
1670
1671         unsafe {
1672             let (first_half, second_half) = self.as_slices();
1673
1674             let first_len = first_half.len();
1675             let second_len = second_half.len();
1676             if at < first_len {
1677                 // `at` lies in the first half.
1678                 let amount_in_first = first_len - at;
1679
1680                 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1681                                          other.ptr(),
1682                                          amount_in_first);
1683
1684                 // just take all of the second half.
1685                 ptr::copy_nonoverlapping(second_half.as_ptr(),
1686                                          other.ptr().offset(amount_in_first as isize),
1687                                          second_len);
1688             } else {
1689                 // `at` lies in the second half, need to factor in the elements we skipped
1690                 // in the first half.
1691                 let offset = at - first_len;
1692                 let amount_in_second = second_len - offset;
1693                 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1694                                          other.ptr(),
1695                                          amount_in_second);
1696             }
1697         }
1698
1699         // Cleanup where the ends of the buffers are
1700         self.head = self.wrap_sub(self.head, other_len);
1701         other.head = other.wrap_index(other_len);
1702
1703         other
1704     }
1705
1706     /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1707     ///
1708     /// # Panics
1709     ///
1710     /// Panics if the new number of elements in self overflows a `usize`.
1711     ///
1712     /// # Examples
1713     ///
1714     /// ```
1715     /// use std::collections::VecDeque;
1716     ///
1717     /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1718     /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
1719     /// buf.append(&mut buf2);
1720     /// assert_eq!(buf.len(), 6);
1721     /// assert_eq!(buf2.len(), 0);
1722     /// ```
1723     #[inline]
1724     #[stable(feature = "append", since = "1.4.0")]
1725     pub fn append(&mut self, other: &mut Self) {
1726         // naive impl
1727         self.extend(other.drain(..));
1728     }
1729
1730     /// Retains only the elements specified by the predicate.
1731     ///
1732     /// In other words, remove all elements `e` such that `f(&e)` returns false.
1733     /// This method operates in place and preserves the order of the retained
1734     /// elements.
1735     ///
1736     /// # Examples
1737     ///
1738     /// ```
1739     /// use std::collections::VecDeque;
1740     ///
1741     /// let mut buf = VecDeque::new();
1742     /// buf.extend(1..5);
1743     /// buf.retain(|&x| x%2 == 0);
1744     ///
1745     /// let v: Vec<_> = buf.into_iter().collect();
1746     /// assert_eq!(&v[..], &[2, 4]);
1747     /// ```
1748     #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1749     pub fn retain<F>(&mut self, mut f: F)
1750         where F: FnMut(&T) -> bool
1751     {
1752         let len = self.len();
1753         let mut del = 0;
1754         for i in 0..len {
1755             if !f(&self[i]) {
1756                 del += 1;
1757             } else if del > 0 {
1758                 self.swap(i - del, i);
1759             }
1760         }
1761         if del > 0 {
1762             self.truncate(len - del);
1763         }
1764     }
1765 }
1766
1767 impl<T: Clone> VecDeque<T> {
1768     /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1769     /// either by removing excess elements or by appending copies of a value to the back.
1770     ///
1771     /// # Examples
1772     ///
1773     /// ```
1774     /// #![feature(deque_extras)]
1775     ///
1776     /// use std::collections::VecDeque;
1777     ///
1778     /// let mut buf = VecDeque::new();
1779     /// buf.push_back(5);
1780     /// buf.push_back(10);
1781     /// buf.push_back(15);
1782     /// buf.resize(2, 0);
1783     /// buf.resize(6, 20);
1784     /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
1785     ///     assert_eq!(a, b);
1786     /// }
1787     /// ```
1788     #[unstable(feature = "deque_extras",
1789                reason = "matches collection reform specification; waiting on panic semantics",
1790                issue = "27788")]
1791     pub fn resize(&mut self, new_len: usize, value: T) {
1792         let len = self.len();
1793
1794         if new_len > len {
1795             self.extend(repeat(value).take(new_len - len))
1796         } else {
1797             self.truncate(new_len);
1798         }
1799     }
1800 }
1801
1802 /// Returns the index in the underlying buffer for a given logical element index.
1803 #[inline]
1804 fn wrap_index(index: usize, size: usize) -> usize {
1805     // size is always a power of 2
1806     debug_assert!(size.is_power_of_two());
1807     index & (size - 1)
1808 }
1809
1810 /// Returns the two slices that cover the VecDeque's valid range
1811 trait RingSlices: Sized {
1812     fn slice(self, from: usize, to: usize) -> Self;
1813     fn split_at(self, i: usize) -> (Self, Self);
1814
1815     fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
1816         let contiguous = tail <= head;
1817         if contiguous {
1818             let (empty, buf) = buf.split_at(0);
1819             (buf.slice(tail, head), empty)
1820         } else {
1821             let (mid, right) = buf.split_at(tail);
1822             let (left, _) = mid.split_at(head);
1823             (right, left)
1824         }
1825     }
1826 }
1827
1828 impl<'a, T> RingSlices for &'a [T] {
1829     fn slice(self, from: usize, to: usize) -> Self {
1830         &self[from..to]
1831     }
1832     fn split_at(self, i: usize) -> (Self, Self) {
1833         (*self).split_at(i)
1834     }
1835 }
1836
1837 impl<'a, T> RingSlices for &'a mut [T] {
1838     fn slice(self, from: usize, to: usize) -> Self {
1839         &mut self[from..to]
1840     }
1841     fn split_at(self, i: usize) -> (Self, Self) {
1842         (*self).split_at_mut(i)
1843     }
1844 }
1845
1846 /// Calculate the number of elements left to be read in the buffer
1847 #[inline]
1848 fn count(tail: usize, head: usize, size: usize) -> usize {
1849     // size is always a power of 2
1850     (head.wrapping_sub(tail)) & (size - 1)
1851 }
1852
1853 /// `VecDeque` iterator.
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 pub struct Iter<'a, T: 'a> {
1856     ring: &'a [T],
1857     tail: usize,
1858     head: usize,
1859 }
1860
1861 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<'a, T> Clone for Iter<'a, T> {
1864     fn clone(&self) -> Iter<'a, T> {
1865         Iter {
1866             ring: self.ring,
1867             tail: self.tail,
1868             head: self.head,
1869         }
1870     }
1871 }
1872
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 impl<'a, T> Iterator for Iter<'a, T> {
1875     type Item = &'a T;
1876
1877     #[inline]
1878     fn next(&mut self) -> Option<&'a T> {
1879         if self.tail == self.head {
1880             return None;
1881         }
1882         let tail = self.tail;
1883         self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1884         unsafe { Some(self.ring.get_unchecked(tail)) }
1885     }
1886
1887     #[inline]
1888     fn size_hint(&self) -> (usize, Option<usize>) {
1889         let len = count(self.tail, self.head, self.ring.len());
1890         (len, Some(len))
1891     }
1892
1893     fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
1894         where F: FnMut(Acc, Self::Item) -> Acc
1895     {
1896         let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
1897         accum = front.iter().fold(accum, &mut f);
1898         back.iter().fold(accum, &mut f)
1899     }
1900 }
1901
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1904     #[inline]
1905     fn next_back(&mut self) -> Option<&'a T> {
1906         if self.tail == self.head {
1907             return None;
1908         }
1909         self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1910         unsafe { Some(self.ring.get_unchecked(self.head)) }
1911     }
1912 }
1913
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1916     fn is_empty(&self) -> bool {
1917         self.head == self.tail
1918     }
1919 }
1920
1921 #[unstable(feature = "fused", issue = "35602")]
1922 impl<'a, T> FusedIterator for Iter<'a, T> {}
1923
1924
1925 /// `VecDeque` mutable iterator.
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 pub struct IterMut<'a, T: 'a> {
1928     ring: &'a mut [T],
1929     tail: usize,
1930     head: usize,
1931 }
1932
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 impl<'a, T> Iterator for IterMut<'a, T> {
1935     type Item = &'a mut T;
1936
1937     #[inline]
1938     fn next(&mut self) -> Option<&'a mut T> {
1939         if self.tail == self.head {
1940             return None;
1941         }
1942         let tail = self.tail;
1943         self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1944
1945         unsafe {
1946             let elem = self.ring.get_unchecked_mut(tail);
1947             Some(&mut *(elem as *mut _))
1948         }
1949     }
1950
1951     #[inline]
1952     fn size_hint(&self) -> (usize, Option<usize>) {
1953         let len = count(self.tail, self.head, self.ring.len());
1954         (len, Some(len))
1955     }
1956
1957     fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
1958         where F: FnMut(Acc, Self::Item) -> Acc
1959     {
1960         let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
1961         accum = front.iter_mut().fold(accum, &mut f);
1962         back.iter_mut().fold(accum, &mut f)
1963     }
1964 }
1965
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1968     #[inline]
1969     fn next_back(&mut self) -> Option<&'a mut T> {
1970         if self.tail == self.head {
1971             return None;
1972         }
1973         self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1974
1975         unsafe {
1976             let elem = self.ring.get_unchecked_mut(self.head);
1977             Some(&mut *(elem as *mut _))
1978         }
1979     }
1980 }
1981
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1984     fn is_empty(&self) -> bool {
1985         self.head == self.tail
1986     }
1987 }
1988
1989 #[unstable(feature = "fused", issue = "35602")]
1990 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1991
1992 /// A by-value VecDeque iterator
1993 #[derive(Clone)]
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 pub struct IntoIter<T> {
1996     inner: VecDeque<T>,
1997 }
1998
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 impl<T> Iterator for IntoIter<T> {
2001     type Item = T;
2002
2003     #[inline]
2004     fn next(&mut self) -> Option<T> {
2005         self.inner.pop_front()
2006     }
2007
2008     #[inline]
2009     fn size_hint(&self) -> (usize, Option<usize>) {
2010         let len = self.inner.len();
2011         (len, Some(len))
2012     }
2013 }
2014
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 impl<T> DoubleEndedIterator for IntoIter<T> {
2017     #[inline]
2018     fn next_back(&mut self) -> Option<T> {
2019         self.inner.pop_back()
2020     }
2021 }
2022
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 impl<T> ExactSizeIterator for IntoIter<T> {
2025     fn is_empty(&self) -> bool {
2026         self.inner.is_empty()
2027     }
2028 }
2029
2030 #[unstable(feature = "fused", issue = "35602")]
2031 impl<T> FusedIterator for IntoIter<T> {}
2032
2033 /// A draining VecDeque iterator
2034 #[stable(feature = "drain", since = "1.6.0")]
2035 pub struct Drain<'a, T: 'a> {
2036     after_tail: usize,
2037     after_head: usize,
2038     iter: Iter<'a, T>,
2039     deque: Shared<VecDeque<T>>,
2040 }
2041
2042 #[stable(feature = "drain", since = "1.6.0")]
2043 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2044 #[stable(feature = "drain", since = "1.6.0")]
2045 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2046
2047 #[stable(feature = "drain", since = "1.6.0")]
2048 impl<'a, T: 'a> Drop for Drain<'a, T> {
2049     fn drop(&mut self) {
2050         for _ in self.by_ref() {}
2051
2052         let source_deque = unsafe { &mut **self.deque };
2053
2054         // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
2055         //
2056         //        T   t   h   H
2057         // [. . . o o x x o o . . .]
2058         //
2059         let orig_tail = source_deque.tail;
2060         let drain_tail = source_deque.head;
2061         let drain_head = self.after_tail;
2062         let orig_head = self.after_head;
2063
2064         let tail_len = count(orig_tail, drain_tail, source_deque.cap());
2065         let head_len = count(drain_head, orig_head, source_deque.cap());
2066
2067         // Restore the original head value
2068         source_deque.head = orig_head;
2069
2070         match (tail_len, head_len) {
2071             (0, 0) => {
2072                 source_deque.head = 0;
2073                 source_deque.tail = 0;
2074             }
2075             (0, _) => {
2076                 source_deque.tail = drain_head;
2077             }
2078             (_, 0) => {
2079                 source_deque.head = drain_tail;
2080             }
2081             _ => unsafe {
2082                 if tail_len <= head_len {
2083                     source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
2084                     source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
2085                 } else {
2086                     source_deque.head = source_deque.wrap_add(drain_tail, head_len);
2087                     source_deque.wrap_copy(drain_tail, drain_head, head_len);
2088                 }
2089             },
2090         }
2091     }
2092 }
2093
2094 #[stable(feature = "drain", since = "1.6.0")]
2095 impl<'a, T: 'a> Iterator for Drain<'a, T> {
2096     type Item = T;
2097
2098     #[inline]
2099     fn next(&mut self) -> Option<T> {
2100         self.iter.next().map(|elt| unsafe { ptr::read(elt) })
2101     }
2102
2103     #[inline]
2104     fn size_hint(&self) -> (usize, Option<usize>) {
2105         self.iter.size_hint()
2106     }
2107 }
2108
2109 #[stable(feature = "drain", since = "1.6.0")]
2110 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
2111     #[inline]
2112     fn next_back(&mut self) -> Option<T> {
2113         self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
2114     }
2115 }
2116
2117 #[stable(feature = "drain", since = "1.6.0")]
2118 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
2119
2120 #[unstable(feature = "fused", issue = "35602")]
2121 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
2122
2123 #[stable(feature = "rust1", since = "1.0.0")]
2124 impl<A: PartialEq> PartialEq for VecDeque<A> {
2125     fn eq(&self, other: &VecDeque<A>) -> bool {
2126         if self.len() != other.len() {
2127             return false;
2128         }
2129         let (sa, sb) = self.as_slices();
2130         let (oa, ob) = other.as_slices();
2131         if sa.len() == oa.len() {
2132             sa == oa && sb == ob
2133         } else if sa.len() < oa.len() {
2134             // Always divisible in three sections, for example:
2135             // self:  [a b c|d e f]
2136             // other: [0 1 2 3|4 5]
2137             // front = 3, mid = 1,
2138             // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2139             let front = sa.len();
2140             let mid = oa.len() - front;
2141
2142             let (oa_front, oa_mid) = oa.split_at(front);
2143             let (sb_mid, sb_back) = sb.split_at(mid);
2144             debug_assert_eq!(sa.len(), oa_front.len());
2145             debug_assert_eq!(sb_mid.len(), oa_mid.len());
2146             debug_assert_eq!(sb_back.len(), ob.len());
2147             sa == oa_front && sb_mid == oa_mid && sb_back == ob
2148         } else {
2149             let front = oa.len();
2150             let mid = sa.len() - front;
2151
2152             let (sa_front, sa_mid) = sa.split_at(front);
2153             let (ob_mid, ob_back) = ob.split_at(mid);
2154             debug_assert_eq!(sa_front.len(), oa.len());
2155             debug_assert_eq!(sa_mid.len(), ob_mid.len());
2156             debug_assert_eq!(sb.len(), ob_back.len());
2157             sa_front == oa && sa_mid == ob_mid && sb == ob_back
2158         }
2159     }
2160 }
2161
2162 #[stable(feature = "rust1", since = "1.0.0")]
2163 impl<A: Eq> Eq for VecDeque<A> {}
2164
2165 #[stable(feature = "rust1", since = "1.0.0")]
2166 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2167     fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2168         self.iter().partial_cmp(other.iter())
2169     }
2170 }
2171
2172 #[stable(feature = "rust1", since = "1.0.0")]
2173 impl<A: Ord> Ord for VecDeque<A> {
2174     #[inline]
2175     fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2176         self.iter().cmp(other.iter())
2177     }
2178 }
2179
2180 #[stable(feature = "rust1", since = "1.0.0")]
2181 impl<A: Hash> Hash for VecDeque<A> {
2182     fn hash<H: Hasher>(&self, state: &mut H) {
2183         self.len().hash(state);
2184         let (a, b) = self.as_slices();
2185         Hash::hash_slice(a, state);
2186         Hash::hash_slice(b, state);
2187     }
2188 }
2189
2190 #[stable(feature = "rust1", since = "1.0.0")]
2191 impl<A> Index<usize> for VecDeque<A> {
2192     type Output = A;
2193
2194     #[inline]
2195     fn index(&self, index: usize) -> &A {
2196         self.get(index).expect("Out of bounds access")
2197     }
2198 }
2199
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 impl<A> IndexMut<usize> for VecDeque<A> {
2202     #[inline]
2203     fn index_mut(&mut self, index: usize) -> &mut A {
2204         self.get_mut(index).expect("Out of bounds access")
2205     }
2206 }
2207
2208 #[stable(feature = "rust1", since = "1.0.0")]
2209 impl<A> FromIterator<A> for VecDeque<A> {
2210     fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2211         let iterator = iter.into_iter();
2212         let (lower, _) = iterator.size_hint();
2213         let mut deq = VecDeque::with_capacity(lower);
2214         deq.extend(iterator);
2215         deq
2216     }
2217 }
2218
2219 #[stable(feature = "rust1", since = "1.0.0")]
2220 impl<T> IntoIterator for VecDeque<T> {
2221     type Item = T;
2222     type IntoIter = IntoIter<T>;
2223
2224     /// Consumes the list into a front-to-back iterator yielding elements by
2225     /// value.
2226     fn into_iter(self) -> IntoIter<T> {
2227         IntoIter { inner: self }
2228     }
2229 }
2230
2231 #[stable(feature = "rust1", since = "1.0.0")]
2232 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2233     type Item = &'a T;
2234     type IntoIter = Iter<'a, T>;
2235
2236     fn into_iter(self) -> Iter<'a, T> {
2237         self.iter()
2238     }
2239 }
2240
2241 #[stable(feature = "rust1", since = "1.0.0")]
2242 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2243     type Item = &'a mut T;
2244     type IntoIter = IterMut<'a, T>;
2245
2246     fn into_iter(mut self) -> IterMut<'a, T> {
2247         self.iter_mut()
2248     }
2249 }
2250
2251 #[stable(feature = "rust1", since = "1.0.0")]
2252 impl<A> Extend<A> for VecDeque<A> {
2253     fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2254         for elt in iter {
2255             self.push_back(elt);
2256         }
2257     }
2258 }
2259
2260 #[stable(feature = "extend_ref", since = "1.2.0")]
2261 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2262     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2263         self.extend(iter.into_iter().cloned());
2264     }
2265 }
2266
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2269     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2270         f.debug_list().entries(self).finish()
2271     }
2272 }
2273
2274 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2275 impl<T> From<Vec<T>> for VecDeque<T> {
2276     fn from(mut other: Vec<T>) -> Self {
2277         unsafe {
2278             let other_buf = other.as_mut_ptr();
2279             let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
2280             let len = other.len();
2281             mem::forget(other);
2282
2283             // We need to extend the buf if it's not a power of two, too small
2284             // or doesn't have at least one free space
2285             if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) ||
2286                (buf.cap() == len) {
2287                 let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
2288                 buf.reserve_exact(len, cap - len);
2289             }
2290
2291             VecDeque {
2292                 tail: 0,
2293                 head: len,
2294                 buf: buf,
2295             }
2296         }
2297     }
2298 }
2299
2300 #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
2301 impl<T> From<VecDeque<T>> for Vec<T> {
2302     fn from(other: VecDeque<T>) -> Self {
2303         unsafe {
2304             let buf = other.buf.ptr();
2305             let len = other.len();
2306             let tail = other.tail;
2307             let head = other.head;
2308             let cap = other.cap();
2309
2310             // Need to move the ring to the front of the buffer, as vec will expect this.
2311             if other.is_contiguous() {
2312                 ptr::copy(buf.offset(tail as isize), buf, len);
2313             } else {
2314                 if (tail - head) >= cmp::min((cap - tail), head) {
2315                     // There is enough free space in the centre for the shortest block so we can
2316                     // do this in at most three copy moves.
2317                     if (cap - tail) > head {
2318                         // right hand block is the long one; move that enough for the left
2319                         ptr::copy(buf.offset(tail as isize),
2320                                   buf.offset((tail - head) as isize),
2321                                   cap - tail);
2322                         // copy left in the end
2323                         ptr::copy(buf, buf.offset((cap - head) as isize), head);
2324                         // shift the new thing to the start
2325                         ptr::copy(buf.offset((tail - head) as isize), buf, len);
2326                     } else {
2327                         // left hand block is the long one, we can do it in two!
2328                         ptr::copy(buf, buf.offset((cap - tail) as isize), head);
2329                         ptr::copy(buf.offset(tail as isize), buf, cap - tail);
2330                     }
2331                 } else {
2332                     // Need to use N swaps to move the ring
2333                     // We can use the space at the end of the ring as a temp store
2334
2335                     let mut left_edge: usize = 0;
2336                     let mut right_edge: usize = tail;
2337
2338                     // The general problem looks like this
2339                     // GHIJKLM...ABCDEF - before any swaps
2340                     // ABCDEFM...GHIJKL - after 1 pass of swaps
2341                     // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
2342                     //                  - then restart the algorithm with a new (smaller) store
2343                     // Sometimes the temp store is reached when the right edge is at the end
2344                     // of the buffer - this means we've hit the right order with fewer swaps!
2345                     // E.g
2346                     // EF..ABCD
2347                     // ABCDEF.. - after four only swaps we've finished
2348
2349                     while left_edge < len && right_edge != cap {
2350                         let mut right_offset = 0;
2351                         for i in left_edge..right_edge {
2352                             right_offset = (i - left_edge) % (cap - right_edge);
2353                             let src: isize = (right_edge + right_offset) as isize;
2354                             ptr::swap(buf.offset(i as isize), buf.offset(src));
2355                         }
2356                         let n_ops = right_edge - left_edge;
2357                         left_edge += n_ops;
2358                         right_edge += right_offset + 1;
2359
2360                     }
2361                 }
2362
2363             }
2364             let out = Vec::from_raw_parts(buf, len, cap);
2365             mem::forget(other);
2366             out
2367         }
2368     }
2369 }
2370
2371 #[cfg(test)]
2372 mod tests {
2373     use test;
2374
2375     use super::VecDeque;
2376
2377     #[bench]
2378     fn bench_push_back_100(b: &mut test::Bencher) {
2379         let mut deq = VecDeque::with_capacity(101);
2380         b.iter(|| {
2381             for i in 0..100 {
2382                 deq.push_back(i);
2383             }
2384             deq.head = 0;
2385             deq.tail = 0;
2386         })
2387     }
2388
2389     #[bench]
2390     fn bench_push_front_100(b: &mut test::Bencher) {
2391         let mut deq = VecDeque::with_capacity(101);
2392         b.iter(|| {
2393             for i in 0..100 {
2394                 deq.push_front(i);
2395             }
2396             deq.head = 0;
2397             deq.tail = 0;
2398         })
2399     }
2400
2401     #[bench]
2402     fn bench_pop_back_100(b: &mut test::Bencher) {
2403         let mut deq = VecDeque::<i32>::with_capacity(101);
2404
2405         b.iter(|| {
2406             deq.head = 100;
2407             deq.tail = 0;
2408             while !deq.is_empty() {
2409                 test::black_box(deq.pop_back());
2410             }
2411         })
2412     }
2413
2414     #[bench]
2415     fn bench_pop_front_100(b: &mut test::Bencher) {
2416         let mut deq = VecDeque::<i32>::with_capacity(101);
2417
2418         b.iter(|| {
2419             deq.head = 100;
2420             deq.tail = 0;
2421             while !deq.is_empty() {
2422                 test::black_box(deq.pop_front());
2423             }
2424         })
2425     }
2426
2427     #[test]
2428     fn test_swap_front_back_remove() {
2429         fn test(back: bool) {
2430             // This test checks that every single combination of tail position and length is tested.
2431             // Capacity 15 should be large enough to cover every case.
2432             let mut tester = VecDeque::with_capacity(15);
2433             let usable_cap = tester.capacity();
2434             let final_len = usable_cap / 2;
2435
2436             for len in 0..final_len {
2437                 let expected = if back {
2438                     (0..len).collect()
2439                 } else {
2440                     (0..len).rev().collect()
2441                 };
2442                 for tail_pos in 0..usable_cap {
2443                     tester.tail = tail_pos;
2444                     tester.head = tail_pos;
2445                     if back {
2446                         for i in 0..len * 2 {
2447                             tester.push_front(i);
2448                         }
2449                         for i in 0..len {
2450                             assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2451                         }
2452                     } else {
2453                         for i in 0..len * 2 {
2454                             tester.push_back(i);
2455                         }
2456                         for i in 0..len {
2457                             let idx = tester.len() - 1 - i;
2458                             assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2459                         }
2460                     }
2461                     assert!(tester.tail < tester.cap());
2462                     assert!(tester.head < tester.cap());
2463                     assert_eq!(tester, expected);
2464                 }
2465             }
2466         }
2467         test(true);
2468         test(false);
2469     }
2470
2471     #[test]
2472     fn test_insert() {
2473         // This test checks that every single combination of tail position, length, and
2474         // insertion position is tested. Capacity 15 should be large enough to cover every case.
2475
2476         let mut tester = VecDeque::with_capacity(15);
2477         // can't guarantee we got 15, so have to get what we got.
2478         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2479         // this test isn't covering what it wants to
2480         let cap = tester.capacity();
2481
2482
2483         // len is the length *after* insertion
2484         for len in 1..cap {
2485             // 0, 1, 2, .., len - 1
2486             let expected = (0..).take(len).collect();
2487             for tail_pos in 0..cap {
2488                 for to_insert in 0..len {
2489                     tester.tail = tail_pos;
2490                     tester.head = tail_pos;
2491                     for i in 0..len {
2492                         if i != to_insert {
2493                             tester.push_back(i);
2494                         }
2495                     }
2496                     tester.insert(to_insert, to_insert);
2497                     assert!(tester.tail < tester.cap());
2498                     assert!(tester.head < tester.cap());
2499                     assert_eq!(tester, expected);
2500                 }
2501             }
2502         }
2503     }
2504
2505     #[test]
2506     fn test_remove() {
2507         // This test checks that every single combination of tail position, length, and
2508         // removal position is tested. Capacity 15 should be large enough to cover every case.
2509
2510         let mut tester = VecDeque::with_capacity(15);
2511         // can't guarantee we got 15, so have to get what we got.
2512         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2513         // this test isn't covering what it wants to
2514         let cap = tester.capacity();
2515
2516         // len is the length *after* removal
2517         for len in 0..cap - 1 {
2518             // 0, 1, 2, .., len - 1
2519             let expected = (0..).take(len).collect();
2520             for tail_pos in 0..cap {
2521                 for to_remove in 0..len + 1 {
2522                     tester.tail = tail_pos;
2523                     tester.head = tail_pos;
2524                     for i in 0..len {
2525                         if i == to_remove {
2526                             tester.push_back(1234);
2527                         }
2528                         tester.push_back(i);
2529                     }
2530                     if to_remove == len {
2531                         tester.push_back(1234);
2532                     }
2533                     tester.remove(to_remove);
2534                     assert!(tester.tail < tester.cap());
2535                     assert!(tester.head < tester.cap());
2536                     assert_eq!(tester, expected);
2537                 }
2538             }
2539         }
2540     }
2541
2542     #[test]
2543     fn test_drain() {
2544         let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2545
2546         let cap = tester.capacity();
2547         for len in 0..cap + 1 {
2548             for tail in 0..cap + 1 {
2549                 for drain_start in 0..len + 1 {
2550                     for drain_end in drain_start..len + 1 {
2551                         tester.tail = tail;
2552                         tester.head = tail;
2553                         for i in 0..len {
2554                             tester.push_back(i);
2555                         }
2556
2557                         // Check that we drain the correct values
2558                         let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2559                         let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2560                         assert_eq!(drained, drained_expected);
2561
2562                         // We shouldn't have changed the capacity or made the
2563                         // head or tail out of bounds
2564                         assert_eq!(tester.capacity(), cap);
2565                         assert!(tester.tail < tester.cap());
2566                         assert!(tester.head < tester.cap());
2567
2568                         // We should see the correct values in the VecDeque
2569                         let expected: VecDeque<_> = (0..drain_start)
2570                             .chain(drain_end..len)
2571                             .collect();
2572                         assert_eq!(expected, tester);
2573                     }
2574                 }
2575             }
2576         }
2577     }
2578
2579     #[test]
2580     fn test_shrink_to_fit() {
2581         // This test checks that every single combination of head and tail position,
2582         // is tested. Capacity 15 should be large enough to cover every case.
2583
2584         let mut tester = VecDeque::with_capacity(15);
2585         // can't guarantee we got 15, so have to get what we got.
2586         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2587         // this test isn't covering what it wants to
2588         let cap = tester.capacity();
2589         tester.reserve(63);
2590         let max_cap = tester.capacity();
2591
2592         for len in 0..cap + 1 {
2593             // 0, 1, 2, .., len - 1
2594             let expected = (0..).take(len).collect();
2595             for tail_pos in 0..max_cap + 1 {
2596                 tester.tail = tail_pos;
2597                 tester.head = tail_pos;
2598                 tester.reserve(63);
2599                 for i in 0..len {
2600                     tester.push_back(i);
2601                 }
2602                 tester.shrink_to_fit();
2603                 assert!(tester.capacity() <= cap);
2604                 assert!(tester.tail < tester.cap());
2605                 assert!(tester.head < tester.cap());
2606                 assert_eq!(tester, expected);
2607             }
2608         }
2609     }
2610
2611     #[test]
2612     fn test_split_off() {
2613         // This test checks that every single combination of tail position, length, and
2614         // split position is tested. Capacity 15 should be large enough to cover every case.
2615
2616         let mut tester = VecDeque::with_capacity(15);
2617         // can't guarantee we got 15, so have to get what we got.
2618         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2619         // this test isn't covering what it wants to
2620         let cap = tester.capacity();
2621
2622         // len is the length *before* splitting
2623         for len in 0..cap {
2624             // index to split at
2625             for at in 0..len + 1 {
2626                 // 0, 1, 2, .., at - 1 (may be empty)
2627                 let expected_self = (0..).take(at).collect();
2628                 // at, at + 1, .., len - 1 (may be empty)
2629                 let expected_other = (at..).take(len - at).collect();
2630
2631                 for tail_pos in 0..cap {
2632                     tester.tail = tail_pos;
2633                     tester.head = tail_pos;
2634                     for i in 0..len {
2635                         tester.push_back(i);
2636                     }
2637                     let result = tester.split_off(at);
2638                     assert!(tester.tail < tester.cap());
2639                     assert!(tester.head < tester.cap());
2640                     assert!(result.tail < result.cap());
2641                     assert!(result.head < result.cap());
2642                     assert_eq!(tester, expected_self);
2643                     assert_eq!(result, expected_other);
2644                 }
2645             }
2646         }
2647     }
2648
2649     #[test]
2650     fn test_from_vec() {
2651         use super::super::vec::Vec;
2652         for cap in 0..35 {
2653             for len in 0..cap + 1 {
2654                 let mut vec = Vec::with_capacity(cap);
2655                 vec.extend(0..len);
2656
2657                 let vd = VecDeque::from(vec.clone());
2658                 assert!(vd.cap().is_power_of_two());
2659                 assert_eq!(vd.len(), vec.len());
2660                 assert!(vd.into_iter().eq(vec));
2661             }
2662         }
2663     }
2664
2665     #[test]
2666     fn test_vec_from_vecdeque() {
2667         use super::super::vec::Vec;
2668
2669         fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
2670             let mut vd = VecDeque::with_capacity(cap);
2671             for _ in 0..offset {
2672                 vd.push_back(0);
2673                 vd.pop_front();
2674             }
2675             vd.extend(0..len);
2676
2677             let vec: Vec<_> = Vec::from(vd.clone());
2678             assert_eq!(vec.len(), vd.len());
2679             assert!(vec.into_iter().eq(vd));
2680         }
2681
2682         for cap_pwr in 0..7 {
2683             // Make capacity as a (2^x)-1, so that the ring size is 2^x
2684             let cap = (2i32.pow(cap_pwr) - 1) as usize;
2685
2686             // In these cases there is enough free space to solve it with copies
2687             for len in 0..((cap + 1) / 2) {
2688                 // Test contiguous cases
2689                 for offset in 0..(cap - len) {
2690                     create_vec_and_test_convert(cap, offset, len)
2691                 }
2692
2693                 // Test cases where block at end of buffer is bigger than block at start
2694                 for offset in (cap - len)..(cap - (len / 2)) {
2695                     create_vec_and_test_convert(cap, offset, len)
2696                 }
2697
2698                 // Test cases where block at start of buffer is bigger than block at end
2699                 for offset in (cap - (len / 2))..cap {
2700                     create_vec_and_test_convert(cap, offset, len)
2701                 }
2702             }
2703
2704             // Now there's not (necessarily) space to straighten the ring with simple copies,
2705             // the ring will use swapping when:
2706             // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
2707             //  right block size  >   free space    &&      left block size       >    free space
2708             for len in ((cap + 1) / 2)..cap {
2709                 // Test contiguous cases
2710                 for offset in 0..(cap - len) {
2711                     create_vec_and_test_convert(cap, offset, len)
2712                 }
2713
2714                 // Test cases where block at end of buffer is bigger than block at start
2715                 for offset in (cap - len)..(cap - (len / 2)) {
2716                     create_vec_and_test_convert(cap, offset, len)
2717                 }
2718
2719                 // Test cases where block at start of buffer is bigger than block at end
2720                 for offset in (cap - (len / 2))..cap {
2721                     create_vec_and_test_convert(cap, offset, len)
2722                 }
2723             }
2724         }
2725     }
2726 }