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