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