]> git.proxmox.com Git - rustc.git/blob - src/libcollections/vec_deque.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / libcollections / vec_deque.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! VecDeque is a double-ended queue, which is implemented with the help of a
12 //! growing ring buffer.
13 //!
14 //! This queue has `O(1)` amortized inserts and removals from both ends of the
15 //! container. It also has `O(1)` indexing like a vector. The contained elements
16 //! are not required to be copyable, and the queue will be sendable if the
17 //! contained type is sendable.
18
19 #![stable(feature = "rust1", since = "1.0.0")]
20
21 use core::cmp::Ordering;
22 use core::fmt;
23 use core::iter::{repeat, FromIterator};
24 use core::mem;
25 use core::ops::{Index, IndexMut};
26 use core::ptr;
27 use core::slice;
28
29 use core::hash::{Hash, Hasher};
30 use core::cmp;
31
32 use alloc::raw_vec::RawVec;
33
34 use super::range::RangeArgument;
35
36 const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
37 const MINIMUM_CAPACITY: usize = 1; // 2 - 1
38 #[cfg(target_pointer_width = "32")]
39 const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
40 #[cfg(target_pointer_width = "64")]
41 const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two
42
43 /// `VecDeque` is a growable ring buffer, which can be used as a double-ended
44 /// queue efficiently.
45 ///
46 /// The "default" usage of this type as a queue is to use `push_back` to add to
47 /// the queue, and `pop_front` to remove from the queue. `extend` and `append`
48 /// push onto the back in this manner, and iterating over `VecDeque` goes front
49 /// to back.
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub struct VecDeque<T> {
52 // tail and head are pointers into the buffer. Tail always points
53 // to the first element that could be read, Head always points
54 // to where data should be written.
55 // If tail == head the buffer is empty. The length of the ringbuffer
56 // is defined as the distance between the two.
57 tail: usize,
58 head: usize,
59 buf: RawVec<T>,
60 }
61
62 #[stable(feature = "rust1", since = "1.0.0")]
63 impl<T: Clone> Clone for VecDeque<T> {
64 fn clone(&self) -> VecDeque<T> {
65 self.iter().cloned().collect()
66 }
67 }
68
69 #[stable(feature = "rust1", since = "1.0.0")]
70 impl<T> Drop for VecDeque<T> {
71 #[unsafe_destructor_blind_to_params]
72 fn drop(&mut self) {
73 let (front, back) = self.as_mut_slices();
74 unsafe {
75 // use drop for [T]
76 ptr::drop_in_place(front);
77 ptr::drop_in_place(back);
78 }
79 // RawVec handles deallocation
80 }
81 }
82
83 #[stable(feature = "rust1", since = "1.0.0")]
84 impl<T> Default for VecDeque<T> {
85 #[inline]
86 fn default() -> VecDeque<T> {
87 VecDeque::new()
88 }
89 }
90
91 impl<T> VecDeque<T> {
92 /// Marginally more convenient
93 #[inline]
94 fn ptr(&self) -> *mut T {
95 self.buf.ptr()
96 }
97
98 /// Marginally more convenient
99 #[inline]
100 fn cap(&self) -> usize {
101 if mem::size_of::<T>() == 0 {
102 // For zero sized types, we are always at maximum capacity
103 MAXIMUM_ZST_CAPACITY
104 } else {
105 self.buf.cap()
106 }
107 }
108
109 /// Turn ptr into a slice
110 #[inline]
111 unsafe fn buffer_as_slice(&self) -> &[T] {
112 slice::from_raw_parts(self.ptr(), self.cap())
113 }
114
115 /// Turn ptr into a mut slice
116 #[inline]
117 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
118 slice::from_raw_parts_mut(self.ptr(), self.cap())
119 }
120
121 /// Moves an element out of the buffer
122 #[inline]
123 unsafe fn buffer_read(&mut self, off: usize) -> T {
124 ptr::read(self.ptr().offset(off as isize))
125 }
126
127 /// Writes an element into the buffer, moving it.
128 #[inline]
129 unsafe fn buffer_write(&mut self, off: usize, value: T) {
130 ptr::write(self.ptr().offset(off as isize), value);
131 }
132
133 /// Returns true if and only if the buffer is at capacity
134 #[inline]
135 fn is_full(&self) -> bool {
136 self.cap() - self.len() == 1
137 }
138
139 /// Returns the index in the underlying buffer for a given logical element
140 /// index.
141 #[inline]
142 fn wrap_index(&self, idx: usize) -> usize {
143 wrap_index(idx, self.cap())
144 }
145
146 /// Returns the index in the underlying buffer for a given logical element
147 /// index + addend.
148 #[inline]
149 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
150 wrap_index(idx.wrapping_add(addend), self.cap())
151 }
152
153 /// Returns the index in the underlying buffer for a given logical element
154 /// index - subtrahend.
155 #[inline]
156 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
157 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
158 }
159
160 /// Copies a contiguous block of memory len long from src to dst
161 #[inline]
162 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
163 debug_assert!(dst + len <= self.cap(),
164 "cpy dst={} src={} len={} cap={}",
165 dst,
166 src,
167 len,
168 self.cap());
169 debug_assert!(src + len <= self.cap(),
170 "cpy dst={} src={} len={} cap={}",
171 dst,
172 src,
173 len,
174 self.cap());
175 ptr::copy(self.ptr().offset(src as isize),
176 self.ptr().offset(dst as isize),
177 len);
178 }
179
180 /// Copies a contiguous block of memory len long from src to dst
181 #[inline]
182 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
183 debug_assert!(dst + len <= self.cap(),
184 "cno dst={} src={} len={} cap={}",
185 dst,
186 src,
187 len,
188 self.cap());
189 debug_assert!(src + len <= self.cap(),
190 "cno dst={} src={} len={} cap={}",
191 dst,
192 src,
193 len,
194 self.cap());
195 ptr::copy_nonoverlapping(self.ptr().offset(src as isize),
196 self.ptr().offset(dst as isize),
197 len);
198 }
199
200 /// Copies a potentially wrapping block of memory len long from src to dest.
201 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
202 /// most one continuous overlapping region between src and dest).
203 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
204 #[allow(dead_code)]
205 fn diff(a: usize, b: usize) -> usize {
206 if a <= b {
207 b - a
208 } else {
209 a - b
210 }
211 }
212 debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
213 "wrc dst={} src={} len={} cap={}",
214 dst,
215 src,
216 len,
217 self.cap());
218
219 if src == dst || len == 0 {
220 return;
221 }
222
223 let dst_after_src = self.wrap_sub(dst, src) < len;
224
225 let src_pre_wrap_len = self.cap() - src;
226 let dst_pre_wrap_len = self.cap() - dst;
227 let src_wraps = src_pre_wrap_len < len;
228 let dst_wraps = dst_pre_wrap_len < len;
229
230 match (dst_after_src, src_wraps, dst_wraps) {
231 (_, false, false) => {
232 // src doesn't wrap, dst doesn't wrap
233 //
234 // S . . .
235 // 1 [_ _ A A B B C C _]
236 // 2 [_ _ A A A A B B _]
237 // D . . .
238 //
239 self.copy(dst, src, len);
240 }
241 (false, false, true) => {
242 // dst before src, src doesn't wrap, dst wraps
243 //
244 // S . . .
245 // 1 [A A B B _ _ _ C C]
246 // 2 [A A B B _ _ _ A A]
247 // 3 [B B B B _ _ _ A A]
248 // . . D .
249 //
250 self.copy(dst, src, dst_pre_wrap_len);
251 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
252 }
253 (true, false, true) => {
254 // src before dst, src doesn't wrap, dst wraps
255 //
256 // S . . .
257 // 1 [C C _ _ _ A A B B]
258 // 2 [B B _ _ _ A A B B]
259 // 3 [B B _ _ _ A A A A]
260 // . . D .
261 //
262 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
263 self.copy(dst, src, dst_pre_wrap_len);
264 }
265 (false, true, false) => {
266 // dst before src, src wraps, dst doesn't wrap
267 //
268 // . . S .
269 // 1 [C C _ _ _ A A B B]
270 // 2 [C C _ _ _ B B B B]
271 // 3 [C C _ _ _ B B C C]
272 // D . . .
273 //
274 self.copy(dst, src, src_pre_wrap_len);
275 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
276 }
277 (true, true, false) => {
278 // src before dst, src wraps, dst doesn't wrap
279 //
280 // . . S .
281 // 1 [A A B B _ _ _ C C]
282 // 2 [A A A A _ _ _ C C]
283 // 3 [C C A A _ _ _ C C]
284 // D . . .
285 //
286 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
287 self.copy(dst, src, src_pre_wrap_len);
288 }
289 (false, true, true) => {
290 // dst before src, src wraps, dst wraps
291 //
292 // . . . S .
293 // 1 [A B C D _ E F G H]
294 // 2 [A B C D _ E G H H]
295 // 3 [A B C D _ E G H A]
296 // 4 [B C C D _ E G H A]
297 // . . D . .
298 //
299 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
300 let delta = dst_pre_wrap_len - src_pre_wrap_len;
301 self.copy(dst, src, src_pre_wrap_len);
302 self.copy(dst + src_pre_wrap_len, 0, delta);
303 self.copy(0, delta, len - dst_pre_wrap_len);
304 }
305 (true, true, true) => {
306 // src before dst, src wraps, dst wraps
307 //
308 // . . S . .
309 // 1 [A B C D _ E F G H]
310 // 2 [A A B D _ E F G H]
311 // 3 [H A B D _ E F G H]
312 // 4 [H A B D _ E F F G]
313 // . . . D .
314 //
315 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
316 let delta = src_pre_wrap_len - dst_pre_wrap_len;
317 self.copy(delta, 0, len - src_pre_wrap_len);
318 self.copy(0, self.cap() - delta, delta);
319 self.copy(dst, src, dst_pre_wrap_len);
320 }
321 }
322 }
323
324 /// Frobs the head and tail sections around to handle the fact that we
325 /// just reallocated. Unsafe because it trusts old_cap.
326 #[inline]
327 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
328 let new_cap = self.cap();
329
330 // Move the shortest contiguous section of the ring buffer
331 // T H
332 // [o o o o o o o . ]
333 // T H
334 // A [o o o o o o o . . . . . . . . . ]
335 // H T
336 // [o o . o o o o o ]
337 // T H
338 // B [. . . o o o o o o o . . . . . . ]
339 // H T
340 // [o o o o o . o o ]
341 // H T
342 // C [o o o o o . . . . . . . . . o o ]
343
344 if self.tail <= self.head {
345 // A
346 // Nop
347 } else if self.head < old_cap - self.tail {
348 // B
349 self.copy_nonoverlapping(old_cap, 0, self.head);
350 self.head += old_cap;
351 debug_assert!(self.head > self.tail);
352 } else {
353 // C
354 let new_tail = new_cap - (old_cap - self.tail);
355 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
356 self.tail = new_tail;
357 debug_assert!(self.head < self.tail);
358 }
359 debug_assert!(self.head < self.cap());
360 debug_assert!(self.tail < self.cap());
361 debug_assert!(self.cap().count_ones() == 1);
362 }
363 }
364
365 impl<T> VecDeque<T> {
366 /// Creates an empty `VecDeque`.
367 #[stable(feature = "rust1", since = "1.0.0")]
368 pub fn new() -> VecDeque<T> {
369 VecDeque::with_capacity(INITIAL_CAPACITY)
370 }
371
372 /// Creates an empty `VecDeque` with space for at least `n` elements.
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn with_capacity(n: usize) -> VecDeque<T> {
375 // +1 since the ringbuffer always leaves one space empty
376 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
377 assert!(cap > n, "capacity overflow");
378
379 VecDeque {
380 tail: 0,
381 head: 0,
382 buf: RawVec::with_capacity(cap),
383 }
384 }
385
386 /// Retrieves an element in the `VecDeque` by index.
387 ///
388 /// # Examples
389 ///
390 /// ```
391 /// use std::collections::VecDeque;
392 ///
393 /// let mut buf = VecDeque::new();
394 /// buf.push_back(3);
395 /// buf.push_back(4);
396 /// buf.push_back(5);
397 /// assert_eq!(buf.get(1), Some(&4));
398 /// ```
399 #[stable(feature = "rust1", since = "1.0.0")]
400 pub fn get(&self, index: usize) -> Option<&T> {
401 if index < self.len() {
402 let idx = self.wrap_add(self.tail, index);
403 unsafe { Some(&*self.ptr().offset(idx as isize)) }
404 } else {
405 None
406 }
407 }
408
409 /// Retrieves an element in the `VecDeque` mutably by index.
410 ///
411 /// # Examples
412 ///
413 /// ```
414 /// use std::collections::VecDeque;
415 ///
416 /// let mut buf = VecDeque::new();
417 /// buf.push_back(3);
418 /// buf.push_back(4);
419 /// buf.push_back(5);
420 /// if let Some(elem) = buf.get_mut(1) {
421 /// *elem = 7;
422 /// }
423 ///
424 /// assert_eq!(buf[1], 7);
425 /// ```
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
428 if index < self.len() {
429 let idx = self.wrap_add(self.tail, index);
430 unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
431 } else {
432 None
433 }
434 }
435
436 /// Swaps elements at indices `i` and `j`.
437 ///
438 /// `i` and `j` may be equal.
439 ///
440 /// Fails if there is no element with either index.
441 ///
442 /// # Examples
443 ///
444 /// ```
445 /// use std::collections::VecDeque;
446 ///
447 /// let mut buf = VecDeque::new();
448 /// buf.push_back(3);
449 /// buf.push_back(4);
450 /// buf.push_back(5);
451 /// buf.swap(0, 2);
452 /// assert_eq!(buf[0], 5);
453 /// assert_eq!(buf[2], 3);
454 /// ```
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn swap(&mut self, i: usize, j: usize) {
457 assert!(i < self.len());
458 assert!(j < self.len());
459 let ri = self.wrap_add(self.tail, i);
460 let rj = self.wrap_add(self.tail, j);
461 unsafe {
462 ptr::swap(self.ptr().offset(ri as isize),
463 self.ptr().offset(rj as isize))
464 }
465 }
466
467 /// Returns the number of elements the `VecDeque` can hold without
468 /// reallocating.
469 ///
470 /// # Examples
471 ///
472 /// ```
473 /// use std::collections::VecDeque;
474 ///
475 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
476 /// assert!(buf.capacity() >= 10);
477 /// ```
478 #[inline]
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn capacity(&self) -> usize {
481 self.cap() - 1
482 }
483
484 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
485 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
486 ///
487 /// Note that the allocator may give the collection more space than it requests. Therefore
488 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
489 /// insertions are expected.
490 ///
491 /// # Panics
492 ///
493 /// Panics if the new capacity overflows `usize`.
494 ///
495 /// # Examples
496 ///
497 /// ```
498 /// use std::collections::VecDeque;
499 ///
500 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
501 /// buf.reserve_exact(10);
502 /// assert!(buf.capacity() >= 11);
503 /// ```
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn reserve_exact(&mut self, additional: usize) {
506 self.reserve(additional);
507 }
508
509 /// Reserves capacity for at least `additional` more elements to be inserted in the given
510 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
511 ///
512 /// # Panics
513 ///
514 /// Panics if the new capacity overflows `usize`.
515 ///
516 /// # Examples
517 ///
518 /// ```
519 /// use std::collections::VecDeque;
520 ///
521 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
522 /// buf.reserve(10);
523 /// assert!(buf.capacity() >= 11);
524 /// ```
525 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn reserve(&mut self, additional: usize) {
527 let old_cap = self.cap();
528 let used_cap = self.len() + 1;
529 let new_cap = used_cap.checked_add(additional)
530 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
531 .expect("capacity overflow");
532
533 if new_cap > self.capacity() {
534 self.buf.reserve_exact(used_cap, new_cap - used_cap);
535 unsafe {
536 self.handle_cap_increase(old_cap);
537 }
538 }
539 }
540
541 /// Shrinks the capacity of the `VecDeque` as much as possible.
542 ///
543 /// It will drop down as close as possible to the length but the allocator may still inform the
544 /// `VecDeque` that there is space for a few more elements.
545 ///
546 /// # Examples
547 ///
548 /// ```
549 /// use std::collections::VecDeque;
550 ///
551 /// let mut buf = VecDeque::with_capacity(15);
552 /// buf.extend(0..4);
553 /// assert_eq!(buf.capacity(), 15);
554 /// buf.shrink_to_fit();
555 /// assert!(buf.capacity() >= 4);
556 /// ```
557 #[stable(feature = "deque_extras_15", since = "1.5.0")]
558 pub fn shrink_to_fit(&mut self) {
559 // +1 since the ringbuffer always leaves one space empty
560 // len + 1 can't overflow for an existing, well-formed ringbuffer.
561 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
562 if target_cap < self.cap() {
563 // There are three cases of interest:
564 // All elements are out of desired bounds
565 // Elements are contiguous, and head is out of desired bounds
566 // Elements are discontiguous, and tail is out of desired bounds
567 //
568 // At all other times, element positions are unaffected.
569 //
570 // Indicates that elements at the head should be moved.
571 let head_outside = self.head == 0 || self.head >= target_cap;
572 // Move elements from out of desired bounds (positions after target_cap)
573 if self.tail >= target_cap && head_outside {
574 // T H
575 // [. . . . . . . . o o o o o o o . ]
576 // T H
577 // [o o o o o o o . ]
578 unsafe {
579 self.copy_nonoverlapping(0, self.tail, self.len());
580 }
581 self.head = self.len();
582 self.tail = 0;
583 } else if self.tail != 0 && self.tail < target_cap && head_outside {
584 // T H
585 // [. . . o o o o o o o . . . . . . ]
586 // H T
587 // [o o . o o o o o ]
588 let len = self.wrap_sub(self.head, target_cap);
589 unsafe {
590 self.copy_nonoverlapping(0, target_cap, len);
591 }
592 self.head = len;
593 debug_assert!(self.head < self.tail);
594 } else if self.tail >= target_cap {
595 // H T
596 // [o o o o o . . . . . . . . . o o ]
597 // H T
598 // [o o o o o . o o ]
599 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
600 let len = self.cap() - self.tail;
601 let new_tail = target_cap - len;
602 unsafe {
603 self.copy_nonoverlapping(new_tail, self.tail, len);
604 }
605 self.tail = new_tail;
606 debug_assert!(self.head < self.tail);
607 }
608
609 self.buf.shrink_to_fit(target_cap);
610
611 debug_assert!(self.head < self.cap());
612 debug_assert!(self.tail < self.cap());
613 debug_assert!(self.cap().count_ones() == 1);
614 }
615 }
616
617 /// Shortens a `VecDeque`, dropping excess elements from the back.
618 ///
619 /// If `len` is greater than the `VecDeque`'s current length, this has no
620 /// effect.
621 ///
622 /// # Examples
623 ///
624 /// ```
625 /// #![feature(deque_extras)]
626 ///
627 /// use std::collections::VecDeque;
628 ///
629 /// let mut buf = VecDeque::new();
630 /// buf.push_back(5);
631 /// buf.push_back(10);
632 /// buf.push_back(15);
633 /// buf.truncate(1);
634 /// assert_eq!(buf.len(), 1);
635 /// assert_eq!(Some(&5), buf.get(0));
636 /// ```
637 #[unstable(feature = "deque_extras",
638 reason = "matches collection reform specification; waiting on panic semantics",
639 issue = "27788")]
640 pub fn truncate(&mut self, len: usize) {
641 for _ in len..self.len() {
642 self.pop_back();
643 }
644 }
645
646 /// Returns a front-to-back iterator.
647 ///
648 /// # Examples
649 ///
650 /// ```
651 /// use std::collections::VecDeque;
652 ///
653 /// let mut buf = VecDeque::new();
654 /// buf.push_back(5);
655 /// buf.push_back(3);
656 /// buf.push_back(4);
657 /// let b: &[_] = &[&5, &3, &4];
658 /// let c: Vec<&i32> = buf.iter().collect();
659 /// assert_eq!(&c[..], b);
660 /// ```
661 #[stable(feature = "rust1", since = "1.0.0")]
662 pub fn iter(&self) -> Iter<T> {
663 Iter {
664 tail: self.tail,
665 head: self.head,
666 ring: unsafe { self.buffer_as_slice() },
667 }
668 }
669
670 /// Returns a front-to-back iterator that returns mutable references.
671 ///
672 /// # Examples
673 ///
674 /// ```
675 /// use std::collections::VecDeque;
676 ///
677 /// let mut buf = VecDeque::new();
678 /// buf.push_back(5);
679 /// buf.push_back(3);
680 /// buf.push_back(4);
681 /// for num in buf.iter_mut() {
682 /// *num = *num - 2;
683 /// }
684 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
685 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
686 /// ```
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn iter_mut(&mut self) -> IterMut<T> {
689 IterMut {
690 tail: self.tail,
691 head: self.head,
692 ring: unsafe { self.buffer_as_mut_slice() },
693 }
694 }
695
696 /// Returns a pair of slices which contain, in order, the contents of the
697 /// `VecDeque`.
698 #[inline]
699 #[stable(feature = "deque_extras_15", since = "1.5.0")]
700 pub fn as_slices(&self) -> (&[T], &[T]) {
701 unsafe {
702 let contiguous = self.is_contiguous();
703 let buf = self.buffer_as_slice();
704 if contiguous {
705 let (empty, buf) = buf.split_at(0);
706 (&buf[self.tail..self.head], empty)
707 } else {
708 let (mid, right) = buf.split_at(self.tail);
709 let (left, _) = mid.split_at(self.head);
710 (right, left)
711 }
712 }
713 }
714
715 /// Returns a pair of slices which contain, in order, the contents of the
716 /// `VecDeque`.
717 #[inline]
718 #[stable(feature = "deque_extras_15", since = "1.5.0")]
719 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
720 unsafe {
721 let contiguous = self.is_contiguous();
722 let head = self.head;
723 let tail = self.tail;
724 let buf = self.buffer_as_mut_slice();
725
726 if contiguous {
727 let (empty, buf) = buf.split_at_mut(0);
728 (&mut buf[tail..head], empty)
729 } else {
730 let (mid, right) = buf.split_at_mut(tail);
731 let (left, _) = mid.split_at_mut(head);
732
733 (right, left)
734 }
735 }
736 }
737
738 /// Returns the number of elements in the `VecDeque`.
739 ///
740 /// # Examples
741 ///
742 /// ```
743 /// use std::collections::VecDeque;
744 ///
745 /// let mut v = VecDeque::new();
746 /// assert_eq!(v.len(), 0);
747 /// v.push_back(1);
748 /// assert_eq!(v.len(), 1);
749 /// ```
750 #[stable(feature = "rust1", since = "1.0.0")]
751 pub fn len(&self) -> usize {
752 count(self.tail, self.head, self.cap())
753 }
754
755 /// Returns true if the buffer contains no elements
756 ///
757 /// # Examples
758 ///
759 /// ```
760 /// use std::collections::VecDeque;
761 ///
762 /// let mut v = VecDeque::new();
763 /// assert!(v.is_empty());
764 /// v.push_front(1);
765 /// assert!(!v.is_empty());
766 /// ```
767 #[stable(feature = "rust1", since = "1.0.0")]
768 pub fn is_empty(&self) -> bool {
769 self.len() == 0
770 }
771
772 /// Create a draining iterator that removes the specified range in the
773 /// `VecDeque` and yields the removed items.
774 ///
775 /// Note 1: The element range is removed even if the iterator is not
776 /// consumed until the end.
777 ///
778 /// Note 2: It is unspecified how many elements are removed from the deque,
779 /// if the `Drain` value is not dropped, but the borrow it holds expires
780 /// (eg. due to mem::forget).
781 ///
782 /// # Panics
783 ///
784 /// Panics if the starting point is greater than the end point or if
785 /// the end point is greater than the length of the vector.
786 ///
787 /// # Examples
788 ///
789 /// ```
790 /// use std::collections::VecDeque;
791
792 /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
793 /// assert_eq!(vec![3].into_iter().collect::<VecDeque<_>>(), v.drain(2..).collect());
794 /// assert_eq!(vec![1, 2].into_iter().collect::<VecDeque<_>>(), v);
795 ///
796 /// // A full range clears all contents
797 /// v.drain(..);
798 /// assert!(v.is_empty());
799 /// ```
800 #[inline]
801 #[stable(feature = "drain", since = "1.6.0")]
802 pub fn drain<R>(&mut self, range: R) -> Drain<T>
803 where R: RangeArgument<usize>
804 {
805 // Memory safety
806 //
807 // When the Drain is first created, the source deque is shortened to
808 // make sure no uninitialized or moved-from elements are accessible at
809 // all if the Drain's destructor never gets to run.
810 //
811 // Drain will ptr::read out the values to remove.
812 // When finished, the remaining data will be copied back to cover the hole,
813 // and the head/tail values will be restored correctly.
814 //
815 let len = self.len();
816 let start = *range.start().unwrap_or(&0);
817 let end = *range.end().unwrap_or(&len);
818 assert!(start <= end, "drain lower bound was too large");
819 assert!(end <= len, "drain upper bound was too large");
820
821 // The deque's elements are parted into three segments:
822 // * self.tail -> drain_tail
823 // * drain_tail -> drain_head
824 // * drain_head -> self.head
825 //
826 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
827 //
828 // We store drain_tail as self.head, and drain_head and self.head as
829 // after_tail and after_head respectively on the Drain. This also
830 // truncates the effective array such that if the Drain is leaked, we
831 // have forgotten about the potentially moved values after the start of
832 // the drain.
833 //
834 // T t h H
835 // [. . . o o x x o o . . .]
836 //
837 let drain_tail = self.wrap_add(self.tail, start);
838 let drain_head = self.wrap_add(self.tail, end);
839 let head = self.head;
840
841 // "forget" about the values after the start of the drain until after
842 // the drain is complete and the Drain destructor is run.
843 self.head = drain_tail;
844
845 Drain {
846 deque: self as *mut _,
847 after_tail: drain_head,
848 after_head: head,
849 iter: Iter {
850 tail: drain_tail,
851 head: drain_head,
852 ring: unsafe { self.buffer_as_mut_slice() },
853 },
854 }
855 }
856
857 /// Clears the buffer, removing all values.
858 ///
859 /// # Examples
860 ///
861 /// ```
862 /// use std::collections::VecDeque;
863 ///
864 /// let mut v = VecDeque::new();
865 /// v.push_back(1);
866 /// v.clear();
867 /// assert!(v.is_empty());
868 /// ```
869 #[stable(feature = "rust1", since = "1.0.0")]
870 #[inline]
871 pub fn clear(&mut self) {
872 self.drain(..);
873 }
874
875 /// Provides a reference to the front element, or `None` if the sequence is
876 /// empty.
877 ///
878 /// # Examples
879 ///
880 /// ```
881 /// use std::collections::VecDeque;
882 ///
883 /// let mut d = VecDeque::new();
884 /// assert_eq!(d.front(), None);
885 ///
886 /// d.push_back(1);
887 /// d.push_back(2);
888 /// assert_eq!(d.front(), Some(&1));
889 /// ```
890 #[stable(feature = "rust1", since = "1.0.0")]
891 pub fn front(&self) -> Option<&T> {
892 if !self.is_empty() {
893 Some(&self[0])
894 } else {
895 None
896 }
897 }
898
899 /// Provides a mutable reference to the front element, or `None` if the
900 /// sequence is empty.
901 ///
902 /// # Examples
903 ///
904 /// ```
905 /// use std::collections::VecDeque;
906 ///
907 /// let mut d = VecDeque::new();
908 /// assert_eq!(d.front_mut(), None);
909 ///
910 /// d.push_back(1);
911 /// d.push_back(2);
912 /// match d.front_mut() {
913 /// Some(x) => *x = 9,
914 /// None => (),
915 /// }
916 /// assert_eq!(d.front(), Some(&9));
917 /// ```
918 #[stable(feature = "rust1", since = "1.0.0")]
919 pub fn front_mut(&mut self) -> Option<&mut T> {
920 if !self.is_empty() {
921 Some(&mut self[0])
922 } else {
923 None
924 }
925 }
926
927 /// Provides a reference to the back element, or `None` if the sequence is
928 /// empty.
929 ///
930 /// # Examples
931 ///
932 /// ```
933 /// use std::collections::VecDeque;
934 ///
935 /// let mut d = VecDeque::new();
936 /// assert_eq!(d.back(), None);
937 ///
938 /// d.push_back(1);
939 /// d.push_back(2);
940 /// assert_eq!(d.back(), Some(&2));
941 /// ```
942 #[stable(feature = "rust1", since = "1.0.0")]
943 pub fn back(&self) -> Option<&T> {
944 if !self.is_empty() {
945 Some(&self[self.len() - 1])
946 } else {
947 None
948 }
949 }
950
951 /// Provides a mutable reference to the back element, or `None` if the
952 /// sequence is empty.
953 ///
954 /// # Examples
955 ///
956 /// ```
957 /// use std::collections::VecDeque;
958 ///
959 /// let mut d = VecDeque::new();
960 /// assert_eq!(d.back(), None);
961 ///
962 /// d.push_back(1);
963 /// d.push_back(2);
964 /// match d.back_mut() {
965 /// Some(x) => *x = 9,
966 /// None => (),
967 /// }
968 /// assert_eq!(d.back(), Some(&9));
969 /// ```
970 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn back_mut(&mut self) -> Option<&mut T> {
972 let len = self.len();
973 if !self.is_empty() {
974 Some(&mut self[len - 1])
975 } else {
976 None
977 }
978 }
979
980 /// Removes the first element and returns it, or `None` if the sequence is
981 /// empty.
982 ///
983 /// # Examples
984 ///
985 /// ```
986 /// use std::collections::VecDeque;
987 ///
988 /// let mut d = VecDeque::new();
989 /// d.push_back(1);
990 /// d.push_back(2);
991 ///
992 /// assert_eq!(d.pop_front(), Some(1));
993 /// assert_eq!(d.pop_front(), Some(2));
994 /// assert_eq!(d.pop_front(), None);
995 /// ```
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn pop_front(&mut self) -> Option<T> {
998 if self.is_empty() {
999 None
1000 } else {
1001 let tail = self.tail;
1002 self.tail = self.wrap_add(self.tail, 1);
1003 unsafe { Some(self.buffer_read(tail)) }
1004 }
1005 }
1006
1007 /// Inserts an element first in the sequence.
1008 ///
1009 /// # Examples
1010 ///
1011 /// ```
1012 /// use std::collections::VecDeque;
1013 ///
1014 /// let mut d = VecDeque::new();
1015 /// d.push_front(1);
1016 /// d.push_front(2);
1017 /// assert_eq!(d.front(), Some(&2));
1018 /// ```
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 pub fn push_front(&mut self, value: T) {
1021 if self.is_full() {
1022 let old_cap = self.cap();
1023 self.buf.double();
1024 unsafe {
1025 self.handle_cap_increase(old_cap);
1026 }
1027 debug_assert!(!self.is_full());
1028 }
1029
1030 self.tail = self.wrap_sub(self.tail, 1);
1031 let tail = self.tail;
1032 unsafe {
1033 self.buffer_write(tail, value);
1034 }
1035 }
1036
1037 /// Appends an element to the back of a buffer
1038 ///
1039 /// # Examples
1040 ///
1041 /// ```
1042 /// use std::collections::VecDeque;
1043 ///
1044 /// let mut buf = VecDeque::new();
1045 /// buf.push_back(1);
1046 /// buf.push_back(3);
1047 /// assert_eq!(3, *buf.back().unwrap());
1048 /// ```
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 pub fn push_back(&mut self, value: T) {
1051 if self.is_full() {
1052 let old_cap = self.cap();
1053 self.buf.double();
1054 unsafe {
1055 self.handle_cap_increase(old_cap);
1056 }
1057 debug_assert!(!self.is_full());
1058 }
1059
1060 let head = self.head;
1061 self.head = self.wrap_add(self.head, 1);
1062 unsafe { self.buffer_write(head, value) }
1063 }
1064
1065 /// Removes the last element from a buffer and returns it, or `None` if
1066 /// it is empty.
1067 ///
1068 /// # Examples
1069 ///
1070 /// ```
1071 /// use std::collections::VecDeque;
1072 ///
1073 /// let mut buf = VecDeque::new();
1074 /// assert_eq!(buf.pop_back(), None);
1075 /// buf.push_back(1);
1076 /// buf.push_back(3);
1077 /// assert_eq!(buf.pop_back(), Some(3));
1078 /// ```
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub fn pop_back(&mut self) -> Option<T> {
1081 if self.is_empty() {
1082 None
1083 } else {
1084 self.head = self.wrap_sub(self.head, 1);
1085 let head = self.head;
1086 unsafe { Some(self.buffer_read(head)) }
1087 }
1088 }
1089
1090 #[inline]
1091 fn is_contiguous(&self) -> bool {
1092 self.tail <= self.head
1093 }
1094
1095 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1096 /// last element.
1097 ///
1098 /// This does not preserve ordering, but is O(1).
1099 ///
1100 /// Returns `None` if `index` is out of bounds.
1101 ///
1102 /// # Examples
1103 ///
1104 /// ```
1105 /// use std::collections::VecDeque;
1106 ///
1107 /// let mut buf = VecDeque::new();
1108 /// assert_eq!(buf.swap_remove_back(0), None);
1109 /// buf.push_back(1);
1110 /// buf.push_back(2);
1111 /// buf.push_back(3);
1112 ///
1113 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1114 /// assert_eq!(buf.len(), 2);
1115 /// assert_eq!(buf[0], 3);
1116 /// assert_eq!(buf[1], 2);
1117 /// ```
1118 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1119 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1120 let length = self.len();
1121 if length > 0 && index < length - 1 {
1122 self.swap(index, length - 1);
1123 } else if index >= length {
1124 return None;
1125 }
1126 self.pop_back()
1127 }
1128
1129 /// Removes an element from anywhere in the `VecDeque` and returns it,
1130 /// replacing it with the first element.
1131 ///
1132 /// This does not preserve ordering, but is O(1).
1133 ///
1134 /// Returns `None` if `index` is out of bounds.
1135 ///
1136 /// # Examples
1137 ///
1138 /// ```
1139 /// use std::collections::VecDeque;
1140 ///
1141 /// let mut buf = VecDeque::new();
1142 /// assert_eq!(buf.swap_remove_front(0), None);
1143 /// buf.push_back(1);
1144 /// buf.push_back(2);
1145 /// buf.push_back(3);
1146 ///
1147 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1148 /// assert_eq!(buf.len(), 2);
1149 /// assert_eq!(buf[0], 2);
1150 /// assert_eq!(buf[1], 1);
1151 /// ```
1152 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1153 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1154 let length = self.len();
1155 if length > 0 && index < length && index != 0 {
1156 self.swap(index, 0);
1157 } else if index >= length {
1158 return None;
1159 }
1160 self.pop_front()
1161 }
1162
1163 /// Inserts an element at `index` within the `VecDeque`. Whichever
1164 /// end is closer to the insertion point will be moved to make room,
1165 /// and all the affected elements will be moved to new positions.
1166 ///
1167 /// # Panics
1168 ///
1169 /// Panics if `index` is greater than `VecDeque`'s length
1170 ///
1171 /// # Examples
1172 /// ```
1173 /// use std::collections::VecDeque;
1174 ///
1175 /// let mut buf = VecDeque::new();
1176 /// buf.push_back(10);
1177 /// buf.push_back(12);
1178 /// buf.insert(1, 11);
1179 /// assert_eq!(Some(&11), buf.get(1));
1180 /// ```
1181 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1182 pub fn insert(&mut self, index: usize, value: T) {
1183 assert!(index <= self.len(), "index out of bounds");
1184 if self.is_full() {
1185 let old_cap = self.cap();
1186 self.buf.double();
1187 unsafe {
1188 self.handle_cap_increase(old_cap);
1189 }
1190 debug_assert!(!self.is_full());
1191 }
1192
1193 // Move the least number of elements in the ring buffer and insert
1194 // the given object
1195 //
1196 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1197 //
1198 // There are three main cases:
1199 // Elements are contiguous
1200 // - special case when tail is 0
1201 // Elements are discontiguous and the insert is in the tail section
1202 // Elements are discontiguous and the insert is in the head section
1203 //
1204 // For each of those there are two more cases:
1205 // Insert is closer to tail
1206 // Insert is closer to head
1207 //
1208 // Key: H - self.head
1209 // T - self.tail
1210 // o - Valid element
1211 // I - Insertion element
1212 // A - The element that should be after the insertion point
1213 // M - Indicates element was moved
1214
1215 let idx = self.wrap_add(self.tail, index);
1216
1217 let distance_to_tail = index;
1218 let distance_to_head = self.len() - index;
1219
1220 let contiguous = self.is_contiguous();
1221
1222 match (contiguous,
1223 distance_to_tail <= distance_to_head,
1224 idx >= self.tail) {
1225 (true, true, _) if index == 0 => {
1226 // push_front
1227 //
1228 // T
1229 // I H
1230 // [A o o o o o o . . . . . . . . .]
1231 //
1232 // H T
1233 // [A o o o o o o o . . . . . I]
1234 //
1235
1236 self.tail = self.wrap_sub(self.tail, 1);
1237 }
1238 (true, true, _) => {
1239 unsafe {
1240 // contiguous, insert closer to tail:
1241 //
1242 // T I H
1243 // [. . . o o A o o o o . . . . . .]
1244 //
1245 // T H
1246 // [. . o o I A o o o o . . . . . .]
1247 // M M
1248 //
1249 // contiguous, insert closer to tail and tail is 0:
1250 //
1251 //
1252 // T I H
1253 // [o o A o o o o . . . . . . . . .]
1254 //
1255 // H T
1256 // [o I A o o o o o . . . . . . . o]
1257 // M M
1258
1259 let new_tail = self.wrap_sub(self.tail, 1);
1260
1261 self.copy(new_tail, self.tail, 1);
1262 // Already moved the tail, so we only copy `index - 1` elements.
1263 self.copy(self.tail, self.tail + 1, index - 1);
1264
1265 self.tail = new_tail;
1266 }
1267 }
1268 (true, false, _) => {
1269 unsafe {
1270 // contiguous, insert closer to head:
1271 //
1272 // T I H
1273 // [. . . o o o o A o o . . . . . .]
1274 //
1275 // T H
1276 // [. . . o o o o I A o o . . . . .]
1277 // M M M
1278
1279 self.copy(idx + 1, idx, self.head - idx);
1280 self.head = self.wrap_add(self.head, 1);
1281 }
1282 }
1283 (false, true, true) => {
1284 unsafe {
1285 // discontiguous, insert closer to tail, tail section:
1286 //
1287 // H T I
1288 // [o o o o o o . . . . . o o A o o]
1289 //
1290 // H T
1291 // [o o o o o o . . . . o o I A o o]
1292 // M M
1293
1294 self.copy(self.tail - 1, self.tail, index);
1295 self.tail -= 1;
1296 }
1297 }
1298 (false, false, true) => {
1299 unsafe {
1300 // discontiguous, insert closer to head, tail section:
1301 //
1302 // H T I
1303 // [o o . . . . . . . o o o o o A o]
1304 //
1305 // H T
1306 // [o o o . . . . . . o o o o o I A]
1307 // M M M M
1308
1309 // copy elements up to new head
1310 self.copy(1, 0, self.head);
1311
1312 // copy last element into empty spot at bottom of buffer
1313 self.copy(0, self.cap() - 1, 1);
1314
1315 // move elements from idx to end forward not including ^ element
1316 self.copy(idx + 1, idx, self.cap() - 1 - idx);
1317
1318 self.head += 1;
1319 }
1320 }
1321 (false, true, false) if idx == 0 => {
1322 unsafe {
1323 // discontiguous, insert is closer to tail, head section,
1324 // and is at index zero in the internal buffer:
1325 //
1326 // I H T
1327 // [A o o o o o o o o o . . . o o o]
1328 //
1329 // H T
1330 // [A o o o o o o o o o . . o o o I]
1331 // M M M
1332
1333 // copy elements up to new tail
1334 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1335
1336 // copy last element into empty spot at bottom of buffer
1337 self.copy(self.cap() - 1, 0, 1);
1338
1339 self.tail -= 1;
1340 }
1341 }
1342 (false, true, false) => {
1343 unsafe {
1344 // discontiguous, insert closer to tail, head section:
1345 //
1346 // I H T
1347 // [o o o A o o o o o o . . . o o o]
1348 //
1349 // H T
1350 // [o o I A o o o o o o . . o o o o]
1351 // M M M M M M
1352
1353 // copy elements up to new tail
1354 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
1355
1356 // copy last element into empty spot at bottom of buffer
1357 self.copy(self.cap() - 1, 0, 1);
1358
1359 // move elements from idx-1 to end forward not including ^ element
1360 self.copy(0, 1, idx - 1);
1361
1362 self.tail -= 1;
1363 }
1364 }
1365 (false, false, false) => {
1366 unsafe {
1367 // discontiguous, insert closer to head, head section:
1368 //
1369 // I H T
1370 // [o o o o A o o . . . . . . o o o]
1371 //
1372 // H T
1373 // [o o o o I A o o . . . . . o o o]
1374 // M M M
1375
1376 self.copy(idx + 1, idx, self.head - idx);
1377 self.head += 1;
1378 }
1379 }
1380 }
1381
1382 // tail might've been changed so we need to recalculate
1383 let new_idx = self.wrap_add(self.tail, index);
1384 unsafe {
1385 self.buffer_write(new_idx, value);
1386 }
1387 }
1388
1389 /// Removes and returns the element at `index` from the `VecDeque`.
1390 /// Whichever end is closer to the removal point will be moved to make
1391 /// room, and all the affected elements will be moved to new positions.
1392 /// Returns `None` if `index` is out of bounds.
1393 ///
1394 /// # Examples
1395 /// ```
1396 /// use std::collections::VecDeque;
1397 ///
1398 /// let mut buf = VecDeque::new();
1399 /// buf.push_back(1);
1400 /// buf.push_back(2);
1401 /// buf.push_back(3);
1402 ///
1403 /// assert_eq!(buf.remove(1), Some(2));
1404 /// assert_eq!(buf.get(1), Some(&3));
1405 /// ```
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 pub fn remove(&mut self, index: usize) -> Option<T> {
1408 if self.is_empty() || self.len() <= index {
1409 return None;
1410 }
1411
1412 // There are three main cases:
1413 // Elements are contiguous
1414 // Elements are discontiguous and the removal is in the tail section
1415 // Elements are discontiguous and the removal is in the head section
1416 // - special case when elements are technically contiguous,
1417 // but self.head = 0
1418 //
1419 // For each of those there are two more cases:
1420 // Insert is closer to tail
1421 // Insert is closer to head
1422 //
1423 // Key: H - self.head
1424 // T - self.tail
1425 // o - Valid element
1426 // x - Element marked for removal
1427 // R - Indicates element that is being removed
1428 // M - Indicates element was moved
1429
1430 let idx = self.wrap_add(self.tail, index);
1431
1432 let elem = unsafe { Some(self.buffer_read(idx)) };
1433
1434 let distance_to_tail = index;
1435 let distance_to_head = self.len() - index;
1436
1437 let contiguous = self.is_contiguous();
1438
1439 match (contiguous,
1440 distance_to_tail <= distance_to_head,
1441 idx >= self.tail) {
1442 (true, true, _) => {
1443 unsafe {
1444 // contiguous, remove closer to tail:
1445 //
1446 // T R H
1447 // [. . . o o x o o o o . . . . . .]
1448 //
1449 // T H
1450 // [. . . . o o o o o o . . . . . .]
1451 // M M
1452
1453 self.copy(self.tail + 1, self.tail, index);
1454 self.tail += 1;
1455 }
1456 }
1457 (true, false, _) => {
1458 unsafe {
1459 // contiguous, remove closer to head:
1460 //
1461 // T R H
1462 // [. . . o o o o x o o . . . . . .]
1463 //
1464 // T H
1465 // [. . . o o o o o o . . . . . . .]
1466 // M M
1467
1468 self.copy(idx, idx + 1, self.head - idx - 1);
1469 self.head -= 1;
1470 }
1471 }
1472 (false, true, true) => {
1473 unsafe {
1474 // discontiguous, remove closer to tail, tail section:
1475 //
1476 // H T R
1477 // [o o o o o o . . . . . o o x o o]
1478 //
1479 // H T
1480 // [o o o o o o . . . . . . o o o o]
1481 // M M
1482
1483 self.copy(self.tail + 1, self.tail, index);
1484 self.tail = self.wrap_add(self.tail, 1);
1485 }
1486 }
1487 (false, false, false) => {
1488 unsafe {
1489 // discontiguous, remove closer to head, head section:
1490 //
1491 // R H T
1492 // [o o o o x o o . . . . . . o o o]
1493 //
1494 // H T
1495 // [o o o o o o . . . . . . . o o o]
1496 // M M
1497
1498 self.copy(idx, idx + 1, self.head - idx - 1);
1499 self.head -= 1;
1500 }
1501 }
1502 (false, false, true) => {
1503 unsafe {
1504 // discontiguous, remove closer to head, tail section:
1505 //
1506 // H T R
1507 // [o o o . . . . . . o o o o o x o]
1508 //
1509 // H T
1510 // [o o . . . . . . . o o o o o o o]
1511 // M M M M
1512 //
1513 // or quasi-discontiguous, remove next to head, tail section:
1514 //
1515 // H T R
1516 // [. . . . . . . . . o o o o o x o]
1517 //
1518 // T H
1519 // [. . . . . . . . . o o o o o o .]
1520 // M
1521
1522 // draw in elements in the tail section
1523 self.copy(idx, idx + 1, self.cap() - idx - 1);
1524
1525 // Prevents underflow.
1526 if self.head != 0 {
1527 // copy first element into empty spot
1528 self.copy(self.cap() - 1, 0, 1);
1529
1530 // move elements in the head section backwards
1531 self.copy(0, 1, self.head - 1);
1532 }
1533
1534 self.head = self.wrap_sub(self.head, 1);
1535 }
1536 }
1537 (false, true, false) => {
1538 unsafe {
1539 // discontiguous, remove closer to tail, head section:
1540 //
1541 // R H T
1542 // [o o x o o o o o o o . . . o o o]
1543 //
1544 // H T
1545 // [o o o o o o o o o o . . . . o o]
1546 // M M M M M
1547
1548 // draw in elements up to idx
1549 self.copy(1, 0, idx);
1550
1551 // copy last element into empty spot
1552 self.copy(0, self.cap() - 1, 1);
1553
1554 // move elements from tail to end forward, excluding the last one
1555 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
1556
1557 self.tail = self.wrap_add(self.tail, 1);
1558 }
1559 }
1560 }
1561
1562 return elem;
1563 }
1564
1565 /// Splits the collection into two at the given index.
1566 ///
1567 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1568 /// and the returned `Self` contains elements `[at, len)`.
1569 ///
1570 /// Note that the capacity of `self` does not change.
1571 ///
1572 /// # Panics
1573 ///
1574 /// Panics if `at > len`
1575 ///
1576 /// # Examples
1577 ///
1578 /// ```
1579 /// use std::collections::VecDeque;
1580 ///
1581 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
1582 /// let buf2 = buf.split_off(1);
1583 /// // buf = [1], buf2 = [2, 3]
1584 /// assert_eq!(buf.len(), 1);
1585 /// assert_eq!(buf2.len(), 2);
1586 /// ```
1587 #[inline]
1588 #[stable(feature = "split_off", since = "1.4.0")]
1589 pub fn split_off(&mut self, at: usize) -> Self {
1590 let len = self.len();
1591 assert!(at <= len, "`at` out of bounds");
1592
1593 let other_len = len - at;
1594 let mut other = VecDeque::with_capacity(other_len);
1595
1596 unsafe {
1597 let (first_half, second_half) = self.as_slices();
1598
1599 let first_len = first_half.len();
1600 let second_len = second_half.len();
1601 if at < first_len {
1602 // `at` lies in the first half.
1603 let amount_in_first = first_len - at;
1604
1605 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1606 other.ptr(),
1607 amount_in_first);
1608
1609 // just take all of the second half.
1610 ptr::copy_nonoverlapping(second_half.as_ptr(),
1611 other.ptr().offset(amount_in_first as isize),
1612 second_len);
1613 } else {
1614 // `at` lies in the second half, need to factor in the elements we skipped
1615 // in the first half.
1616 let offset = at - first_len;
1617 let amount_in_second = second_len - offset;
1618 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1619 other.ptr(),
1620 amount_in_second);
1621 }
1622 }
1623
1624 // Cleanup where the ends of the buffers are
1625 self.head = self.wrap_sub(self.head, other_len);
1626 other.head = other.wrap_index(other_len);
1627
1628 other
1629 }
1630
1631 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1632 ///
1633 /// # Panics
1634 ///
1635 /// Panics if the new number of elements in self overflows a `usize`.
1636 ///
1637 /// # Examples
1638 ///
1639 /// ```
1640 /// use std::collections::VecDeque;
1641 ///
1642 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1643 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
1644 /// buf.append(&mut buf2);
1645 /// assert_eq!(buf.len(), 6);
1646 /// assert_eq!(buf2.len(), 0);
1647 /// ```
1648 #[inline]
1649 #[stable(feature = "append", since = "1.4.0")]
1650 pub fn append(&mut self, other: &mut Self) {
1651 // naive impl
1652 self.extend(other.drain(..));
1653 }
1654
1655 /// Retains only the elements specified by the predicate.
1656 ///
1657 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1658 /// This method operates in place and preserves the order of the retained
1659 /// elements.
1660 ///
1661 /// # Examples
1662 ///
1663 /// ```
1664 /// use std::collections::VecDeque;
1665 ///
1666 /// let mut buf = VecDeque::new();
1667 /// buf.extend(1..5);
1668 /// buf.retain(|&x| x%2 == 0);
1669 ///
1670 /// let v: Vec<_> = buf.into_iter().collect();
1671 /// assert_eq!(&v[..], &[2, 4]);
1672 /// ```
1673 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
1674 pub fn retain<F>(&mut self, mut f: F)
1675 where F: FnMut(&T) -> bool
1676 {
1677 let len = self.len();
1678 let mut del = 0;
1679 for i in 0..len {
1680 if !f(&self[i]) {
1681 del += 1;
1682 } else if del > 0 {
1683 self.swap(i - del, i);
1684 }
1685 }
1686 if del > 0 {
1687 self.truncate(len - del);
1688 }
1689 }
1690 }
1691
1692 impl<T: Clone> VecDeque<T> {
1693 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
1694 /// either by removing excess elements or by appending copies of a value to the back.
1695 ///
1696 /// # Examples
1697 ///
1698 /// ```
1699 /// #![feature(deque_extras)]
1700 ///
1701 /// use std::collections::VecDeque;
1702 ///
1703 /// let mut buf = VecDeque::new();
1704 /// buf.push_back(5);
1705 /// buf.push_back(10);
1706 /// buf.push_back(15);
1707 /// buf.resize(2, 0);
1708 /// buf.resize(6, 20);
1709 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
1710 /// assert_eq!(a, b);
1711 /// }
1712 /// ```
1713 #[unstable(feature = "deque_extras",
1714 reason = "matches collection reform specification; waiting on panic semantics",
1715 issue = "27788")]
1716 pub fn resize(&mut self, new_len: usize, value: T) {
1717 let len = self.len();
1718
1719 if new_len > len {
1720 self.extend(repeat(value).take(new_len - len))
1721 } else {
1722 self.truncate(new_len);
1723 }
1724 }
1725 }
1726
1727 /// Returns the index in the underlying buffer for a given logical element index.
1728 #[inline]
1729 fn wrap_index(index: usize, size: usize) -> usize {
1730 // size is always a power of 2
1731 debug_assert!(size.is_power_of_two());
1732 index & (size - 1)
1733 }
1734
1735 /// Calculate the number of elements left to be read in the buffer
1736 #[inline]
1737 fn count(tail: usize, head: usize, size: usize) -> usize {
1738 // size is always a power of 2
1739 (head.wrapping_sub(tail)) & (size - 1)
1740 }
1741
1742 /// `VecDeque` iterator.
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 pub struct Iter<'a, T: 'a> {
1745 ring: &'a [T],
1746 tail: usize,
1747 head: usize,
1748 }
1749
1750 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 impl<'a, T> Clone for Iter<'a, T> {
1753 fn clone(&self) -> Iter<'a, T> {
1754 Iter {
1755 ring: self.ring,
1756 tail: self.tail,
1757 head: self.head,
1758 }
1759 }
1760 }
1761
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl<'a, T> Iterator for Iter<'a, T> {
1764 type Item = &'a T;
1765
1766 #[inline]
1767 fn next(&mut self) -> Option<&'a T> {
1768 if self.tail == self.head {
1769 return None;
1770 }
1771 let tail = self.tail;
1772 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1773 unsafe { Some(self.ring.get_unchecked(tail)) }
1774 }
1775
1776 #[inline]
1777 fn size_hint(&self) -> (usize, Option<usize>) {
1778 let len = count(self.tail, self.head, self.ring.len());
1779 (len, Some(len))
1780 }
1781 }
1782
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1785 #[inline]
1786 fn next_back(&mut self) -> Option<&'a T> {
1787 if self.tail == self.head {
1788 return None;
1789 }
1790 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1791 unsafe { Some(self.ring.get_unchecked(self.head)) }
1792 }
1793 }
1794
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1797
1798 /// `VecDeque` mutable iterator.
1799 #[stable(feature = "rust1", since = "1.0.0")]
1800 pub struct IterMut<'a, T: 'a> {
1801 ring: &'a mut [T],
1802 tail: usize,
1803 head: usize,
1804 }
1805
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 impl<'a, T> Iterator for IterMut<'a, T> {
1808 type Item = &'a mut T;
1809
1810 #[inline]
1811 fn next(&mut self) -> Option<&'a mut T> {
1812 if self.tail == self.head {
1813 return None;
1814 }
1815 let tail = self.tail;
1816 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
1817
1818 unsafe {
1819 let elem = self.ring.get_unchecked_mut(tail);
1820 Some(&mut *(elem as *mut _))
1821 }
1822 }
1823
1824 #[inline]
1825 fn size_hint(&self) -> (usize, Option<usize>) {
1826 let len = count(self.tail, self.head, self.ring.len());
1827 (len, Some(len))
1828 }
1829 }
1830
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1833 #[inline]
1834 fn next_back(&mut self) -> Option<&'a mut T> {
1835 if self.tail == self.head {
1836 return None;
1837 }
1838 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
1839
1840 unsafe {
1841 let elem = self.ring.get_unchecked_mut(self.head);
1842 Some(&mut *(elem as *mut _))
1843 }
1844 }
1845 }
1846
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1849
1850 /// A by-value VecDeque iterator
1851 #[derive(Clone)]
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 pub struct IntoIter<T> {
1854 inner: VecDeque<T>,
1855 }
1856
1857 #[stable(feature = "rust1", since = "1.0.0")]
1858 impl<T> Iterator for IntoIter<T> {
1859 type Item = T;
1860
1861 #[inline]
1862 fn next(&mut self) -> Option<T> {
1863 self.inner.pop_front()
1864 }
1865
1866 #[inline]
1867 fn size_hint(&self) -> (usize, Option<usize>) {
1868 let len = self.inner.len();
1869 (len, Some(len))
1870 }
1871 }
1872
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 impl<T> DoubleEndedIterator for IntoIter<T> {
1875 #[inline]
1876 fn next_back(&mut self) -> Option<T> {
1877 self.inner.pop_back()
1878 }
1879 }
1880
1881 #[stable(feature = "rust1", since = "1.0.0")]
1882 impl<T> ExactSizeIterator for IntoIter<T> {}
1883
1884 /// A draining VecDeque iterator
1885 #[stable(feature = "drain", since = "1.6.0")]
1886 pub struct Drain<'a, T: 'a> {
1887 after_tail: usize,
1888 after_head: usize,
1889 iter: Iter<'a, T>,
1890 deque: *mut VecDeque<T>,
1891 }
1892
1893 #[stable(feature = "drain", since = "1.6.0")]
1894 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1895 #[stable(feature = "drain", since = "1.6.0")]
1896 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1897
1898 #[stable(feature = "rust1", since = "1.0.0")]
1899 impl<'a, T: 'a> Drop for Drain<'a, T> {
1900 fn drop(&mut self) {
1901 for _ in self.by_ref() {}
1902
1903 let source_deque = unsafe { &mut *self.deque };
1904
1905 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
1906 //
1907 // T t h H
1908 // [. . . o o x x o o . . .]
1909 //
1910 let orig_tail = source_deque.tail;
1911 let drain_tail = source_deque.head;
1912 let drain_head = self.after_tail;
1913 let orig_head = self.after_head;
1914
1915 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
1916 let head_len = count(drain_head, orig_head, source_deque.cap());
1917
1918 // Restore the original head value
1919 source_deque.head = orig_head;
1920
1921 match (tail_len, head_len) {
1922 (0, 0) => {
1923 source_deque.head = 0;
1924 source_deque.tail = 0;
1925 }
1926 (0, _) => {
1927 source_deque.tail = drain_head;
1928 }
1929 (_, 0) => {
1930 source_deque.head = drain_tail;
1931 }
1932 _ => {
1933 unsafe {
1934 if tail_len <= head_len {
1935 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
1936 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
1937 } else {
1938 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
1939 source_deque.wrap_copy(drain_tail, drain_head, head_len);
1940 }
1941 }
1942 }
1943 }
1944 }
1945 }
1946
1947 #[stable(feature = "rust1", since = "1.0.0")]
1948 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1949 type Item = T;
1950
1951 #[inline]
1952 fn next(&mut self) -> Option<T> {
1953 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
1954 }
1955
1956 #[inline]
1957 fn size_hint(&self) -> (usize, Option<usize>) {
1958 self.iter.size_hint()
1959 }
1960 }
1961
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1964 #[inline]
1965 fn next_back(&mut self) -> Option<T> {
1966 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
1967 }
1968 }
1969
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1972
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl<A: PartialEq> PartialEq for VecDeque<A> {
1975 fn eq(&self, other: &VecDeque<A>) -> bool {
1976 if self.len() != other.len() {
1977 return false;
1978 }
1979 let (sa, sb) = self.as_slices();
1980 let (oa, ob) = other.as_slices();
1981 if sa.len() == oa.len() {
1982 sa == oa && sb == ob
1983 } else if sa.len() < oa.len() {
1984 // Always divisible in three sections, for example:
1985 // self: [a b c|d e f]
1986 // other: [0 1 2 3|4 5]
1987 // front = 3, mid = 1,
1988 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
1989 let front = sa.len();
1990 let mid = oa.len() - front;
1991
1992 let (oa_front, oa_mid) = oa.split_at(front);
1993 let (sb_mid, sb_back) = sb.split_at(mid);
1994 debug_assert_eq!(sa.len(), oa_front.len());
1995 debug_assert_eq!(sb_mid.len(), oa_mid.len());
1996 debug_assert_eq!(sb_back.len(), ob.len());
1997 sa == oa_front && sb_mid == oa_mid && sb_back == ob
1998 } else {
1999 let front = oa.len();
2000 let mid = sa.len() - front;
2001
2002 let (sa_front, sa_mid) = sa.split_at(front);
2003 let (ob_mid, ob_back) = ob.split_at(mid);
2004 debug_assert_eq!(sa_front.len(), oa.len());
2005 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2006 debug_assert_eq!(sb.len(), ob_back.len());
2007 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2008 }
2009 }
2010 }
2011
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl<A: Eq> Eq for VecDeque<A> {}
2014
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 impl<A: PartialOrd> PartialOrd for VecDeque<A> {
2017 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
2018 self.iter().partial_cmp(other.iter())
2019 }
2020 }
2021
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl<A: Ord> Ord for VecDeque<A> {
2024 #[inline]
2025 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
2026 self.iter().cmp(other.iter())
2027 }
2028 }
2029
2030 #[stable(feature = "rust1", since = "1.0.0")]
2031 impl<A: Hash> Hash for VecDeque<A> {
2032 fn hash<H: Hasher>(&self, state: &mut H) {
2033 self.len().hash(state);
2034 let (a, b) = self.as_slices();
2035 Hash::hash_slice(a, state);
2036 Hash::hash_slice(b, state);
2037 }
2038 }
2039
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 impl<A> Index<usize> for VecDeque<A> {
2042 type Output = A;
2043
2044 #[inline]
2045 fn index(&self, index: usize) -> &A {
2046 self.get(index).expect("Out of bounds access")
2047 }
2048 }
2049
2050 #[stable(feature = "rust1", since = "1.0.0")]
2051 impl<A> IndexMut<usize> for VecDeque<A> {
2052 #[inline]
2053 fn index_mut(&mut self, index: usize) -> &mut A {
2054 self.get_mut(index).expect("Out of bounds access")
2055 }
2056 }
2057
2058 #[stable(feature = "rust1", since = "1.0.0")]
2059 impl<A> FromIterator<A> for VecDeque<A> {
2060 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> {
2061 let iterator = iter.into_iter();
2062 let (lower, _) = iterator.size_hint();
2063 let mut deq = VecDeque::with_capacity(lower);
2064 deq.extend(iterator);
2065 deq
2066 }
2067 }
2068
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 impl<T> IntoIterator for VecDeque<T> {
2071 type Item = T;
2072 type IntoIter = IntoIter<T>;
2073
2074 /// Consumes the list into a front-to-back iterator yielding elements by
2075 /// value.
2076 fn into_iter(self) -> IntoIter<T> {
2077 IntoIter { inner: self }
2078 }
2079 }
2080
2081 #[stable(feature = "rust1", since = "1.0.0")]
2082 impl<'a, T> IntoIterator for &'a VecDeque<T> {
2083 type Item = &'a T;
2084 type IntoIter = Iter<'a, T>;
2085
2086 fn into_iter(self) -> Iter<'a, T> {
2087 self.iter()
2088 }
2089 }
2090
2091 #[stable(feature = "rust1", since = "1.0.0")]
2092 impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
2093 type Item = &'a mut T;
2094 type IntoIter = IterMut<'a, T>;
2095
2096 fn into_iter(mut self) -> IterMut<'a, T> {
2097 self.iter_mut()
2098 }
2099 }
2100
2101 #[stable(feature = "rust1", since = "1.0.0")]
2102 impl<A> Extend<A> for VecDeque<A> {
2103 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2104 for elt in iter {
2105 self.push_back(elt);
2106 }
2107 }
2108 }
2109
2110 #[stable(feature = "extend_ref", since = "1.2.0")]
2111 impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2112 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2113 self.extend(iter.into_iter().cloned());
2114 }
2115 }
2116
2117 #[stable(feature = "rust1", since = "1.0.0")]
2118 impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
2119 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2120 f.debug_list().entries(self).finish()
2121 }
2122 }
2123
2124 #[cfg(test)]
2125 mod tests {
2126 use core::iter::Iterator;
2127 use core::option::Option::Some;
2128
2129 use test;
2130
2131 use super::VecDeque;
2132
2133 #[bench]
2134 fn bench_push_back_100(b: &mut test::Bencher) {
2135 let mut deq = VecDeque::with_capacity(101);
2136 b.iter(|| {
2137 for i in 0..100 {
2138 deq.push_back(i);
2139 }
2140 deq.head = 0;
2141 deq.tail = 0;
2142 })
2143 }
2144
2145 #[bench]
2146 fn bench_push_front_100(b: &mut test::Bencher) {
2147 let mut deq = VecDeque::with_capacity(101);
2148 b.iter(|| {
2149 for i in 0..100 {
2150 deq.push_front(i);
2151 }
2152 deq.head = 0;
2153 deq.tail = 0;
2154 })
2155 }
2156
2157 #[bench]
2158 fn bench_pop_back_100(b: &mut test::Bencher) {
2159 let mut deq = VecDeque::<i32>::with_capacity(101);
2160
2161 b.iter(|| {
2162 deq.head = 100;
2163 deq.tail = 0;
2164 while !deq.is_empty() {
2165 test::black_box(deq.pop_back());
2166 }
2167 })
2168 }
2169
2170 #[bench]
2171 fn bench_pop_front_100(b: &mut test::Bencher) {
2172 let mut deq = VecDeque::<i32>::with_capacity(101);
2173
2174 b.iter(|| {
2175 deq.head = 100;
2176 deq.tail = 0;
2177 while !deq.is_empty() {
2178 test::black_box(deq.pop_front());
2179 }
2180 })
2181 }
2182
2183 #[test]
2184 fn test_swap_front_back_remove() {
2185 fn test(back: bool) {
2186 // This test checks that every single combination of tail position and length is tested.
2187 // Capacity 15 should be large enough to cover every case.
2188 let mut tester = VecDeque::with_capacity(15);
2189 let usable_cap = tester.capacity();
2190 let final_len = usable_cap / 2;
2191
2192 for len in 0..final_len {
2193 let expected = if back {
2194 (0..len).collect()
2195 } else {
2196 (0..len).rev().collect()
2197 };
2198 for tail_pos in 0..usable_cap {
2199 tester.tail = tail_pos;
2200 tester.head = tail_pos;
2201 if back {
2202 for i in 0..len * 2 {
2203 tester.push_front(i);
2204 }
2205 for i in 0..len {
2206 assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i));
2207 }
2208 } else {
2209 for i in 0..len * 2 {
2210 tester.push_back(i);
2211 }
2212 for i in 0..len {
2213 let idx = tester.len() - 1 - i;
2214 assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i));
2215 }
2216 }
2217 assert!(tester.tail < tester.cap());
2218 assert!(tester.head < tester.cap());
2219 assert_eq!(tester, expected);
2220 }
2221 }
2222 }
2223 test(true);
2224 test(false);
2225 }
2226
2227 #[test]
2228 fn test_insert() {
2229 // This test checks that every single combination of tail position, length, and
2230 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2231
2232 let mut tester = VecDeque::with_capacity(15);
2233 // can't guarantee we got 15, so have to get what we got.
2234 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2235 // this test isn't covering what it wants to
2236 let cap = tester.capacity();
2237
2238
2239 // len is the length *after* insertion
2240 for len in 1..cap {
2241 // 0, 1, 2, .., len - 1
2242 let expected = (0..).take(len).collect();
2243 for tail_pos in 0..cap {
2244 for to_insert in 0..len {
2245 tester.tail = tail_pos;
2246 tester.head = tail_pos;
2247 for i in 0..len {
2248 if i != to_insert {
2249 tester.push_back(i);
2250 }
2251 }
2252 tester.insert(to_insert, to_insert);
2253 assert!(tester.tail < tester.cap());
2254 assert!(tester.head < tester.cap());
2255 assert_eq!(tester, expected);
2256 }
2257 }
2258 }
2259 }
2260
2261 #[test]
2262 fn test_remove() {
2263 // This test checks that every single combination of tail position, length, and
2264 // removal position is tested. Capacity 15 should be large enough to cover every case.
2265
2266 let mut tester = VecDeque::with_capacity(15);
2267 // can't guarantee we got 15, so have to get what we got.
2268 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2269 // this test isn't covering what it wants to
2270 let cap = tester.capacity();
2271
2272 // len is the length *after* removal
2273 for len in 0..cap - 1 {
2274 // 0, 1, 2, .., len - 1
2275 let expected = (0..).take(len).collect();
2276 for tail_pos in 0..cap {
2277 for to_remove in 0..len + 1 {
2278 tester.tail = tail_pos;
2279 tester.head = tail_pos;
2280 for i in 0..len {
2281 if i == to_remove {
2282 tester.push_back(1234);
2283 }
2284 tester.push_back(i);
2285 }
2286 if to_remove == len {
2287 tester.push_back(1234);
2288 }
2289 tester.remove(to_remove);
2290 assert!(tester.tail < tester.cap());
2291 assert!(tester.head < tester.cap());
2292 assert_eq!(tester, expected);
2293 }
2294 }
2295 }
2296 }
2297
2298 #[test]
2299 fn test_drain() {
2300 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2301
2302 let cap = tester.capacity();
2303 for len in 0..cap + 1 {
2304 for tail in 0..cap + 1 {
2305 for drain_start in 0..len + 1 {
2306 for drain_end in drain_start..len + 1 {
2307 tester.tail = tail;
2308 tester.head = tail;
2309 for i in 0..len {
2310 tester.push_back(i);
2311 }
2312
2313 // Check that we drain the correct values
2314 let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect();
2315 let drained_expected: VecDeque<_> = (drain_start..drain_end).collect();
2316 assert_eq!(drained, drained_expected);
2317
2318 // We shouldn't have changed the capacity or made the
2319 // head or tail out of bounds
2320 assert_eq!(tester.capacity(), cap);
2321 assert!(tester.tail < tester.cap());
2322 assert!(tester.head < tester.cap());
2323
2324 // We should see the correct values in the VecDeque
2325 let expected: VecDeque<_> = (0..drain_start)
2326 .chain(drain_end..len)
2327 .collect();
2328 assert_eq!(expected, tester);
2329 }
2330 }
2331 }
2332 }
2333 }
2334
2335 #[test]
2336 fn test_shrink_to_fit() {
2337 // This test checks that every single combination of head and tail position,
2338 // is tested. Capacity 15 should be large enough to cover every case.
2339
2340 let mut tester = VecDeque::with_capacity(15);
2341 // can't guarantee we got 15, so have to get what we got.
2342 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2343 // this test isn't covering what it wants to
2344 let cap = tester.capacity();
2345 tester.reserve(63);
2346 let max_cap = tester.capacity();
2347
2348 for len in 0..cap + 1 {
2349 // 0, 1, 2, .., len - 1
2350 let expected = (0..).take(len).collect();
2351 for tail_pos in 0..max_cap + 1 {
2352 tester.tail = tail_pos;
2353 tester.head = tail_pos;
2354 tester.reserve(63);
2355 for i in 0..len {
2356 tester.push_back(i);
2357 }
2358 tester.shrink_to_fit();
2359 assert!(tester.capacity() <= cap);
2360 assert!(tester.tail < tester.cap());
2361 assert!(tester.head < tester.cap());
2362 assert_eq!(tester, expected);
2363 }
2364 }
2365 }
2366
2367 #[test]
2368 fn test_split_off() {
2369 // This test checks that every single combination of tail position, length, and
2370 // split position is tested. Capacity 15 should be large enough to cover every case.
2371
2372 let mut tester = VecDeque::with_capacity(15);
2373 // can't guarantee we got 15, so have to get what we got.
2374 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2375 // this test isn't covering what it wants to
2376 let cap = tester.capacity();
2377
2378 // len is the length *before* splitting
2379 for len in 0..cap {
2380 // index to split at
2381 for at in 0..len + 1 {
2382 // 0, 1, 2, .., at - 1 (may be empty)
2383 let expected_self = (0..).take(at).collect();
2384 // at, at + 1, .., len - 1 (may be empty)
2385 let expected_other = (at..).take(len - at).collect();
2386
2387 for tail_pos in 0..cap {
2388 tester.tail = tail_pos;
2389 tester.head = tail_pos;
2390 for i in 0..len {
2391 tester.push_back(i);
2392 }
2393 let result = tester.split_off(at);
2394 assert!(tester.tail < tester.cap());
2395 assert!(tester.head < tester.cap());
2396 assert!(result.tail < result.cap());
2397 assert!(result.head < result.cap());
2398 assert_eq!(tester, expected_self);
2399 assert_eq!(result, expected_other);
2400 }
2401 }
2402 }
2403 }
2404 }