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