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