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