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