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