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