blob: 4a2f7e378f7f83d265722dfca1b757d1a88fdb6b [file] [log] [blame]
Jonathan S03609e52014-04-21 04:59:121// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
Graydon Hoare00c856c2012-12-04 00:48:012// 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
Aaron Turon5fa9de12015-02-18 07:44:5511//! VecDeque is a double-ended queue, which is implemented with the help of a
12//! growing ring buffer.
Steve Klabnik0a795c22015-02-17 18:45:3513//!
Alex Crichton665ea962015-02-18 03:00:2014//! 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.
Patrick Waltonf3723cf2013-05-17 22:28:4418
Brian Andersonb44ee372015-01-24 05:48:2019#![stable(feature = "rust1", since = "1.0.0")]
Aaron Turoncb765ce2015-01-05 00:35:2020
Alex Crichton6a585372014-05-30 01:50:1221use core::prelude::*;
22
Alex Crichton56290a02014-12-22 17:04:2323use core::cmp::Ordering;
Tom Jakubowskid6a39412014-06-09 07:30:0424use core::default::Default;
Alex Crichton6a585372014-05-30 01:50:1225use core::fmt;
Jorge Aparicioa65d3f52015-01-08 03:01:0526use core::iter::{self, repeat, FromIterator, IntoIterator, RandomAccessIterator};
Colin Sherratt7a666df2014-10-19 20:19:0727use core::mem;
Colin Sherratt6277e3b2014-11-14 09:21:4428use core::num::{Int, UnsignedInt};
Alex Crichton56290a02014-12-22 17:04:2329use core::ops::{Index, IndexMut};
Niko Matsakis8dbdcdb2015-02-12 15:38:4530use core::ptr::{self, Unique};
Alex Crichton56290a02014-12-22 17:04:2331use core::raw::Slice as RawSlice;
Alex Crichton998fece2013-05-06 04:42:5432
Alex Crichtonf83e23a2015-02-18 04:48:0733use core::hash::{Hash, Hasher};
Keegan McAllister67350bc2014-09-07 21:57:2634use core::cmp;
Colin Sherratt7a666df2014-10-19 20:19:0735
36use alloc::heap;
blake2-ppc70523712013-07-10 13:27:1437
Aaron Turon5fa9de12015-02-18 07:44:5538#[deprecated(since = "1.0.0", reason = "renamed to VecDeque")]
39#[unstable(feature = "collections")]
40pub use VecDeque as RingBuf;
41
Alexis15fb06d2015-02-05 20:08:3342static INITIAL_CAPACITY: usize = 7; // 2^3 - 1
43static MINIMUM_CAPACITY: usize = 1; // 2 - 1
Alexis Beingessnercf3b2e42014-11-06 17:24:4744
Aaron Turon5fa9de12015-02-18 07:44:5545/// `VecDeque` is a growable ring buffer, which can be used as a
46/// double-ended queue efficiently.
Brian Andersonb44ee372015-01-24 05:48:2047#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5548pub struct VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:0749 // tail and head are pointers into the buffer. Tail always points
50 // to the first element that could be read, Head always points
51 // to where data should be written.
52 // If tail == head the buffer is empty. The length of the ringbuf
53 // is defined as the distance between the two.
54
Alexise250fe32015-02-05 02:17:1955 tail: usize,
56 head: usize,
57 cap: usize,
Niko Matsakis8dbdcdb2015-02-12 15:38:4558 ptr: Unique<T>,
Colin Sherratt7a666df2014-10-19 20:19:0759}
60
Brian Andersonb44ee372015-01-24 05:48:2061#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5562unsafe impl<T: Send> Send for VecDeque<T> {}
Rohit Joshi8fb25ab2014-12-30 09:20:2463
Brian Andersonb44ee372015-01-24 05:48:2064#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5565unsafe impl<T: Sync> Sync for VecDeque<T> {}
Rohit Joshi8fb25ab2014-12-30 09:20:2466
Brian Andersonb44ee372015-01-24 05:48:2067#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5568impl<T: Clone> Clone for VecDeque<T> {
69 fn clone(&self) -> VecDeque<T> {
Alexise250fe32015-02-05 02:17:1970 self.iter().cloned().collect()
Colin Sherratt7a666df2014-10-19 20:19:0771 }
72}
73
74#[unsafe_destructor]
Brian Andersonb44ee372015-01-24 05:48:2075#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5576impl<T> Drop for VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:0777 fn drop(&mut self) {
78 self.clear();
79 unsafe {
80 if mem::size_of::<T>() != 0 {
Niko Matsakis8dbdcdb2015-02-12 15:38:4581 heap::deallocate(*self.ptr as *mut u8,
Colin Sherratt7a666df2014-10-19 20:19:0782 self.cap * mem::size_of::<T>(),
83 mem::min_align_of::<T>())
84 }
85 }
86 }
Marijn Haverbeke26610db2012-01-11 11:49:3387}
Roy Frostig9c818892010-07-21 01:03:0988
Brian Andersonb44ee372015-01-24 05:48:2089#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5590impl<T> Default for VecDeque<T> {
Tom Jakubowskid6a39412014-06-09 07:30:0491 #[inline]
Aaron Turon5fa9de12015-02-18 07:44:5592 fn default() -> VecDeque<T> { VecDeque::new() }
Tom Jakubowskid6a39412014-06-09 07:30:0493}
94
Aaron Turon5fa9de12015-02-18 07:44:5595impl<T> VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:0796 /// Turn ptr into a slice
97 #[inline]
Alexis Beingessner8dbaa712014-12-31 00:07:5398 unsafe fn buffer_as_slice(&self) -> &[T] {
Niko Matsakis8dbdcdb2015-02-12 15:38:4599 mem::transmute(RawSlice { data: *self.ptr as *const T, len: self.cap })
Clark Gaebel525f65e2014-12-16 04:01:58100 }
101
102 /// Turn ptr into a mut slice
103 #[inline]
Alexis Beingessner8dbaa712014-12-31 00:07:53104 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
Niko Matsakis8dbdcdb2015-02-12 15:38:45105 mem::transmute(RawSlice { data: *self.ptr as *const T, len: self.cap })
Colin Sherratt7a666df2014-10-19 20:19:07106 }
107
108 /// Moves an element out of the buffer
109 #[inline]
Alexise250fe32015-02-05 02:17:19110 unsafe fn buffer_read(&mut self, off: usize) -> T {
111 ptr::read(self.ptr.offset(off as isize))
Colin Sherratt7a666df2014-10-19 20:19:07112 }
113
114 /// Writes an element into the buffer, moving it.
115 #[inline]
Alexise250fe32015-02-05 02:17:19116 unsafe fn buffer_write(&mut self, off: usize, t: T) {
117 ptr::write(self.ptr.offset(off as isize), t);
Colin Sherratt7a666df2014-10-19 20:19:07118 }
119
120 /// Returns true iff the buffer is at capacity
121 #[inline]
122 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
Colin Sherratt40191182014-11-12 01:22:07123
Alex Crichton665ea962015-02-18 03:00:20124 /// Returns the index in the underlying buffer for a given logical element
125 /// index.
Colin Sherratt40191182014-11-12 01:22:07126 #[inline]
Alexise250fe32015-02-05 02:17:19127 fn wrap_index(&self, idx: usize) -> usize { wrap_index(idx, self.cap) }
Matt Murphy40f28c72014-12-03 17:12:30128
129 /// Copies a contiguous block of memory len long from src to dst
130 #[inline]
Alexise250fe32015-02-05 02:17:19131 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
Piotr Czarnecki59d41532014-12-16 23:37:55132 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
133 self.cap);
134 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
135 self.cap);
Alex Crichtonab456942015-02-23 19:39:16136 ptr::copy(
Alexise250fe32015-02-05 02:17:19137 self.ptr.offset(dst as isize),
138 self.ptr.offset(src as isize),
Piotr Czarnecki156a1c32015-01-05 14:48:58139 len);
140 }
141
142 /// Copies a contiguous block of memory len long from src to dst
143 #[inline]
Alexise250fe32015-02-05 02:17:19144 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
Piotr Czarnecki156a1c32015-01-05 14:48:58145 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
146 self.cap);
147 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
148 self.cap);
Alex Crichtonab456942015-02-23 19:39:16149 ptr::copy_nonoverlapping(
Alexise250fe32015-02-05 02:17:19150 self.ptr.offset(dst as isize),
151 self.ptr.offset(src as isize),
Piotr Czarnecki59d41532014-12-16 23:37:55152 len);
Matt Murphy40f28c72014-12-03 17:12:30153 }
Colin Sherratt7a666df2014-10-19 20:19:07154}
155
Aaron Turon5fa9de12015-02-18 07:44:55156impl<T> VecDeque<T> {
157 /// Creates an empty `VecDeque`.
Brian Andersonb44ee372015-01-24 05:48:20158 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55159 pub fn new() -> VecDeque<T> {
160 VecDeque::with_capacity(INITIAL_CAPACITY)
blake2-ppc70523712013-07-10 13:27:14161 }
162
Aaron Turon5fa9de12015-02-18 07:44:55163 /// Creates an empty `VecDeque` with space for at least `n` elements.
Brian Andersonb44ee372015-01-24 05:48:20164 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55165 pub fn with_capacity(n: usize) -> VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:07166 // +1 since the ringbuffer always leaves one space empty
Piotr Czarnecki156a1c32015-01-05 14:48:58167 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
168 assert!(cap > n, "capacity overflow");
Colin Sherratt6277e3b2014-11-14 09:21:44169 let size = cap.checked_mul(mem::size_of::<T>())
Colin Sherratt7a666df2014-10-19 20:19:07170 .expect("capacity overflow");
171
Niko Matsakis8dbdcdb2015-02-12 15:38:45172 let ptr = unsafe {
173 if mem::size_of::<T>() != 0 {
Colin Sherrattba24e332014-11-10 03:34:53174 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
175 if ptr.is_null() { ::alloc::oom() }
Niko Matsakis8dbdcdb2015-02-12 15:38:45176 Unique::new(ptr)
177 } else {
178 Unique::new(heap::EMPTY as *mut T)
Colin Sherrattba24e332014-11-10 03:34:53179 }
Colin Sherrattba24e332014-11-10 03:34:53180 };
181
Aaron Turon5fa9de12015-02-18 07:44:55182 VecDeque {
Colin Sherratt7a666df2014-10-19 20:19:07183 tail: 0,
184 head: 0,
185 cap: cap,
Niko Matsakis8dbdcdb2015-02-12 15:38:45186 ptr: ptr,
Colin Sherratt7a666df2014-10-19 20:19:07187 }
blake2-ppc70523712013-07-10 13:27:14188 }
189
Aaron Turon5fa9de12015-02-18 07:44:55190 /// Retrieves an element in the `VecDeque` by index.
blake2-ppc70523712013-07-10 13:27:14191 ///
jbranchaudc09defa2014-12-09 05:28:07192 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47193 ///
194 /// ```rust
Aaron Turon5fa9de12015-02-18 07:44:55195 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47196 ///
Aaron Turon5fa9de12015-02-18 07:44:55197 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03198 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47199 /// buf.push_back(4);
200 /// buf.push_back(5);
201 /// assert_eq!(buf.get(1).unwrap(), &4);
202 /// ```
Brian Andersonb44ee372015-01-24 05:48:20203 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19204 pub fn get(&self, i: usize) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07205 if i < self.len() {
Colin Sherratt40191182014-11-12 01:22:07206 let idx = self.wrap_index(self.tail + i);
Alexise250fe32015-02-05 02:17:19207 unsafe { Some(&*self.ptr.offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07208 } else {
209 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47210 }
211 }
212
Aaron Turon5fa9de12015-02-18 07:44:55213 /// Retrieves an element in the `VecDeque` mutably by index.
nhamebe80972014-07-17 23:19:51214 ///
jbranchaudc09defa2014-12-09 05:28:07215 /// # Examples
nhamebe80972014-07-17 23:19:51216 ///
217 /// ```rust
Aaron Turon5fa9de12015-02-18 07:44:55218 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51219 ///
Aaron Turon5fa9de12015-02-18 07:44:55220 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03221 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47222 /// buf.push_back(4);
223 /// buf.push_back(5);
224 /// match buf.get_mut(1) {
225 /// None => {}
226 /// Some(elem) => {
227 /// *elem = 7;
228 /// }
229 /// }
230 ///
P1startfd10d202014-08-02 06:39:39231 /// assert_eq!(buf[1], 7);
nhamebe80972014-07-17 23:19:51232 /// ```
Brian Andersonb44ee372015-01-24 05:48:20233 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19234 pub fn get_mut(&mut self, i: usize) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07235 if i < self.len() {
Colin Sherratt40191182014-11-12 01:22:07236 let idx = self.wrap_index(self.tail + i);
Alexise250fe32015-02-05 02:17:19237 unsafe { Some(&mut *self.ptr.offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07238 } else {
239 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47240 }
blake2-ppc70523712013-07-10 13:27:14241 }
242
P1startf2aa88c2014-08-04 10:48:39243 /// Swaps elements at indices `i` and `j`.
blake2-ppc57757a82013-09-26 07:19:26244 ///
245 /// `i` and `j` may be equal.
246 ///
P1startf2aa88c2014-08-04 10:48:39247 /// Fails if there is no element with either index.
nhamebe80972014-07-17 23:19:51248 ///
jbranchaudc09defa2014-12-09 05:28:07249 /// # Examples
nhamebe80972014-07-17 23:19:51250 ///
251 /// ```rust
Aaron Turon5fa9de12015-02-18 07:44:55252 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51253 ///
Aaron Turon5fa9de12015-02-18 07:44:55254 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03255 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47256 /// buf.push_back(4);
257 /// buf.push_back(5);
nhamebe80972014-07-17 23:19:51258 /// buf.swap(0, 2);
P1startfd10d202014-08-02 06:39:39259 /// assert_eq!(buf[0], 5);
260 /// assert_eq!(buf[2], 3);
nhamebe80972014-07-17 23:19:51261 /// ```
Brian Andersonb44ee372015-01-24 05:48:20262 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19263 pub fn swap(&mut self, i: usize, j: usize) {
blake2-ppc57757a82013-09-26 07:19:26264 assert!(i < self.len());
265 assert!(j < self.len());
Colin Sherratt40191182014-11-12 01:22:07266 let ri = self.wrap_index(self.tail + i);
267 let rj = self.wrap_index(self.tail + j);
Colin Sherratt7a666df2014-10-19 20:19:07268 unsafe {
Alexise250fe32015-02-05 02:17:19269 ptr::swap(self.ptr.offset(ri as isize), self.ptr.offset(rj as isize))
Colin Sherratt7a666df2014-10-19 20:19:07270 }
blake2-ppc70523712013-07-10 13:27:14271 }
272
Aaron Turon5fa9de12015-02-18 07:44:55273 /// Returns the number of elements the `VecDeque` can hold without
Alexis Beingessnercf3b2e42014-11-06 17:24:47274 /// reallocating.
275 ///
jbranchaudc09defa2014-12-09 05:28:07276 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47277 ///
278 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55279 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47280 ///
Aaron Turon5fa9de12015-02-18 07:44:55281 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
Colin Sherratt7a666df2014-10-19 20:19:07282 /// assert!(buf.capacity() >= 10);
Alexis Beingessnercf3b2e42014-11-06 17:24:47283 /// ```
284 #[inline]
Brian Andersonb44ee372015-01-24 05:48:20285 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19286 pub fn capacity(&self) -> usize { self.cap - 1 }
Tim Chevalier77de84b2013-05-27 18:47:38287
Alexis Beingessnercf3b2e42014-11-06 17:24:47288 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
Aaron Turon5fa9de12015-02-18 07:44:55289 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
Tim Chevalier77de84b2013-05-27 18:47:38290 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47291 /// Note that the allocator may give the collection more space than it requests. Therefore
292 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
293 /// insertions are expected.
294 ///
295 /// # Panics
296 ///
Alexise250fe32015-02-05 02:17:19297 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47298 ///
jbranchaudc09defa2014-12-09 05:28:07299 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47300 ///
301 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55302 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47303 ///
Aaron Turon5fa9de12015-02-18 07:44:55304 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47305 /// buf.reserve_exact(10);
306 /// assert!(buf.capacity() >= 11);
307 /// ```
Brian Andersonb44ee372015-01-24 05:48:20308 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19309 pub fn reserve_exact(&mut self, additional: usize) {
Colin Sherratt7a666df2014-10-19 20:19:07310 self.reserve(additional);
Alexis Beingessnercf3b2e42014-11-06 17:24:47311 }
312
313 /// Reserves capacity for at least `additional` more elements to be inserted in the given
314 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
315 ///
316 /// # Panics
317 ///
Alexise250fe32015-02-05 02:17:19318 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47319 ///
jbranchaudc09defa2014-12-09 05:28:07320 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47321 ///
322 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55323 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47324 ///
Aaron Turon5fa9de12015-02-18 07:44:55325 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47326 /// buf.reserve(10);
327 /// assert!(buf.capacity() >= 11);
328 /// ```
Brian Andersonb44ee372015-01-24 05:48:20329 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19330 pub fn reserve(&mut self, additional: usize) {
Colin Sherratt7a666df2014-10-19 20:19:07331 let new_len = self.len() + additional;
332 assert!(new_len + 1 > self.len(), "capacity overflow");
333 if new_len > self.capacity() {
Colin Sherratt6277e3b2014-11-14 09:21:44334 let count = (new_len + 1).next_power_of_two();
Colin Sherratt7a666df2014-10-19 20:19:07335 assert!(count >= new_len + 1);
336
337 if mem::size_of::<T>() != 0 {
338 let old = self.cap * mem::size_of::<T>();
Colin Sherratt6277e3b2014-11-14 09:21:44339 let new = count.checked_mul(mem::size_of::<T>())
Colin Sherratt7a666df2014-10-19 20:19:07340 .expect("capacity overflow");
341 unsafe {
Niko Matsakis8dbdcdb2015-02-12 15:38:45342 let ptr = heap::reallocate(*self.ptr as *mut u8,
343 old,
344 new,
345 mem::min_align_of::<T>()) as *mut T;
346 if ptr.is_null() { ::alloc::oom() }
347 self.ptr = Unique::new(ptr);
Colin Sherratt7a666df2014-10-19 20:19:07348 }
349 }
350
351 // Move the shortest contiguous section of the ring buffer
352 // T H
353 // [o o o o o o o . ]
354 // T H
355 // A [o o o o o o o . . . . . . . . . ]
356 // H T
357 // [o o . o o o o o ]
358 // T H
359 // B [. . . o o o o o o o . . . . . . ]
360 // H T
361 // [o o o o o . o o ]
362 // H T
363 // C [o o o o o . . . . . . . . . o o ]
364
365 let oldcap = self.cap;
366 self.cap = count;
367
368 if self.tail <= self.head { // A
369 // Nop
370 } else if self.head < oldcap - self.tail { // B
371 unsafe {
Piotr Czarnecki156a1c32015-01-05 14:48:58372 self.copy_nonoverlapping(oldcap, 0, self.head);
Colin Sherratt7a666df2014-10-19 20:19:07373 }
374 self.head += oldcap;
Colin Sherratt4cae9ad2014-11-11 02:16:29375 debug_assert!(self.head > self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07376 } else { // C
Piotr Czarnecki156a1c32015-01-05 14:48:58377 let new_tail = count - (oldcap - self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07378 unsafe {
Piotr Czarnecki156a1c32015-01-05 14:48:58379 self.copy_nonoverlapping(new_tail, self.tail, oldcap - self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07380 }
Piotr Czarnecki156a1c32015-01-05 14:48:58381 self.tail = new_tail;
Colin Sherratt4cae9ad2014-11-11 02:16:29382 debug_assert!(self.head < self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07383 }
Colin Sherratt4cae9ad2014-11-11 02:16:29384 debug_assert!(self.head < self.cap);
385 debug_assert!(self.tail < self.cap);
Colin Sherratt40191182014-11-12 01:22:07386 debug_assert!(self.cap.count_ones() == 1);
Colin Sherratt7a666df2014-10-19 20:19:07387 }
Tim Chevalier77de84b2013-05-27 18:47:38388 }
Jed Estep4f7a7422013-06-25 19:08:47389
Piotr Czarnecki156a1c32015-01-05 14:48:58390 /// Shrinks the capacity of the ringbuf as much as possible.
391 ///
392 /// It will drop down as close as possible to the length but the allocator may still inform the
393 /// ringbuf that there is space for a few more elements.
394 ///
395 /// # Examples
396 ///
397 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55398 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58399 ///
Aaron Turon5fa9de12015-02-18 07:44:55400 /// let mut buf = VecDeque::with_capacity(15);
Alexise15538d2015-02-06 18:57:13401 /// buf.extend(0..4);
Piotr Czarnecki156a1c32015-01-05 14:48:58402 /// assert_eq!(buf.capacity(), 15);
403 /// buf.shrink_to_fit();
404 /// assert!(buf.capacity() >= 4);
405 /// ```
406 pub fn shrink_to_fit(&mut self) {
407 // +1 since the ringbuffer always leaves one space empty
408 // len + 1 can't overflow for an existing, well-formed ringbuf.
409 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
410 if target_cap < self.cap {
411 // There are three cases of interest:
412 // All elements are out of desired bounds
413 // Elements are contiguous, and head is out of desired bounds
414 // Elements are discontiguous, and tail is out of desired bounds
415 //
416 // At all other times, element positions are unaffected.
417 //
418 // Indicates that elements at the head should be moved.
419 let head_outside = self.head == 0 || self.head >= target_cap;
420 // Move elements from out of desired bounds (positions after target_cap)
421 if self.tail >= target_cap && head_outside {
422 // T H
423 // [. . . . . . . . o o o o o o o . ]
424 // T H
425 // [o o o o o o o . ]
426 unsafe {
427 self.copy_nonoverlapping(0, self.tail, self.len());
428 }
429 self.head = self.len();
430 self.tail = 0;
431 } else if self.tail != 0 && self.tail < target_cap && head_outside {
432 // T H
433 // [. . . o o o o o o o . . . . . . ]
434 // H T
435 // [o o . o o o o o ]
436 let len = self.wrap_index(self.head - target_cap);
437 unsafe {
438 self.copy_nonoverlapping(0, target_cap, len);
439 }
440 self.head = len;
441 debug_assert!(self.head < self.tail);
442 } else if self.tail >= target_cap {
443 // H T
444 // [o o o o o . . . . . . . . . o o ]
445 // H T
446 // [o o o o o . o o ]
447 debug_assert!(self.wrap_index(self.head - 1) < target_cap);
448 let len = self.cap - self.tail;
449 let new_tail = target_cap - len;
450 unsafe {
451 self.copy_nonoverlapping(new_tail, self.tail, len);
452 }
453 self.tail = new_tail;
454 debug_assert!(self.head < self.tail);
455 }
456
457 if mem::size_of::<T>() != 0 {
458 let old = self.cap * mem::size_of::<T>();
459 let new_size = target_cap * mem::size_of::<T>();
460 unsafe {
Niko Matsakis8dbdcdb2015-02-12 15:38:45461 let ptr = heap::reallocate(*self.ptr as *mut u8,
462 old,
463 new_size,
464 mem::min_align_of::<T>()) as *mut T;
465 if ptr.is_null() { ::alloc::oom() }
466 self.ptr = Unique::new(ptr);
Piotr Czarnecki156a1c32015-01-05 14:48:58467 }
468 }
469 self.cap = target_cap;
470 debug_assert!(self.head < self.cap);
471 debug_assert!(self.tail < self.cap);
472 debug_assert!(self.cap.count_ones() == 1);
473 }
474 }
475
476 /// Shorten a ringbuf, dropping excess elements from the back.
477 ///
478 /// If `len` is greater than the ringbuf's current length, this has no
479 /// effect.
480 ///
481 /// # Examples
482 ///
483 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55484 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58485 ///
Aaron Turon5fa9de12015-02-18 07:44:55486 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03487 /// buf.push_back(5);
488 /// buf.push_back(10);
Piotr Czarnecki156a1c32015-01-05 14:48:58489 /// buf.push_back(15);
490 /// buf.truncate(1);
491 /// assert_eq!(buf.len(), 1);
492 /// assert_eq!(Some(&5), buf.get(0));
493 /// ```
Brian Andersoncd6d9ea2015-01-23 02:22:03494 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19495 reason = "matches collection reform specification; waiting on panic semantics")]
Alexise250fe32015-02-05 02:17:19496 pub fn truncate(&mut self, len: usize) {
Jorge Aparicioefc97a52015-01-26 21:05:07497 for _ in len..self.len() {
Piotr Czarnecki156a1c32015-01-05 14:48:58498 self.pop_back();
499 }
500 }
501
P1startf2aa88c2014-08-04 10:48:39502 /// Returns a front-to-back iterator.
nhamebe80972014-07-17 23:19:51503 ///
jbranchaudc09defa2014-12-09 05:28:07504 /// # Examples
nhamebe80972014-07-17 23:19:51505 ///
506 /// ```rust
Aaron Turon5fa9de12015-02-18 07:44:55507 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51508 ///
Aaron Turon5fa9de12015-02-18 07:44:55509 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03510 /// buf.push_back(5);
Alexis Beingessnercf3b2e42014-11-06 17:24:47511 /// buf.push_back(3);
512 /// buf.push_back(4);
Nick Cameron52ef4622014-08-06 09:59:40513 /// let b: &[_] = &[&5, &3, &4];
Tobias Bucher7f64fe42015-01-25 21:05:03514 /// assert_eq!(buf.iter().collect::<Vec<&i32>>().as_slice(), b);
nhamebe80972014-07-17 23:19:51515 /// ```
Brian Andersonb44ee372015-01-24 05:48:20516 #[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:10517 pub fn iter(&self) -> Iter<T> {
518 Iter {
Colin Sherratt7a666df2014-10-19 20:19:07519 tail: self.tail,
520 head: self.head,
521 ring: unsafe { self.buffer_as_slice() }
522 }
blake2-ppc3385e792013-07-15 23:13:26523 }
524
Andrew Wagner8fcc8322014-12-15 09:22:49525 /// Returns a front-to-back iterator that returns mutable references.
nhamebe80972014-07-17 23:19:51526 ///
jbranchaudc09defa2014-12-09 05:28:07527 /// # Examples
nhamebe80972014-07-17 23:19:51528 ///
529 /// ```rust
Aaron Turon5fa9de12015-02-18 07:44:55530 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51531 ///
Aaron Turon5fa9de12015-02-18 07:44:55532 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03533 /// buf.push_back(5);
Alexis Beingessnercf3b2e42014-11-06 17:24:47534 /// buf.push_back(3);
535 /// buf.push_back(4);
Aaron Turonfc525ee2014-09-15 03:27:36536 /// for num in buf.iter_mut() {
nhamebe80972014-07-17 23:19:51537 /// *num = *num - 2;
538 /// }
Nick Cameron52ef4622014-08-06 09:59:40539 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
Tobias Bucher7f64fe42015-01-25 21:05:03540 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[], b);
nhamebe80972014-07-17 23:19:51541 /// ```
Brian Andersonb44ee372015-01-24 05:48:20542 #[stable(feature = "rust1", since = "1.0.0")]
Alexis1420ceb2015-02-05 18:48:20543 pub fn iter_mut(&mut self) -> IterMut<T> {
Florian Wilkensf8cfd242014-12-19 20:52:10544 IterMut {
Colin Sherratt7a666df2014-10-19 20:19:07545 tail: self.tail,
546 head: self.head,
Edward Wang101498c2015-02-25 10:11:23547 ring: unsafe { self.buffer_as_mut_slice() },
Niko Matsakisbc4164d2013-11-16 22:29:39548 }
Jed Estep4f7a7422013-06-25 19:08:47549 }
Alex Crichton21ac9852014-10-30 20:43:24550
Alexis Beingessner865c2db2014-11-23 02:34:11551 /// Consumes the list into an iterator yielding elements by value.
Brian Andersonb44ee372015-01-24 05:48:20552 #[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:10553 pub fn into_iter(self) -> IntoIter<T> {
554 IntoIter {
Alexis Beingessner865c2db2014-11-23 02:34:11555 inner: self,
556 }
557 }
558
Clark Gaebel525f65e2014-12-16 04:01:58559 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55560 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58561 #[inline]
Brian Andersoncd6d9ea2015-01-23 02:22:03562 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19563 reason = "matches collection reform specification, waiting for dust to settle")]
Alexis1420ceb2015-02-05 18:48:20564 pub fn as_slices(&self) -> (&[T], &[T]) {
Clark Gaebel525f65e2014-12-16 04:01:58565 unsafe {
566 let contiguous = self.is_contiguous();
567 let buf = self.buffer_as_slice();
568 if contiguous {
569 let (empty, buf) = buf.split_at(0);
Jorge Aparicio517f1cc2015-01-07 16:58:31570 (&buf[self.tail..self.head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58571 } else {
572 let (mid, right) = buf.split_at(self.tail);
573 let (left, _) = mid.split_at(self.head);
574 (right, left)
575 }
576 }
577 }
578
579 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55580 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58581 #[inline]
Brian Andersoncd6d9ea2015-01-23 02:22:03582 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19583 reason = "matches collection reform specification, waiting for dust to settle")]
Alexis1420ceb2015-02-05 18:48:20584 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
Clark Gaebel525f65e2014-12-16 04:01:58585 unsafe {
586 let contiguous = self.is_contiguous();
587 let head = self.head;
588 let tail = self.tail;
589 let buf = self.buffer_as_mut_slice();
590
591 if contiguous {
592 let (empty, buf) = buf.split_at_mut(0);
Aaron Turona506d4c2015-01-18 00:15:52593 (&mut buf[tail .. head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58594 } else {
595 let (mid, right) = buf.split_at_mut(tail);
596 let (left, _) = mid.split_at_mut(head);
597
598 (right, left)
599 }
600 }
601 }
602
Aaron Turon5fa9de12015-02-18 07:44:55603 /// Returns the number of elements in the `VecDeque`.
Alex Crichton21ac9852014-10-30 20:43:24604 ///
jbranchaudc09defa2014-12-09 05:28:07605 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24606 ///
607 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55608 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24609 ///
Aaron Turon5fa9de12015-02-18 07:44:55610 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24611 /// assert_eq!(v.len(), 0);
Tobias Bucher7f64fe42015-01-25 21:05:03612 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24613 /// assert_eq!(v.len(), 1);
614 /// ```
Brian Andersonb44ee372015-01-24 05:48:20615 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19616 pub fn len(&self) -> usize { count(self.tail, self.head, self.cap) }
Alex Crichton21ac9852014-10-30 20:43:24617
618 /// Returns true if the buffer contains no elements
619 ///
jbranchaudc09defa2014-12-09 05:28:07620 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24621 ///
622 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55623 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24624 ///
Aaron Turon5fa9de12015-02-18 07:44:55625 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24626 /// assert!(v.is_empty());
Tobias Bucher7f64fe42015-01-25 21:05:03627 /// v.push_front(1);
Alex Crichton21ac9852014-10-30 20:43:24628 /// assert!(!v.is_empty());
629 /// ```
Brian Andersonb44ee372015-01-24 05:48:20630 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24631 pub fn is_empty(&self) -> bool { self.len() == 0 }
632
Aaron Turon5fa9de12015-02-18 07:44:55633 /// Creates a draining iterator that clears the `VecDeque` and iterates over
Clark Gaebeld57f2592014-12-16 22:45:03634 /// the removed items from start to end.
635 ///
636 /// # Examples
637 ///
638 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55639 /// use std::collections::VecDeque;
Clark Gaebeld57f2592014-12-16 22:45:03640 ///
Aaron Turon5fa9de12015-02-18 07:44:55641 /// let mut v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03642 /// v.push_back(1);
Clark Gaebeld57f2592014-12-16 22:45:03643 /// assert_eq!(v.drain().next(), Some(1));
644 /// assert!(v.is_empty());
645 /// ```
646 #[inline]
Brian Andersoncd6d9ea2015-01-23 02:22:03647 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19648 reason = "matches collection reform specification, waiting for dust to settle")]
Alexis Beingessner8dbaa712014-12-31 00:07:53649 pub fn drain(&mut self) -> Drain<T> {
Clark Gaebeld57f2592014-12-16 22:45:03650 Drain {
651 inner: self,
652 }
653 }
654
Alex Crichton21ac9852014-10-30 20:43:24655 /// Clears the buffer, removing all values.
656 ///
jbranchaudc09defa2014-12-09 05:28:07657 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24658 ///
659 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55660 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24661 ///
Aaron Turon5fa9de12015-02-18 07:44:55662 /// let mut v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03663 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24664 /// v.clear();
665 /// assert!(v.is_empty());
666 /// ```
Brian Andersonb44ee372015-01-24 05:48:20667 #[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:03668 #[inline]
Alex Crichton21ac9852014-10-30 20:43:24669 pub fn clear(&mut self) {
Clark Gaebeld57f2592014-12-16 22:45:03670 self.drain();
Alex Crichton21ac9852014-10-30 20:43:24671 }
672
673 /// Provides a reference to the front element, or `None` if the sequence is
674 /// empty.
675 ///
jbranchaudc09defa2014-12-09 05:28:07676 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24677 ///
678 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55679 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24680 ///
Aaron Turon5fa9de12015-02-18 07:44:55681 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24682 /// assert_eq!(d.front(), None);
683 ///
Tobias Bucher7f64fe42015-01-25 21:05:03684 /// d.push_back(1);
685 /// d.push_back(2);
686 /// assert_eq!(d.front(), Some(&1));
Alex Crichton21ac9852014-10-30 20:43:24687 /// ```
Brian Andersonb44ee372015-01-24 05:48:20688 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24689 pub fn front(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07690 if !self.is_empty() { Some(&self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24691 }
692
693 /// Provides a mutable reference to the front element, or `None` if the
694 /// sequence is empty.
695 ///
jbranchaudc09defa2014-12-09 05:28:07696 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24697 ///
698 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55699 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24700 ///
Aaron Turon5fa9de12015-02-18 07:44:55701 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24702 /// assert_eq!(d.front_mut(), None);
703 ///
Tobias Bucher7f64fe42015-01-25 21:05:03704 /// d.push_back(1);
705 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24706 /// match d.front_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03707 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24708 /// None => (),
709 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03710 /// assert_eq!(d.front(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24711 /// ```
Brian Andersonb44ee372015-01-24 05:48:20712 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24713 pub fn front_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07714 if !self.is_empty() { Some(&mut self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24715 }
716
717 /// Provides a reference to the back element, or `None` if the sequence is
718 /// empty.
719 ///
jbranchaudc09defa2014-12-09 05:28:07720 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24721 ///
722 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55723 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24724 ///
Aaron Turon5fa9de12015-02-18 07:44:55725 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24726 /// assert_eq!(d.back(), None);
727 ///
Tobias Bucher7f64fe42015-01-25 21:05:03728 /// d.push_back(1);
729 /// d.push_back(2);
730 /// assert_eq!(d.back(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24731 /// ```
Brian Andersonb44ee372015-01-24 05:48:20732 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24733 pub fn back(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07734 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24735 }
736
737 /// Provides a mutable reference to the back element, or `None` if the
738 /// sequence is empty.
739 ///
jbranchaudc09defa2014-12-09 05:28:07740 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24741 ///
742 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55743 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24744 ///
Aaron Turon5fa9de12015-02-18 07:44:55745 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24746 /// assert_eq!(d.back(), None);
747 ///
Tobias Bucher7f64fe42015-01-25 21:05:03748 /// d.push_back(1);
749 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24750 /// match d.back_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03751 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24752 /// None => (),
753 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03754 /// assert_eq!(d.back(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24755 /// ```
Brian Andersonb44ee372015-01-24 05:48:20756 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24757 pub fn back_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07758 let len = self.len();
759 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24760 }
761
762 /// Removes the first element and returns it, or `None` if the sequence is
763 /// empty.
764 ///
jbranchaudc09defa2014-12-09 05:28:07765 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24766 ///
767 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55768 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24769 ///
Aaron Turon5fa9de12015-02-18 07:44:55770 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03771 /// d.push_back(1);
772 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24773 ///
Tobias Bucher7f64fe42015-01-25 21:05:03774 /// assert_eq!(d.pop_front(), Some(1));
775 /// assert_eq!(d.pop_front(), Some(2));
Alex Crichton21ac9852014-10-30 20:43:24776 /// assert_eq!(d.pop_front(), None);
777 /// ```
Brian Andersonb44ee372015-01-24 05:48:20778 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24779 pub fn pop_front(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07780 if self.is_empty() {
781 None
782 } else {
783 let tail = self.tail;
Colin Sherratt40191182014-11-12 01:22:07784 self.tail = self.wrap_index(self.tail + 1);
Colin Sherratt7a666df2014-10-19 20:19:07785 unsafe { Some(self.buffer_read(tail)) }
Alex Crichton21ac9852014-10-30 20:43:24786 }
Alex Crichton21ac9852014-10-30 20:43:24787 }
788
789 /// Inserts an element first in the sequence.
790 ///
jbranchaudc09defa2014-12-09 05:28:07791 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24792 ///
793 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55794 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24795 ///
Aaron Turon5fa9de12015-02-18 07:44:55796 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03797 /// d.push_front(1);
798 /// d.push_front(2);
799 /// assert_eq!(d.front(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24800 /// ```
Brian Andersonb44ee372015-01-24 05:48:20801 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24802 pub fn push_front(&mut self, t: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29803 if self.is_full() {
804 self.reserve(1);
805 debug_assert!(!self.is_full());
806 }
Colin Sherratt7a666df2014-10-19 20:19:07807
Colin Sherratt40191182014-11-12 01:22:07808 self.tail = self.wrap_index(self.tail - 1);
Colin Sherratt7a666df2014-10-19 20:19:07809 let tail = self.tail;
810 unsafe { self.buffer_write(tail, t); }
Alex Crichton21ac9852014-10-30 20:43:24811 }
812
813 /// Appends an element to the back of a buffer
814 ///
jbranchaudc09defa2014-12-09 05:28:07815 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24816 ///
817 /// ```rust
Aaron Turon5fa9de12015-02-18 07:44:55818 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24819 ///
Aaron Turon5fa9de12015-02-18 07:44:55820 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03821 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:47822 /// buf.push_back(3);
Alex Crichton21ac9852014-10-30 20:43:24823 /// assert_eq!(3, *buf.back().unwrap());
824 /// ```
Brian Andersonb44ee372015-01-24 05:48:20825 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnercf3b2e42014-11-06 17:24:47826 pub fn push_back(&mut self, t: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29827 if self.is_full() {
828 self.reserve(1);
829 debug_assert!(!self.is_full());
830 }
Colin Sherratt7a666df2014-10-19 20:19:07831
832 let head = self.head;
Colin Sherratt40191182014-11-12 01:22:07833 self.head = self.wrap_index(self.head + 1);
Colin Sherratt7a666df2014-10-19 20:19:07834 unsafe { self.buffer_write(head, t) }
Alex Crichton21ac9852014-10-30 20:43:24835 }
836
837 /// Removes the last element from a buffer and returns it, or `None` if
838 /// it is empty.
839 ///
jbranchaudc09defa2014-12-09 05:28:07840 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24841 ///
842 /// ```rust
Aaron Turon5fa9de12015-02-18 07:44:55843 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24844 ///
Aaron Turon5fa9de12015-02-18 07:44:55845 /// let mut buf = VecDeque::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47846 /// assert_eq!(buf.pop_back(), None);
Tobias Bucher7f64fe42015-01-25 21:05:03847 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:47848 /// buf.push_back(3);
849 /// assert_eq!(buf.pop_back(), Some(3));
Alex Crichton21ac9852014-10-30 20:43:24850 /// ```
Brian Andersonb44ee372015-01-24 05:48:20851 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnercf3b2e42014-11-06 17:24:47852 pub fn pop_back(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07853 if self.is_empty() {
Alex Crichton21ac9852014-10-30 20:43:24854 None
Colin Sherratt7a666df2014-10-19 20:19:07855 } else {
Colin Sherratt40191182014-11-12 01:22:07856 self.head = self.wrap_index(self.head - 1);
Colin Sherratt7a666df2014-10-19 20:19:07857 let head = self.head;
858 unsafe { Some(self.buffer_read(head)) }
Alex Crichton21ac9852014-10-30 20:43:24859 }
860 }
Matt Murphy40f28c72014-12-03 17:12:30861
Clark Gaebel525f65e2014-12-16 04:01:58862 #[inline]
863 fn is_contiguous(&self) -> bool {
864 self.tail <= self.head
865 }
866
Piotr Czarnecki156a1c32015-01-05 14:48:58867 /// Removes an element from anywhere in the ringbuf and returns it, replacing it with the last
868 /// element.
869 ///
870 /// This does not preserve ordering, but is O(1).
871 ///
872 /// Returns `None` if `index` is out of bounds.
873 ///
874 /// # Examples
875 ///
876 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55877 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58878 ///
Aaron Turon5fa9de12015-02-18 07:44:55879 /// let mut buf = VecDeque::new();
Piotr Czarnecki156a1c32015-01-05 14:48:58880 /// assert_eq!(buf.swap_back_remove(0), None);
Tobias Bucher7f64fe42015-01-25 21:05:03881 /// buf.push_back(5);
Piotr Czarnecki156a1c32015-01-05 14:48:58882 /// buf.push_back(99);
883 /// buf.push_back(15);
884 /// buf.push_back(20);
885 /// buf.push_back(10);
886 /// assert_eq!(buf.swap_back_remove(1), Some(99));
887 /// ```
Brian Andersoncd6d9ea2015-01-23 02:22:03888 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19889 reason = "the naming of this function may be altered")]
Alexise250fe32015-02-05 02:17:19890 pub fn swap_back_remove(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:58891 let length = self.len();
892 if length > 0 && index < length - 1 {
893 self.swap(index, length - 1);
894 } else if index >= length {
895 return None;
896 }
897 self.pop_back()
898 }
899
900 /// Removes an element from anywhere in the ringbuf and returns it, replacing it with the first
901 /// element.
902 ///
903 /// This does not preserve ordering, but is O(1).
904 ///
905 /// Returns `None` if `index` is out of bounds.
906 ///
907 /// # Examples
908 ///
909 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55910 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58911 ///
Aaron Turon5fa9de12015-02-18 07:44:55912 /// let mut buf = VecDeque::new();
Piotr Czarnecki156a1c32015-01-05 14:48:58913 /// assert_eq!(buf.swap_front_remove(0), None);
Tobias Bucher7f64fe42015-01-25 21:05:03914 /// buf.push_back(15);
Piotr Czarnecki156a1c32015-01-05 14:48:58915 /// buf.push_back(5);
916 /// buf.push_back(10);
917 /// buf.push_back(99);
Tobias Bucher7f64fe42015-01-25 21:05:03918 /// buf.push_back(20);
Piotr Czarnecki156a1c32015-01-05 14:48:58919 /// assert_eq!(buf.swap_front_remove(3), Some(99));
920 /// ```
Brian Andersoncd6d9ea2015-01-23 02:22:03921 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19922 reason = "the naming of this function may be altered")]
Alexise250fe32015-02-05 02:17:19923 pub fn swap_front_remove(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:58924 let length = self.len();
925 if length > 0 && index < length && index != 0 {
926 self.swap(index, 0);
927 } else if index >= length {
928 return None;
929 }
930 self.pop_front()
931 }
932
Matt Murphy40f28c72014-12-03 17:12:30933 /// Inserts an element at position `i` within the ringbuf. Whichever
934 /// end is closer to the insertion point will be moved to make room,
935 /// and all the affected elements will be moved to new positions.
936 ///
937 /// # Panics
938 ///
939 /// Panics if `i` is greater than ringbuf's length
940 ///
Piotr Czarnecki156a1c32015-01-05 14:48:58941 /// # Examples
Matt Murphy40f28c72014-12-03 17:12:30942 /// ```rust
Aaron Turon5fa9de12015-02-18 07:44:55943 /// use std::collections::VecDeque;
Matt Murphy40f28c72014-12-03 17:12:30944 ///
Aaron Turon5fa9de12015-02-18 07:44:55945 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03946 /// buf.push_back(10);
Matt Murphy40f28c72014-12-03 17:12:30947 /// buf.push_back(12);
948 /// buf.insert(1,11);
949 /// assert_eq!(Some(&11), buf.get(1));
950 /// ```
Alexise250fe32015-02-05 02:17:19951 pub fn insert(&mut self, i: usize, t: T) {
Matt Murphy40f28c72014-12-03 17:12:30952 assert!(i <= self.len(), "index out of bounds");
953 if self.is_full() {
954 self.reserve(1);
955 debug_assert!(!self.is_full());
956 }
957
958 // Move the least number of elements in the ring buffer and insert
959 // the given object
960 //
961 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
962 //
963 // There are three main cases:
964 // Elements are contiguous
965 // - special case when tail is 0
966 // Elements are discontiguous and the insert is in the tail section
967 // Elements are discontiguous and the insert is in the head section
968 //
969 // For each of those there are two more cases:
970 // Insert is closer to tail
971 // Insert is closer to head
972 //
973 // Key: H - self.head
974 // T - self.tail
975 // o - Valid element
976 // I - Insertion element
977 // A - The element that should be after the insertion point
978 // M - Indicates element was moved
979
980 let idx = self.wrap_index(self.tail + i);
981
982 let distance_to_tail = i;
983 let distance_to_head = self.len() - i;
984
Clark Gaebel525f65e2014-12-16 04:01:58985 let contiguous = self.is_contiguous();
Matt Murphy40f28c72014-12-03 17:12:30986
987 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
988 (true, true, _) if i == 0 => {
989 // push_front
990 //
991 // T
992 // I H
993 // [A o o o o o o . . . . . . . . .]
994 //
995 // H T
996 // [A o o o o o o o . . . . . I]
997 //
998
999 self.tail = self.wrap_index(self.tail - 1);
1000 },
Piotr Czarnecki59d41532014-12-16 23:37:551001 (true, true, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:301002 // contiguous, insert closer to tail:
1003 //
1004 // T I H
1005 // [. . . o o A o o o o . . . . . .]
1006 //
1007 // T H
1008 // [. . o o I A o o o o . . . . . .]
1009 // M M
1010 //
1011 // contiguous, insert closer to tail and tail is 0:
1012 //
1013 //
1014 // T I H
1015 // [o o A o o o o . . . . . . . . .]
1016 //
1017 // H T
1018 // [o I A o o o o o . . . . . . . o]
1019 // M M
1020
Piotr Czarnecki59d41532014-12-16 23:37:551021 let new_tail = self.wrap_index(self.tail - 1);
Matt Murphy40f28c72014-12-03 17:12:301022
Piotr Czarnecki59d41532014-12-16 23:37:551023 self.copy(new_tail, self.tail, 1);
1024 // Already moved the tail, so we only copy `i - 1` elements.
1025 self.copy(self.tail, self.tail + 1, i - 1);
1026
1027 self.tail = new_tail;
Matt Murphy40f28c72014-12-03 17:12:301028 },
Piotr Czarnecki59d41532014-12-16 23:37:551029 (true, false, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:301030 // contiguous, insert closer to head:
1031 //
1032 // T I H
1033 // [. . . o o o o A o o . . . . . .]
1034 //
1035 // T H
1036 // [. . . o o o o I A o o . . . . .]
1037 // M M M
1038
Piotr Czarnecki59d41532014-12-16 23:37:551039 self.copy(idx + 1, idx, self.head - idx);
Matt Murphy40f28c72014-12-03 17:12:301040 self.head = self.wrap_index(self.head + 1);
Matt Murphy40f28c72014-12-03 17:12:301041 },
Piotr Czarnecki59d41532014-12-16 23:37:551042 (false, true, true) => unsafe {
1043 // discontiguous, insert closer to tail, tail section:
Matt Murphy40f28c72014-12-03 17:12:301044 //
1045 // H T I
1046 // [o o o o o o . . . . . o o A o o]
1047 //
1048 // H T
1049 // [o o o o o o . . . . o o I A o o]
1050 // M M
1051
Piotr Czarnecki59d41532014-12-16 23:37:551052 self.copy(self.tail - 1, self.tail, i);
1053 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301054 },
Piotr Czarnecki59d41532014-12-16 23:37:551055 (false, false, true) => unsafe {
1056 // discontiguous, insert closer to head, tail section:
Matt Murphy40f28c72014-12-03 17:12:301057 //
1058 // H T I
1059 // [o o . . . . . . . o o o o o A o]
1060 //
1061 // H T
1062 // [o o o . . . . . . o o o o o I A]
1063 // M M M M
1064
Matt Murphy40f28c72014-12-03 17:12:301065 // copy elements up to new head
Piotr Czarnecki59d41532014-12-16 23:37:551066 self.copy(1, 0, self.head);
Matt Murphy40f28c72014-12-03 17:12:301067
1068 // copy last element into empty spot at bottom of buffer
1069 self.copy(0, self.cap - 1, 1);
1070
1071 // move elements from idx to end forward not including ^ element
1072 self.copy(idx + 1, idx, self.cap - 1 - idx);
Piotr Czarnecki59d41532014-12-16 23:37:551073
1074 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301075 },
Piotr Czarnecki59d41532014-12-16 23:37:551076 (false, true, false) if idx == 0 => unsafe {
1077 // discontiguous, insert is closer to tail, head section,
Matt Murphy40f28c72014-12-03 17:12:301078 // and is at index zero in the internal buffer:
1079 //
1080 // I H T
1081 // [A o o o o o o o o o . . . o o o]
1082 //
1083 // H T
1084 // [A o o o o o o o o o . . o o o I]
1085 // M M M
1086
Matt Murphy40f28c72014-12-03 17:12:301087 // copy elements up to new tail
Piotr Czarnecki59d41532014-12-16 23:37:551088 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301089
1090 // copy last element into empty spot at bottom of buffer
1091 self.copy(self.cap - 1, 0, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551092
1093 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301094 },
Piotr Czarnecki59d41532014-12-16 23:37:551095 (false, true, false) => unsafe {
1096 // discontiguous, insert closer to tail, head section:
Matt Murphy40f28c72014-12-03 17:12:301097 //
1098 // I H T
1099 // [o o o A o o o o o o . . . o o o]
1100 //
1101 // H T
1102 // [o o I A o o o o o o . . o o o o]
1103 // M M M M M M
1104
Matt Murphy40f28c72014-12-03 17:12:301105 // copy elements up to new tail
Piotr Czarnecki59d41532014-12-16 23:37:551106 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301107
1108 // copy last element into empty spot at bottom of buffer
1109 self.copy(self.cap - 1, 0, 1);
1110
1111 // move elements from idx-1 to end forward not including ^ element
1112 self.copy(0, 1, idx - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551113
1114 self.tail -= 1;
1115 },
1116 (false, false, false) => unsafe {
1117 // discontiguous, insert closer to head, head section:
Matt Murphy40f28c72014-12-03 17:12:301118 //
1119 // I H T
1120 // [o o o o A o o . . . . . . o o o]
1121 //
1122 // H T
1123 // [o o o o I A o o . . . . . o o o]
1124 // M M M
1125
Piotr Czarnecki59d41532014-12-16 23:37:551126 self.copy(idx + 1, idx, self.head - idx);
1127 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301128 }
1129 }
1130
1131 // tail might've been changed so we need to recalculate
1132 let new_idx = self.wrap_index(self.tail + i);
1133 unsafe {
1134 self.buffer_write(new_idx, t);
1135 }
1136 }
Piotr Czarnecki59d41532014-12-16 23:37:551137
1138 /// Removes and returns the element at position `i` from the ringbuf.
1139 /// Whichever end is closer to the removal point will be moved to make
1140 /// room, and all the affected elements will be moved to new positions.
1141 /// Returns `None` if `i` is out of bounds.
1142 ///
Piotr Czarnecki156a1c32015-01-05 14:48:581143 /// # Examples
Piotr Czarnecki59d41532014-12-16 23:37:551144 /// ```rust
Aaron Turon5fa9de12015-02-18 07:44:551145 /// use std::collections::VecDeque;
Piotr Czarnecki59d41532014-12-16 23:37:551146 ///
Aaron Turon5fa9de12015-02-18 07:44:551147 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031148 /// buf.push_back(5);
1149 /// buf.push_back(10);
1150 /// buf.push_back(12);
Piotr Czarnecki59d41532014-12-16 23:37:551151 /// buf.push_back(15);
1152 /// buf.remove(2);
1153 /// assert_eq!(Some(&15), buf.get(2));
1154 /// ```
Brian Andersonb44ee372015-01-24 05:48:201155 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:191156 pub fn remove(&mut self, i: usize) -> Option<T> {
Piotr Czarnecki59d41532014-12-16 23:37:551157 if self.is_empty() || self.len() <= i {
1158 return None;
1159 }
1160
1161 // There are three main cases:
1162 // Elements are contiguous
1163 // Elements are discontiguous and the removal is in the tail section
1164 // Elements are discontiguous and the removal is in the head section
1165 // - special case when elements are technically contiguous,
1166 // but self.head = 0
1167 //
1168 // For each of those there are two more cases:
1169 // Insert is closer to tail
1170 // Insert is closer to head
1171 //
1172 // Key: H - self.head
1173 // T - self.tail
1174 // o - Valid element
1175 // x - Element marked for removal
1176 // R - Indicates element that is being removed
1177 // M - Indicates element was moved
1178
1179 let idx = self.wrap_index(self.tail + i);
1180
1181 let elem = unsafe {
1182 Some(self.buffer_read(idx))
1183 };
1184
1185 let distance_to_tail = i;
1186 let distance_to_head = self.len() - i;
1187
Piotr Czarnecki156a1c32015-01-05 14:48:581188 let contiguous = self.is_contiguous();
Piotr Czarnecki59d41532014-12-16 23:37:551189
1190 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1191 (true, true, _) => unsafe {
1192 // contiguous, remove closer to tail:
1193 //
1194 // T R H
1195 // [. . . o o x o o o o . . . . . .]
1196 //
1197 // T H
1198 // [. . . . o o o o o o . . . . . .]
1199 // M M
1200
1201 self.copy(self.tail + 1, self.tail, i);
1202 self.tail += 1;
1203 },
1204 (true, false, _) => unsafe {
1205 // contiguous, remove closer to head:
1206 //
1207 // T R H
1208 // [. . . o o o o x o o . . . . . .]
1209 //
1210 // T H
1211 // [. . . o o o o o o . . . . . . .]
1212 // M M
1213
1214 self.copy(idx, idx + 1, self.head - idx - 1);
1215 self.head -= 1;
1216 },
1217 (false, true, true) => unsafe {
1218 // discontiguous, remove closer to tail, tail section:
1219 //
1220 // H T R
1221 // [o o o o o o . . . . . o o x o o]
1222 //
1223 // H T
1224 // [o o o o o o . . . . . . o o o o]
1225 // M M
1226
1227 self.copy(self.tail + 1, self.tail, i);
1228 self.tail = self.wrap_index(self.tail + 1);
1229 },
1230 (false, false, false) => unsafe {
1231 // discontiguous, remove closer to head, head section:
1232 //
1233 // R H T
1234 // [o o o o x o o . . . . . . o o o]
1235 //
1236 // H T
1237 // [o o o o o o . . . . . . . o o o]
1238 // M M
1239
1240 self.copy(idx, idx + 1, self.head - idx - 1);
1241 self.head -= 1;
1242 },
1243 (false, false, true) => unsafe {
1244 // discontiguous, remove closer to head, tail section:
1245 //
1246 // H T R
1247 // [o o o . . . . . . o o o o o x o]
1248 //
1249 // H T
1250 // [o o . . . . . . . o o o o o o o]
1251 // M M M M
1252 //
1253 // or quasi-discontiguous, remove next to head, tail section:
1254 //
1255 // H T R
1256 // [. . . . . . . . . o o o o o x o]
1257 //
1258 // T H
1259 // [. . . . . . . . . o o o o o o .]
1260 // M
1261
1262 // draw in elements in the tail section
1263 self.copy(idx, idx + 1, self.cap - idx - 1);
1264
1265 // Prevents underflow.
1266 if self.head != 0 {
1267 // copy first element into empty spot
1268 self.copy(self.cap - 1, 0, 1);
1269
1270 // move elements in the head section backwards
1271 self.copy(0, 1, self.head - 1);
1272 }
1273
1274 self.head = self.wrap_index(self.head - 1);
1275 },
1276 (false, true, false) => unsafe {
1277 // discontiguous, remove closer to tail, head section:
1278 //
1279 // R H T
1280 // [o o x o o o o o o o . . . o o o]
1281 //
1282 // H T
1283 // [o o o o o o o o o o . . . . o o]
1284 // M M M M M
1285
1286 // draw in elements up to idx
1287 self.copy(1, 0, idx);
1288
1289 // copy last element into empty spot
1290 self.copy(0, self.cap - 1, 1);
1291
1292 // move elements from tail to end forward, excluding the last one
1293 self.copy(self.tail + 1, self.tail, self.cap - self.tail - 1);
1294
1295 self.tail = self.wrap_index(self.tail + 1);
1296 }
1297 }
1298
1299 return elem;
1300 }
Alexisdc930b12015-02-07 16:46:161301
1302 /// Splits the collection into two at the given index.
1303 ///
1304 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1305 /// and the returned `Self` contains elements `[at, len)`.
1306 ///
1307 /// Note that the capacity of `self` does not change.
1308 ///
1309 /// # Panics
1310 ///
1311 /// Panics if `at > len`
1312 ///
1313 /// # Examples
Alexis3c18bc42015-02-07 17:13:321314 ///
1315 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551316 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321317 ///
Aaron Turon5fa9de12015-02-18 07:44:551318 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
Alexisdc930b12015-02-07 16:46:161319 /// let buf2 = buf.split_off(1);
1320 /// // buf = [1], buf2 = [2, 3]
1321 /// assert_eq!(buf.len(), 1);
1322 /// assert_eq!(buf2.len(), 2);
1323 /// ```
1324 #[inline]
1325 #[unstable(feature = "collections",
1326 reason = "new API, waiting for dust to settle")]
1327 pub fn split_off(&mut self, at: usize) -> Self {
1328 let len = self.len();
1329 assert!(at <= len, "`at` out of bounds");
1330
1331 let other_len = len - at;
Aaron Turon5fa9de12015-02-18 07:44:551332 let mut other = VecDeque::with_capacity(other_len);
Alexisdc930b12015-02-07 16:46:161333
1334 unsafe {
1335 let (first_half, second_half) = self.as_slices();
1336
1337 let first_len = first_half.len();
1338 let second_len = second_half.len();
1339 if at < first_len {
1340 // `at` lies in the first half.
1341 let amount_in_first = first_len - at;
1342
Alex Crichtonab456942015-02-23 19:39:161343 ptr::copy_nonoverlapping(*other.ptr,
1344 first_half.as_ptr().offset(at as isize),
1345 amount_in_first);
Alexisdc930b12015-02-07 16:46:161346
1347 // just take all of the second half.
Alex Crichtonab456942015-02-23 19:39:161348 ptr::copy_nonoverlapping(other.ptr.offset(amount_in_first as isize),
1349 second_half.as_ptr(),
1350 second_len);
Alexisdc930b12015-02-07 16:46:161351 } else {
1352 // `at` lies in the second half, need to factor in the elements we skipped
1353 // in the first half.
1354 let offset = at - first_len;
1355 let amount_in_second = second_len - offset;
Alex Crichtonab456942015-02-23 19:39:161356 ptr::copy_nonoverlapping(*other.ptr,
1357 second_half.as_ptr().offset(offset as isize),
1358 amount_in_second);
Alexisdc930b12015-02-07 16:46:161359 }
1360 }
1361
1362 // Cleanup where the ends of the buffers are
1363 self.head = self.wrap_index(self.head - other_len);
1364 other.head = other.wrap_index(other_len);
1365
1366 other
1367 }
Alexis3c18bc42015-02-07 17:13:321368
1369 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1370 ///
1371 /// # Panics
1372 ///
1373 /// Panics if the new number of elements in self overflows a `usize`.
1374 ///
1375 /// # Examples
1376 ///
1377 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551378 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321379 ///
Aaron Turon5fa9de12015-02-18 07:44:551380 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1381 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
Alexis3c18bc42015-02-07 17:13:321382 /// buf.append(&mut buf2);
1383 /// assert_eq!(buf.len(), 6);
1384 /// assert_eq!(buf2.len(), 0);
1385 /// ```
1386 #[inline]
1387 #[unstable(feature = "collections",
1388 reason = "new API, waiting for dust to settle")]
1389 pub fn append(&mut self, other: &mut Self) {
1390 // naive impl
1391 self.extend(other.drain());
1392 }
Jed Estep4f7a7422013-06-25 19:08:471393}
1394
Aaron Turon5fa9de12015-02-18 07:44:551395impl<T: Clone> VecDeque<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:581396 /// Modifies the ringbuf in-place so that `len()` is equal to new_len,
1397 /// either by removing excess elements or by appending copies of a value to the back.
1398 ///
1399 /// # Examples
1400 ///
1401 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551402 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:581403 ///
Aaron Turon5fa9de12015-02-18 07:44:551404 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031405 /// buf.push_back(5);
1406 /// buf.push_back(10);
Piotr Czarnecki156a1c32015-01-05 14:48:581407 /// buf.push_back(15);
1408 /// buf.resize(2, 0);
1409 /// buf.resize(6, 20);
1410 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(buf.iter()) {
1411 /// assert_eq!(a, b);
1412 /// }
1413 /// ```
Brian Andersoncd6d9ea2015-01-23 02:22:031414 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:191415 reason = "matches collection reform specification; waiting on panic semantics")]
Alexise250fe32015-02-05 02:17:191416 pub fn resize(&mut self, new_len: usize, value: T) {
Piotr Czarnecki156a1c32015-01-05 14:48:581417 let len = self.len();
1418
1419 if new_len > len {
1420 self.extend(repeat(value).take(new_len - len))
1421 } else {
1422 self.truncate(new_len);
1423 }
1424 }
1425}
1426
Colin Sherratt7a666df2014-10-19 20:19:071427/// Returns the index in the underlying buffer for a given logical element index.
1428#[inline]
Alexise250fe32015-02-05 02:17:191429fn wrap_index(index: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071430 // size is always a power of 2
Colin Sherratt40191182014-11-12 01:22:071431 index & (size - 1)
Colin Sherratt7a666df2014-10-19 20:19:071432}
1433
1434/// Calculate the number of elements left to be read in the buffer
1435#[inline]
Alexise250fe32015-02-05 02:17:191436fn count(tail: usize, head: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071437 // size is always a power of 2
1438 (head - tail) & (size - 1)
1439}
1440
Aaron Turon5fa9de12015-02-18 07:44:551441/// `VecDeque` iterator.
Brian Andersonb44ee372015-01-24 05:48:201442#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101443pub struct Iter<'a, T:'a> {
Colin Sherratt7a666df2014-10-19 20:19:071444 ring: &'a [T],
Alexise250fe32015-02-05 02:17:191445 tail: usize,
1446 head: usize
Niko Matsakis1b487a82014-08-28 01:46:521447}
1448
Jorge Aparicio351409a2015-01-04 03:54:181449// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
Huon Wilsonb7832ed2014-12-30 10:01:361450impl<'a, T> Clone for Iter<'a, T> {
1451 fn clone(&self) -> Iter<'a, T> {
1452 Iter {
1453 ring: self.ring,
1454 tail: self.tail,
1455 head: self.head
1456 }
1457 }
1458}
1459
Brian Andersonb44ee372015-01-24 05:48:201460#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351461impl<'a, T> Iterator for Iter<'a, T> {
1462 type Item = &'a T;
1463
Niko Matsakisbc4164d2013-11-16 22:29:391464 #[inline]
Erik Price5731ca32013-12-10 07:16:181465 fn next(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071466 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391467 return None;
1468 }
Colin Sherratt7a666df2014-10-19 20:19:071469 let tail = self.tail;
1470 self.tail = wrap_index(self.tail + 1, self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181471 unsafe { Some(self.ring.get_unchecked(tail)) }
Niko Matsakisbc4164d2013-11-16 22:29:391472 }
1473
1474 #[inline]
Alexise250fe32015-02-05 02:17:191475 fn size_hint(&self) -> (usize, Option<usize>) {
Colin Sherratt7a666df2014-10-19 20:19:071476 let len = count(self.tail, self.head, self.ring.len());
Niko Matsakisbc4164d2013-11-16 22:29:391477 (len, Some(len))
1478 }
1479}
1480
Brian Andersonb44ee372015-01-24 05:48:201481#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351482impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391483 #[inline]
Erik Price5731ca32013-12-10 07:16:181484 fn next_back(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071485 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391486 return None;
1487 }
Colin Sherratt7a666df2014-10-19 20:19:071488 self.head = wrap_index(self.head - 1, self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181489 unsafe { Some(self.ring.get_unchecked(self.head)) }
Niko Matsakisbc4164d2013-11-16 22:29:391490 }
1491}
Jed Estep35314c92013-06-26 15:38:291492
Brian Andersonb44ee372015-01-24 05:48:201493#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351494impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241495
Brian Andersonb44ee372015-01-24 05:48:201496#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351497impl<'a, T> RandomAccessIterator for Iter<'a, T> {
blake2-ppcf6862132013-07-29 18:16:261498 #[inline]
Alexise250fe32015-02-05 02:17:191499 fn indexable(&self) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071500 let (len, _) = self.size_hint();
1501 len
1502 }
blake2-ppcf6862132013-07-29 18:16:261503
1504 #[inline]
Alexise250fe32015-02-05 02:17:191505 fn idx(&mut self, j: usize) -> Option<&'a T> {
blake2-ppcf6862132013-07-29 18:16:261506 if j >= self.indexable() {
1507 None
1508 } else {
Colin Sherratt7a666df2014-10-19 20:19:071509 let idx = wrap_index(self.tail + j, self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181510 unsafe { Some(self.ring.get_unchecked(idx)) }
blake2-ppcf6862132013-07-29 18:16:261511 }
1512 }
1513}
1514
Aaron Turon5fa9de12015-02-18 07:44:551515/// `VecDeque` mutable iterator.
Brian Andersonb44ee372015-01-24 05:48:201516#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101517pub struct IterMut<'a, T:'a> {
Edward Wang101498c2015-02-25 10:11:231518 ring: &'a mut [T],
Alexise250fe32015-02-05 02:17:191519 tail: usize,
1520 head: usize,
Niko Matsakis1b487a82014-08-28 01:46:521521}
1522
Brian Andersonb44ee372015-01-24 05:48:201523#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351524impl<'a, T> Iterator for IterMut<'a, T> {
1525 type Item = &'a mut T;
1526
Niko Matsakisbc4164d2013-11-16 22:29:391527 #[inline]
Erik Price5731ca32013-12-10 07:16:181528 fn next(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:071529 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391530 return None;
1531 }
Colin Sherratt7a666df2014-10-19 20:19:071532 let tail = self.tail;
Edward Wang101498c2015-02-25 10:11:231533 self.tail = wrap_index(self.tail + 1, self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111534
1535 unsafe {
Edward Wang101498c2015-02-25 10:11:231536 let elem = self.ring.get_unchecked_mut(tail);
1537 Some(&mut *(elem as *mut _))
Alex Crichton9d5d97b2014-10-15 06:05:011538 }
Niko Matsakisbc4164d2013-11-16 22:29:391539 }
1540
1541 #[inline]
Alexise250fe32015-02-05 02:17:191542 fn size_hint(&self) -> (usize, Option<usize>) {
Edward Wang101498c2015-02-25 10:11:231543 let len = count(self.tail, self.head, self.ring.len());
Colin Sherratt7a666df2014-10-19 20:19:071544 (len, Some(len))
Niko Matsakisbc4164d2013-11-16 22:29:391545 }
1546}
1547
Brian Andersonb44ee372015-01-24 05:48:201548#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351549impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391550 #[inline]
Erik Price5731ca32013-12-10 07:16:181551 fn next_back(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:071552 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391553 return None;
1554 }
Edward Wang101498c2015-02-25 10:11:231555 self.head = wrap_index(self.head - 1, self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111556
1557 unsafe {
Edward Wang101498c2015-02-25 10:11:231558 let elem = self.ring.get_unchecked_mut(self.head);
1559 Some(&mut *(elem as *mut _))
Alexis Beingessner865c2db2014-11-23 02:34:111560 }
Niko Matsakisbc4164d2013-11-16 22:29:391561 }
1562}
Daniel Micayb47e1e92013-02-16 22:55:551563
Brian Andersonb44ee372015-01-24 05:48:201564#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351565impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241566
Aaron Turon5fa9de12015-02-18 07:44:551567/// A by-value VecDeque iterator
Brian Andersonb44ee372015-01-24 05:48:201568#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101569pub struct IntoIter<T> {
Aaron Turon5fa9de12015-02-18 07:44:551570 inner: VecDeque<T>,
Alexis Beingessner865c2db2014-11-23 02:34:111571}
1572
Brian Andersonb44ee372015-01-24 05:48:201573#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351574impl<T> Iterator for IntoIter<T> {
1575 type Item = T;
1576
Alexis Beingessner865c2db2014-11-23 02:34:111577 #[inline]
1578 fn next(&mut self) -> Option<T> {
1579 self.inner.pop_front()
1580 }
1581
1582 #[inline]
Alexise250fe32015-02-05 02:17:191583 fn size_hint(&self) -> (usize, Option<usize>) {
Alexis Beingessner865c2db2014-11-23 02:34:111584 let len = self.inner.len();
1585 (len, Some(len))
1586 }
1587}
1588
Brian Andersonb44ee372015-01-24 05:48:201589#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351590impl<T> DoubleEndedIterator for IntoIter<T> {
Alexis Beingessner865c2db2014-11-23 02:34:111591 #[inline]
1592 fn next_back(&mut self) -> Option<T> {
1593 self.inner.pop_back()
1594 }
1595}
1596
Brian Andersonb44ee372015-01-24 05:48:201597#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351598impl<T> ExactSizeIterator for IntoIter<T> {}
Alexis Beingessner865c2db2014-11-23 02:34:111599
Aaron Turon5fa9de12015-02-18 07:44:551600/// A draining VecDeque iterator
Brian Andersoncd6d9ea2015-01-23 02:22:031601#[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:191602 reason = "matches collection reform specification, waiting for dust to settle")]
Clark Gaebeld57f2592014-12-16 22:45:031603pub struct Drain<'a, T: 'a> {
Aaron Turon5fa9de12015-02-18 07:44:551604 inner: &'a mut VecDeque<T>,
Clark Gaebeld57f2592014-12-16 22:45:031605}
1606
1607#[unsafe_destructor]
Brian Andersonb44ee372015-01-24 05:48:201608#[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:031609impl<'a, T: 'a> Drop for Drain<'a, T> {
1610 fn drop(&mut self) {
Jorge Apariciof9865ea2015-01-11 02:50:071611 for _ in self.by_ref() {}
Clark Gaebeld57f2592014-12-16 22:45:031612 self.inner.head = 0;
1613 self.inner.tail = 0;
1614 }
1615}
1616
Brian Andersonb44ee372015-01-24 05:48:201617#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351618impl<'a, T: 'a> Iterator for Drain<'a, T> {
1619 type Item = T;
1620
Clark Gaebeld57f2592014-12-16 22:45:031621 #[inline]
1622 fn next(&mut self) -> Option<T> {
1623 self.inner.pop_front()
1624 }
1625
1626 #[inline]
Alexise250fe32015-02-05 02:17:191627 fn size_hint(&self) -> (usize, Option<usize>) {
Clark Gaebeld57f2592014-12-16 22:45:031628 let len = self.inner.len();
1629 (len, Some(len))
1630 }
1631}
1632
Brian Andersonb44ee372015-01-24 05:48:201633#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351634impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
Clark Gaebeld57f2592014-12-16 22:45:031635 #[inline]
1636 fn next_back(&mut self) -> Option<T> {
1637 self.inner.pop_back()
1638 }
1639}
1640
Brian Andersonb44ee372015-01-24 05:48:201641#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351642impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
Clark Gaebeld57f2592014-12-16 22:45:031643
Brian Andersonb44ee372015-01-24 05:48:201644#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551645impl<A: PartialEq> PartialEq for VecDeque<A> {
1646 fn eq(&self, other: &VecDeque<A>) -> bool {
Colin Sherratt7a666df2014-10-19 20:19:071647 self.len() == other.len() &&
blake2-ppc10c76982013-07-06 13:27:321648 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
1649 }
blake2-ppc10c76982013-07-06 13:27:321650}
1651
Brian Andersonb44ee372015-01-24 05:48:201652#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551653impl<A: Eq> Eq for VecDeque<A> {}
nham25acfde2014-08-01 20:05:031654
Brian Andersonb44ee372015-01-24 05:48:201655#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551656impl<A: PartialOrd> PartialOrd for VecDeque<A> {
1657 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
nham63615772014-07-27 03:18:561658 iter::order::partial_cmp(self.iter(), other.iter())
1659 }
1660}
1661
Brian Andersonb44ee372015-01-24 05:48:201662#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551663impl<A: Ord> Ord for VecDeque<A> {
nham3737c532014-08-01 20:22:481664 #[inline]
Aaron Turon5fa9de12015-02-18 07:44:551665 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
nham3737c532014-08-01 20:22:481666 iter::order::cmp(self.iter(), other.iter())
1667 }
1668}
1669
Brian Andersonb44ee372015-01-24 05:48:201670#[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton5a32b4a2015-02-18 22:34:081671impl<A: Hash> Hash for VecDeque<A> {
Alex Crichtonf83e23a2015-02-18 04:48:071672 fn hash<H: Hasher>(&self, state: &mut H) {
1673 self.len().hash(state);
1674 for elt in self {
1675 elt.hash(state);
1676 }
1677 }
1678}
nham1cfa6562014-07-27 02:33:471679
Brian Andersonb44ee372015-01-24 05:48:201680#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551681impl<A> Index<usize> for VecDeque<A> {
Jorge Aparicio32dd5922015-01-03 15:40:101682 type Output = A;
1683
1684 #[inline]
Alexis1420ceb2015-02-05 18:48:201685 fn index(&self, i: &usize) -> &A {
Jorge Aparicio32dd5922015-01-03 15:40:101686 self.get(*i).expect("Out of bounds access")
1687 }
1688}
1689
Brian Andersonb44ee372015-01-24 05:48:201690#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551691impl<A> IndexMut<usize> for VecDeque<A> {
Jorge Aparicio32dd5922015-01-03 15:40:101692 #[inline]
Alexis1420ceb2015-02-05 18:48:201693 fn index_mut(&mut self, i: &usize) -> &mut A {
Jorge Aparicio32dd5922015-01-03 15:40:101694 self.get_mut(*i).expect("Out of bounds access")
1695 }
1696}
1697
Brian Andersonb44ee372015-01-24 05:48:201698#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551699impl<A> FromIterator<A> for VecDeque<A> {
Alexis66613e22015-02-18 18:06:211700 fn from_iter<T: IntoIterator<Item=A>>(iterable: T) -> VecDeque<A> {
1701 let iterator = iterable.into_iter();
blake2-ppcf8ae5262013-07-30 00:06:491702 let (lower, _) = iterator.size_hint();
Aaron Turon5fa9de12015-02-18 07:44:551703 let mut deq = VecDeque::with_capacity(lower);
blake2-ppcf8ae5262013-07-30 00:06:491704 deq.extend(iterator);
blake2-ppc08dc72f2013-07-06 03:42:451705 deq
1706 }
1707}
1708
Alex Crichtoncc687862015-02-17 18:06:241709#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551710impl<T> IntoIterator for VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101711 type Item = T;
1712 type IntoIter = IntoIter<T>;
1713
1714 fn into_iter(self) -> IntoIter<T> {
1715 self.into_iter()
1716 }
1717}
1718
Alex Crichtoncc687862015-02-17 18:06:241719#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551720impl<'a, T> IntoIterator for &'a VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101721 type Item = &'a T;
1722 type IntoIter = Iter<'a, T>;
1723
1724 fn into_iter(self) -> Iter<'a, T> {
1725 self.iter()
1726 }
1727}
1728
Alex Crichtoncc687862015-02-17 18:06:241729#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551730impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101731 type Item = &'a mut T;
1732 type IntoIter = IterMut<'a, T>;
1733
1734 fn into_iter(mut self) -> IterMut<'a, T> {
1735 self.iter_mut()
1736 }
1737}
1738
Brian Andersonb44ee372015-01-24 05:48:201739#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551740impl<A> Extend<A> for VecDeque<A> {
Alexis4a9d1902015-02-18 15:04:301741 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
1742 for elt in iter {
Alexis Beingessnercf3b2e42014-11-06 17:24:471743 self.push_back(elt);
blake2-ppcf8ae5262013-07-30 00:06:491744 }
1745 }
1746}
1747
Brian Andersonb44ee372015-01-24 05:48:201748#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551749impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041750 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Tobias Bucher408f7b52015-02-10 21:12:131751 try!(write!(f, "["));
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041752
1753 for (i, e) in self.iter().enumerate() {
1754 if i != 0 { try!(write!(f, ", ")); }
Sean McArthur44440e52014-12-20 08:09:351755 try!(write!(f, "{:?}", *e));
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041756 }
1757
1758 write!(f, "]")
1759 }
1760}
1761
Brian Anderson6e27b272012-01-18 03:05:071762#[cfg(test)]
1763mod tests {
Steven Fackler3dcd2152014-11-06 08:05:531764 use self::Taggy::*;
1765 use self::Taggypar::*;
Eduard Burtescub45d30d2014-12-19 12:02:221766 use prelude::*;
Eduard Burtescub45d30d2014-12-19 12:02:221767 use core::iter;
Alex Crichton3cb9fa22015-01-20 23:45:071768 use std::fmt::Debug;
Alex Crichton511f0b82014-12-09 20:37:231769 use std::hash::{self, SipHasher};
Alex Crichton760b93a2014-05-30 02:03:061770 use test::Bencher;
1771 use test;
1772
Aaron Turon5fa9de12015-02-18 07:44:551773 use super::VecDeque;
Patrick Waltonfa5ee932012-12-28 02:24:181774
Brian Anderson6e27b272012-01-18 03:05:071775 #[test]
Victor Berger52ea83d2014-09-22 17:30:061776 #[allow(deprecated)]
Brian Anderson6e27b272012-01-18 03:05:071777 fn test_simple() {
Aaron Turon5fa9de12015-02-18 07:44:551778 let mut d = VecDeque::new();
Alexise250fe32015-02-05 02:17:191779 assert_eq!(d.len(), 0);
Tobias Bucher7f64fe42015-01-25 21:05:031780 d.push_front(17);
1781 d.push_front(42);
Alexis Beingessnercf3b2e42014-11-06 17:24:471782 d.push_back(137);
Alexise250fe32015-02-05 02:17:191783 assert_eq!(d.len(), 3);
Alexis Beingessnercf3b2e42014-11-06 17:24:471784 d.push_back(137);
Alexise250fe32015-02-05 02:17:191785 assert_eq!(d.len(), 4);
blake2-ppc70523712013-07-10 13:27:141786 assert_eq!(*d.front().unwrap(), 42);
blake2-ppc70523712013-07-10 13:27:141787 assert_eq!(*d.back().unwrap(), 137);
1788 let mut i = d.pop_front();
blake2-ppc70523712013-07-10 13:27:141789 assert_eq!(i, Some(42));
Alexis Beingessnercf3b2e42014-11-06 17:24:471790 i = d.pop_back();
blake2-ppc70523712013-07-10 13:27:141791 assert_eq!(i, Some(137));
Alexis Beingessnercf3b2e42014-11-06 17:24:471792 i = d.pop_back();
blake2-ppc70523712013-07-10 13:27:141793 assert_eq!(i, Some(137));
Alexis Beingessnercf3b2e42014-11-06 17:24:471794 i = d.pop_back();
blake2-ppc70523712013-07-10 13:27:141795 assert_eq!(i, Some(17));
Alexise250fe32015-02-05 02:17:191796 assert_eq!(d.len(), 0);
Alexis Beingessnercf3b2e42014-11-06 17:24:471797 d.push_back(3);
Alexise250fe32015-02-05 02:17:191798 assert_eq!(d.len(), 1);
blake2-ppc70523712013-07-10 13:27:141799 d.push_front(2);
Alexise250fe32015-02-05 02:17:191800 assert_eq!(d.len(), 2);
Alexis Beingessnercf3b2e42014-11-06 17:24:471801 d.push_back(4);
Alexise250fe32015-02-05 02:17:191802 assert_eq!(d.len(), 3);
blake2-ppc70523712013-07-10 13:27:141803 d.push_front(1);
Alexise250fe32015-02-05 02:17:191804 assert_eq!(d.len(), 4);
Alex Crichton9d5d97b2014-10-15 06:05:011805 debug!("{}", d[0]);
1806 debug!("{}", d[1]);
1807 debug!("{}", d[2]);
1808 debug!("{}", d[3]);
1809 assert_eq!(d[0], 1);
1810 assert_eq!(d[1], 2);
1811 assert_eq!(d[2], 3);
1812 assert_eq!(d[3], 4);
Brian Anderson6e27b272012-01-18 03:05:071813 }
1814
Felix S. Klock IIa636f512013-05-01 23:32:371815 #[cfg(test)]
Alex Crichton3cb9fa22015-01-20 23:45:071816 fn test_parameterized<T:Clone + PartialEq + Debug>(a: T, b: T, c: T, d: T) {
Aaron Turon5fa9de12015-02-18 07:44:551817 let mut deq = VecDeque::new();
Corey Richardsoncc57ca02013-05-19 02:02:451818 assert_eq!(deq.len(), 0);
Patrick Waltondc4bf172013-07-13 04:05:591819 deq.push_front(a.clone());
1820 deq.push_front(b.clone());
Alexis Beingessnercf3b2e42014-11-06 17:24:471821 deq.push_back(c.clone());
Corey Richardsoncc57ca02013-05-19 02:02:451822 assert_eq!(deq.len(), 3);
Alexis Beingessnercf3b2e42014-11-06 17:24:471823 deq.push_back(d.clone());
Corey Richardsoncc57ca02013-05-19 02:02:451824 assert_eq!(deq.len(), 4);
Marvin Löbel0ac7a212013-08-03 23:59:241825 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
1826 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
1827 assert_eq!(deq.pop_front().unwrap(), b.clone());
Alexis Beingessnercf3b2e42014-11-06 17:24:471828 assert_eq!(deq.pop_back().unwrap(), d.clone());
1829 assert_eq!(deq.pop_back().unwrap(), c.clone());
1830 assert_eq!(deq.pop_back().unwrap(), a.clone());
Corey Richardsoncc57ca02013-05-19 02:02:451831 assert_eq!(deq.len(), 0);
Alexis Beingessnercf3b2e42014-11-06 17:24:471832 deq.push_back(c.clone());
Corey Richardsoncc57ca02013-05-19 02:02:451833 assert_eq!(deq.len(), 1);
Patrick Waltondc4bf172013-07-13 04:05:591834 deq.push_front(b.clone());
Corey Richardsoncc57ca02013-05-19 02:02:451835 assert_eq!(deq.len(), 2);
Alexis Beingessnercf3b2e42014-11-06 17:24:471836 deq.push_back(d.clone());
Corey Richardsoncc57ca02013-05-19 02:02:451837 assert_eq!(deq.len(), 3);
Patrick Waltondc4bf172013-07-13 04:05:591838 deq.push_front(a.clone());
Corey Richardsoncc57ca02013-05-19 02:02:451839 assert_eq!(deq.len(), 4);
NODA, Kaif27ad3d2014-10-05 10:11:171840 assert_eq!(deq[0].clone(), a.clone());
1841 assert_eq!(deq[1].clone(), b.clone());
1842 assert_eq!(deq[2].clone(), c.clone());
1843 assert_eq!(deq[3].clone(), d.clone());
Brian Anderson6e27b272012-01-18 03:05:071844 }
1845
blake2-ppc81933ed2013-07-06 03:42:451846 #[test]
blake2-ppc70523712013-07-10 13:27:141847 fn test_push_front_grow() {
Aaron Turon5fa9de12015-02-18 07:44:551848 let mut deq = VecDeque::new();
Alexise250fe32015-02-05 02:17:191849 for i in 0..66 {
blake2-ppc70523712013-07-10 13:27:141850 deq.push_front(i);
blake2-ppc81933ed2013-07-06 03:42:451851 }
1852 assert_eq!(deq.len(), 66);
1853
Alexise250fe32015-02-05 02:17:191854 for i in 0..66 {
NODA, Kaif27ad3d2014-10-05 10:11:171855 assert_eq!(deq[i], 65 - i);
blake2-ppc81933ed2013-07-06 03:42:451856 }
1857
Aaron Turon5fa9de12015-02-18 07:44:551858 let mut deq = VecDeque::new();
Alexise250fe32015-02-05 02:17:191859 for i in 0..66 {
Alexis Beingessnercf3b2e42014-11-06 17:24:471860 deq.push_back(i);
blake2-ppc81933ed2013-07-06 03:42:451861 }
1862
Alexise250fe32015-02-05 02:17:191863 for i in 0..66 {
NODA, Kaif27ad3d2014-10-05 10:11:171864 assert_eq!(deq[i], i);
blake2-ppc81933ed2013-07-06 03:42:451865 }
1866 }
1867
P1startfd10d202014-08-02 06:39:391868 #[test]
1869 fn test_index() {
Aaron Turon5fa9de12015-02-18 07:44:551870 let mut deq = VecDeque::new();
Alexise250fe32015-02-05 02:17:191871 for i in 1..4 {
P1startfd10d202014-08-02 06:39:391872 deq.push_front(i);
1873 }
1874 assert_eq!(deq[1], 2);
1875 }
1876
1877 #[test]
1878 #[should_fail]
1879 fn test_index_out_of_bounds() {
Aaron Turon5fa9de12015-02-18 07:44:551880 let mut deq = VecDeque::new();
Alexise250fe32015-02-05 02:17:191881 for i in 1..4 {
P1startfd10d202014-08-02 06:39:391882 deq.push_front(i);
1883 }
1884 deq[3];
1885 }
1886
blake2-ppc81933ed2013-07-06 03:42:451887 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:351888 fn bench_new(b: &mut test::Bencher) {
Patrick Walton38efa172013-11-22 03:20:481889 b.iter(|| {
Aaron Turon5fa9de12015-02-18 07:44:551890 let ring: VecDeque<i32> = VecDeque::new();
Colin Sherratt5e549d82014-11-11 02:57:521891 test::black_box(ring);
Patrick Walton38efa172013-11-22 03:20:481892 })
blake2-ppc81933ed2013-07-06 03:42:451893 }
1894
1895 #[bench]
Colin Sherratt7a666df2014-10-19 20:19:071896 fn bench_push_back_100(b: &mut test::Bencher) {
Aaron Turon5fa9de12015-02-18 07:44:551897 let mut deq = VecDeque::with_capacity(101);
Patrick Walton38efa172013-11-22 03:20:481898 b.iter(|| {
Tobias Bucher7f64fe42015-01-25 21:05:031899 for i in 0..100 {
Colin Sherratt7a666df2014-10-19 20:19:071900 deq.push_back(i);
1901 }
Colin Sherratt5e549d82014-11-11 02:57:521902 deq.head = 0;
1903 deq.tail = 0;
Patrick Walton38efa172013-11-22 03:20:481904 })
blake2-ppc81933ed2013-07-06 03:42:451905 }
1906
1907 #[bench]
Colin Sherratt7a666df2014-10-19 20:19:071908 fn bench_push_front_100(b: &mut test::Bencher) {
Aaron Turon5fa9de12015-02-18 07:44:551909 let mut deq = VecDeque::with_capacity(101);
Patrick Walton38efa172013-11-22 03:20:481910 b.iter(|| {
Tobias Bucher7f64fe42015-01-25 21:05:031911 for i in 0..100 {
Colin Sherratt7a666df2014-10-19 20:19:071912 deq.push_front(i);
1913 }
Colin Sherratt5e549d82014-11-11 02:57:521914 deq.head = 0;
1915 deq.tail = 0;
Patrick Walton38efa172013-11-22 03:20:481916 })
blake2-ppc81933ed2013-07-06 03:42:451917 }
1918
1919 #[bench]
Colin Sherratt5e549d82014-11-11 02:57:521920 fn bench_pop_back_100(b: &mut test::Bencher) {
Aaron Turon5fa9de12015-02-18 07:44:551921 let mut deq= VecDeque::<i32>::with_capacity(101);
Colin Sherratt7a666df2014-10-19 20:19:071922
Patrick Walton38efa172013-11-22 03:20:481923 b.iter(|| {
Colin Sherratt5e549d82014-11-11 02:57:521924 deq.head = 100;
1925 deq.tail = 0;
1926 while !deq.is_empty() {
1927 test::black_box(deq.pop_back());
Colin Sherratt7a666df2014-10-19 20:19:071928 }
Colin Sherratt7a666df2014-10-19 20:19:071929 })
1930 }
1931
1932 #[bench]
1933 fn bench_pop_front_100(b: &mut test::Bencher) {
Aaron Turon5fa9de12015-02-18 07:44:551934 let mut deq = VecDeque::<i32>::with_capacity(101);
Colin Sherratt7a666df2014-10-19 20:19:071935
1936 b.iter(|| {
Colin Sherratt5e549d82014-11-11 02:57:521937 deq.head = 100;
1938 deq.tail = 0;
1939 while !deq.is_empty() {
1940 test::black_box(deq.pop_front());
Colin Sherratt7a666df2014-10-19 20:19:071941 }
Colin Sherratt7a666df2014-10-19 20:19:071942 })
1943 }
1944
1945 #[bench]
1946 fn bench_grow_1025(b: &mut test::Bencher) {
1947 b.iter(|| {
Aaron Turon5fa9de12015-02-18 07:44:551948 let mut deq = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031949 for i in 0..1025 {
Colin Sherratt7a666df2014-10-19 20:19:071950 deq.push_front(i);
Brendan Zabarauskas729060d2014-01-30 00:20:341951 }
Colin Sherratt5e549d82014-11-11 02:57:521952 test::black_box(deq);
Patrick Walton38efa172013-11-22 03:20:481953 })
blake2-ppc81933ed2013-07-06 03:42:451954 }
1955
Colin Sherratt7a666df2014-10-19 20:19:071956 #[bench]
1957 fn bench_iter_1000(b: &mut test::Bencher) {
Aaron Turon5fa9de12015-02-18 07:44:551958 let ring: VecDeque<_> = (0..1000).collect();
Colin Sherratt7a666df2014-10-19 20:19:071959
1960 b.iter(|| {
1961 let mut sum = 0;
Jorge Apariciod5d7e652015-01-31 17:20:461962 for &i in &ring {
Colin Sherratt7a666df2014-10-19 20:19:071963 sum += i;
1964 }
Colin Sherratt5e549d82014-11-11 02:57:521965 test::black_box(sum);
Colin Sherratt7a666df2014-10-19 20:19:071966 })
1967 }
1968
1969 #[bench]
1970 fn bench_mut_iter_1000(b: &mut test::Bencher) {
Aaron Turon5fa9de12015-02-18 07:44:551971 let mut ring: VecDeque<_> = (0..1000).collect();
Colin Sherratt7a666df2014-10-19 20:19:071972
1973 b.iter(|| {
Colin Sherratt5e549d82014-11-11 02:57:521974 let mut sum = 0;
Jorge Apariciod5f61b42015-02-01 01:02:001975 for i in &mut ring {
Colin Sherratt5e549d82014-11-11 02:57:521976 sum += *i;
Colin Sherratt7a666df2014-10-19 20:19:071977 }
Colin Sherratt5e549d82014-11-11 02:57:521978 test::black_box(sum);
Colin Sherratt7a666df2014-10-19 20:19:071979 })
1980 }
1981
Jorge Aparicio788181d2015-01-28 13:34:181982 #[derive(Clone, PartialEq, Debug)]
Patrick Walton99b33f72013-07-02 19:47:321983 enum Taggy {
Tobias Bucher7f64fe42015-01-25 21:05:031984 One(i32),
1985 Two(i32, i32),
1986 Three(i32, i32, i32),
Brian Anderson6e27b272012-01-18 03:05:071987 }
1988
Jorge Aparicio788181d2015-01-28 13:34:181989 #[derive(Clone, PartialEq, Debug)]
Patrick Walton99b33f72013-07-02 19:47:321990 enum Taggypar<T> {
Niko Matsakis8dbdcdb2015-02-12 15:38:451991 Onepar(T),
1992 Twopar(T, T),
1993 Threepar(T, T, T),
Patrick Walton99b33f72013-07-02 19:47:321994 }
1995
Jorge Aparicio788181d2015-01-28 13:34:181996 #[derive(Clone, PartialEq, Debug)]
Erick Tryzelaare84576b2013-01-22 16:44:241997 struct RecCy {
Tobias Bucher7f64fe42015-01-25 21:05:031998 x: i32,
1999 y: i32,
Patrick Waltoneb4d39e2013-01-26 00:57:392000 t: Taggy
Patrick Walton9117dcb2012-09-20 01:00:262001 }
Kevin Cantuc43426e2012-09-13 05:09:552002
2003 #[test]
2004 fn test_param_int() {
Tobias Bucher7f64fe42015-01-25 21:05:032005 test_parameterized::<i32>(5, 72, 64, 175);
Kevin Cantuc43426e2012-09-13 05:09:552006 }
2007
2008 #[test]
Kevin Cantuc43426e2012-09-13 05:09:552009 fn test_param_taggy() {
Corey Richardsonf8ae9b02013-06-26 22:14:352010 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
Kevin Cantuc43426e2012-09-13 05:09:552011 }
2012
2013 #[test]
2014 fn test_param_taggypar() {
Tobias Bucher7f64fe42015-01-25 21:05:032015 test_parameterized::<Taggypar<i32>>(Onepar::<i32>(1),
2016 Twopar::<i32>(1, 2),
2017 Threepar::<i32>(1, 2, 3),
2018 Twopar::<i32>(17, 42));
Kevin Cantuc43426e2012-09-13 05:09:552019 }
Brian Anderson6e27b272012-01-18 03:05:072020
Kevin Cantuc43426e2012-09-13 05:09:552021 #[test]
2022 fn test_param_reccy() {
Erick Tryzelaare84576b2013-01-22 16:44:242023 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
2024 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
2025 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
2026 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
Kevin Cantuc43426e2012-09-13 05:09:552027 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
Brian Anderson6e27b272012-01-18 03:05:072028 }
Erick Tryzelaar909d8f02013-03-30 01:02:442029
2030 #[test]
blake2-ppc0ff5c172013-07-06 03:42:452031 fn test_with_capacity() {
Aaron Turon5fa9de12015-02-18 07:44:552032 let mut d = VecDeque::with_capacity(0);
Tobias Bucher7f64fe42015-01-25 21:05:032033 d.push_back(1);
blake2-ppc0ff5c172013-07-06 03:42:452034 assert_eq!(d.len(), 1);
Aaron Turon5fa9de12015-02-18 07:44:552035 let mut d = VecDeque::with_capacity(50);
Tobias Bucher7f64fe42015-01-25 21:05:032036 d.push_back(1);
blake2-ppc0ff5c172013-07-06 03:42:452037 assert_eq!(d.len(), 1);
2038 }
2039
2040 #[test]
Kevin Butler64896d62014-08-07 01:11:132041 fn test_with_capacity_non_power_two() {
Aaron Turon5fa9de12015-02-18 07:44:552042 let mut d3 = VecDeque::with_capacity(3);
Tobias Bucher7f64fe42015-01-25 21:05:032043 d3.push_back(1);
Kevin Butler64896d62014-08-07 01:11:132044
2045 // X = None, | = lo
2046 // [|1, X, X]
2047 assert_eq!(d3.pop_front(), Some(1));
2048 // [X, |X, X]
2049 assert_eq!(d3.front(), None);
2050
2051 // [X, |3, X]
Alexis Beingessnercf3b2e42014-11-06 17:24:472052 d3.push_back(3);
Kevin Butler64896d62014-08-07 01:11:132053 // [X, |3, 6]
Alexis Beingessnercf3b2e42014-11-06 17:24:472054 d3.push_back(6);
Kevin Butler64896d62014-08-07 01:11:132055 // [X, X, |6]
2056 assert_eq!(d3.pop_front(), Some(3));
2057
2058 // Pushing the lo past half way point to trigger
2059 // the 'B' scenario for growth
2060 // [9, X, |6]
Alexis Beingessnercf3b2e42014-11-06 17:24:472061 d3.push_back(9);
Kevin Butler64896d62014-08-07 01:11:132062 // [9, 12, |6]
Alexis Beingessnercf3b2e42014-11-06 17:24:472063 d3.push_back(12);
Kevin Butler64896d62014-08-07 01:11:132064
Alexis Beingessnercf3b2e42014-11-06 17:24:472065 d3.push_back(15);
Kevin Butler64896d62014-08-07 01:11:132066 // There used to be a bug here about how the
Aaron Turon5fa9de12015-02-18 07:44:552067 // VecDeque made growth assumptions about the
Kevin Butler64896d62014-08-07 01:11:132068 // underlying Vec which didn't hold and lead
2069 // to corruption.
2070 // (Vec grows to next power of two)
2071 //good- [9, 12, 15, X, X, X, X, |6]
2072 //bug- [15, 12, X, X, X, |6, X, X]
2073 assert_eq!(d3.pop_front(), Some(6));
2074
2075 // Which leads us to the following state which
2076 // would be a failure case.
2077 //bug- [15, 12, X, X, X, X, |X, X]
2078 assert_eq!(d3.front(), Some(&9));
2079 }
2080
2081 #[test]
David Manescu65f35782014-01-31 13:03:202082 fn test_reserve_exact() {
Aaron Turon5fa9de12015-02-18 07:44:552083 let mut d = VecDeque::new();
Alexise250fe32015-02-05 02:17:192084 d.push_back(0);
David Manescu65f35782014-01-31 13:03:202085 d.reserve_exact(50);
Alexis Beingessnercf3b2e42014-11-06 17:24:472086 assert!(d.capacity() >= 51);
Tim Chevalier77de84b2013-05-27 18:47:382087 }
2088
2089 #[test]
David Manescu65f35782014-01-31 13:03:202090 fn test_reserve() {
Aaron Turon5fa9de12015-02-18 07:44:552091 let mut d = VecDeque::new();
Alexise250fe32015-02-05 02:17:192092 d.push_back(0);
David Manescu65f35782014-01-31 13:03:202093 d.reserve(50);
Colin Sherratt7a666df2014-10-19 20:19:072094 assert!(d.capacity() >= 51);
Tim Chevalier77de84b2013-05-27 18:47:382095 }
2096
Jed Estep096fb792013-06-26 14:04:442097 #[test]
blake2-ppc57757a82013-09-26 07:19:262098 fn test_swap() {
Aaron Turon5fa9de12015-02-18 07:44:552099 let mut d: VecDeque<_> = (0..5).collect();
blake2-ppc57757a82013-09-26 07:19:262100 d.pop_front();
2101 d.swap(0, 3);
Vadim Petrochenkov2807a1c2015-02-24 18:15:452102 assert_eq!(d.iter().cloned().collect::<Vec<_>>(), [4, 2, 3, 1]);
blake2-ppc57757a82013-09-26 07:19:262103 }
2104
2105 #[test]
Jed Estep096fb792013-06-26 14:04:442106 fn test_iter() {
Aaron Turon5fa9de12015-02-18 07:44:552107 let mut d = VecDeque::new();
blake2-ppcf88d5322013-07-06 03:42:452108 assert_eq!(d.iter().next(), None);
blake2-ppc9ccf4432013-07-14 20:30:222109 assert_eq!(d.iter().size_hint(), (0, Some(0)));
blake2-ppcf88d5322013-07-06 03:42:452110
Tobias Bucher7f64fe42015-01-25 21:05:032111 for i in 0..5 {
Alexis Beingessnercf3b2e42014-11-06 17:24:472112 d.push_back(i);
Jed Estep096fb792013-06-26 14:04:442113 }
Nick Cameron37a94b82014-08-04 12:19:022114 {
2115 let b: &[_] = &[&0,&1,&2,&3,&4];
Alexise250fe32015-02-05 02:17:192116 assert_eq!(d.iter().collect::<Vec<_>>(), b);
Nick Cameron37a94b82014-08-04 12:19:022117 }
Corey Richardsonf8ae9b02013-06-26 22:14:352118
Tobias Bucher7f64fe42015-01-25 21:05:032119 for i in 6..9 {
blake2-ppc70523712013-07-10 13:27:142120 d.push_front(i);
Jed Estep096fb792013-06-26 14:04:442121 }
Nick Cameron37a94b82014-08-04 12:19:022122 {
2123 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
Alexise250fe32015-02-05 02:17:192124 assert_eq!(d.iter().collect::<Vec<_>>(), b);
Nick Cameron37a94b82014-08-04 12:19:022125 }
blake2-ppc9ccf4432013-07-14 20:30:222126
2127 let mut it = d.iter();
2128 let mut len = d.len();
2129 loop {
2130 match it.next() {
2131 None => break,
2132 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
2133 }
2134 }
Jed Estep096fb792013-06-26 14:04:442135 }
2136
2137 #[test]
2138 fn test_rev_iter() {
Aaron Turon5fa9de12015-02-18 07:44:552139 let mut d = VecDeque::new();
Jonathan S03609e52014-04-21 04:59:122140 assert_eq!(d.iter().rev().next(), None);
blake2-ppcf88d5322013-07-06 03:42:452141
Tobias Bucher7f64fe42015-01-25 21:05:032142 for i in 0..5 {
Alexis Beingessnercf3b2e42014-11-06 17:24:472143 d.push_back(i);
Jed Estep096fb792013-06-26 14:04:442144 }
Nick Cameron37a94b82014-08-04 12:19:022145 {
2146 let b: &[_] = &[&4,&3,&2,&1,&0];
Alexise250fe32015-02-05 02:17:192147 assert_eq!(d.iter().rev().collect::<Vec<_>>(), b);
Nick Cameron37a94b82014-08-04 12:19:022148 }
Corey Richardsonf8ae9b02013-06-26 22:14:352149
Tobias Bucher7f64fe42015-01-25 21:05:032150 for i in 6..9 {
blake2-ppc70523712013-07-10 13:27:142151 d.push_front(i);
Jed Estep096fb792013-06-26 14:04:442152 }
Nick Cameron37a94b82014-08-04 12:19:022153 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
Alexise250fe32015-02-05 02:17:192154 assert_eq!(d.iter().rev().collect::<Vec<_>>(), b);
Jed Estep096fb792013-06-26 14:04:442155 }
blake2-ppc08dc72f2013-07-06 03:42:452156
2157 #[test]
Niko Matsakisbc4164d2013-11-16 22:29:392158 fn test_mut_rev_iter_wrap() {
Aaron Turon5fa9de12015-02-18 07:44:552159 let mut d = VecDeque::with_capacity(3);
Aaron Turonfc525ee2014-09-15 03:27:362160 assert!(d.iter_mut().rev().next().is_none());
Niko Matsakisbc4164d2013-11-16 22:29:392161
Tobias Bucher7f64fe42015-01-25 21:05:032162 d.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:472163 d.push_back(2);
2164 d.push_back(3);
Niko Matsakisbc4164d2013-11-16 22:29:392165 assert_eq!(d.pop_front(), Some(1));
Alexis Beingessnercf3b2e42014-11-06 17:24:472166 d.push_back(4);
Niko Matsakisbc4164d2013-11-16 22:29:392167
Alexise250fe32015-02-05 02:17:192168 assert_eq!(d.iter_mut().rev().cloned().collect::<Vec<_>>(),
2169 vec![4, 3, 2]);
Niko Matsakisbc4164d2013-11-16 22:29:392170 }
2171
2172 #[test]
blake2-ppcf88d5322013-07-06 03:42:452173 fn test_mut_iter() {
Aaron Turon5fa9de12015-02-18 07:44:552174 let mut d = VecDeque::new();
Aaron Turonfc525ee2014-09-15 03:27:362175 assert!(d.iter_mut().next().is_none());
blake2-ppcf88d5322013-07-06 03:42:452176
Alexise250fe32015-02-05 02:17:192177 for i in 0..3 {
blake2-ppc70523712013-07-10 13:27:142178 d.push_front(i);
blake2-ppcf88d5322013-07-06 03:42:452179 }
2180
Aaron Turonfc525ee2014-09-15 03:27:362181 for (i, elt) in d.iter_mut().enumerate() {
blake2-ppcf88d5322013-07-06 03:42:452182 assert_eq!(*elt, 2 - i);
2183 *elt = i;
2184 }
2185
2186 {
Aaron Turonfc525ee2014-09-15 03:27:362187 let mut it = d.iter_mut();
blake2-ppcf88d5322013-07-06 03:42:452188 assert_eq!(*it.next().unwrap(), 0);
2189 assert_eq!(*it.next().unwrap(), 1);
2190 assert_eq!(*it.next().unwrap(), 2);
2191 assert!(it.next().is_none());
2192 }
2193 }
2194
2195 #[test]
2196 fn test_mut_rev_iter() {
Aaron Turon5fa9de12015-02-18 07:44:552197 let mut d = VecDeque::new();
Aaron Turonfc525ee2014-09-15 03:27:362198 assert!(d.iter_mut().rev().next().is_none());
blake2-ppcf88d5322013-07-06 03:42:452199
Alexise250fe32015-02-05 02:17:192200 for i in 0..3 {
blake2-ppc70523712013-07-10 13:27:142201 d.push_front(i);
blake2-ppcf88d5322013-07-06 03:42:452202 }
2203
Aaron Turonfc525ee2014-09-15 03:27:362204 for (i, elt) in d.iter_mut().rev().enumerate() {
blake2-ppcf88d5322013-07-06 03:42:452205 assert_eq!(*elt, i);
2206 *elt = i;
2207 }
2208
2209 {
Aaron Turonfc525ee2014-09-15 03:27:362210 let mut it = d.iter_mut().rev();
blake2-ppcf88d5322013-07-06 03:42:452211 assert_eq!(*it.next().unwrap(), 0);
2212 assert_eq!(*it.next().unwrap(), 1);
2213 assert_eq!(*it.next().unwrap(), 2);
2214 assert!(it.next().is_none());
2215 }
2216 }
2217
2218 #[test]
Alexis Beingessner865c2db2014-11-23 02:34:112219 fn test_into_iter() {
2220
2221 // Empty iter
2222 {
Aaron Turon5fa9de12015-02-18 07:44:552223 let d: VecDeque<i32> = VecDeque::new();
Alexis Beingessner865c2db2014-11-23 02:34:112224 let mut iter = d.into_iter();
2225
2226 assert_eq!(iter.size_hint(), (0, Some(0)));
2227 assert_eq!(iter.next(), None);
2228 assert_eq!(iter.size_hint(), (0, Some(0)));
2229 }
2230
2231 // simple iter
2232 {
Aaron Turon5fa9de12015-02-18 07:44:552233 let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032234 for i in 0..5 {
Alexis Beingessner865c2db2014-11-23 02:34:112235 d.push_back(i);
2236 }
2237
2238 let b = vec![0,1,2,3,4];
Alexise250fe32015-02-05 02:17:192239 assert_eq!(d.into_iter().collect::<Vec<_>>(), b);
Alexis Beingessner865c2db2014-11-23 02:34:112240 }
2241
2242 // wrapped iter
2243 {
Aaron Turon5fa9de12015-02-18 07:44:552244 let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032245 for i in 0..5 {
Alexis Beingessner865c2db2014-11-23 02:34:112246 d.push_back(i);
2247 }
Tobias Bucher7f64fe42015-01-25 21:05:032248 for i in 6..9 {
Alexis Beingessner865c2db2014-11-23 02:34:112249 d.push_front(i);
2250 }
2251
2252 let b = vec![8,7,6,0,1,2,3,4];
Alexise250fe32015-02-05 02:17:192253 assert_eq!(d.into_iter().collect::<Vec<_>>(), b);
Alexis Beingessner865c2db2014-11-23 02:34:112254 }
2255
2256 // partially used
2257 {
Aaron Turon5fa9de12015-02-18 07:44:552258 let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032259 for i in 0..5 {
Alexis Beingessner865c2db2014-11-23 02:34:112260 d.push_back(i);
2261 }
Tobias Bucher7f64fe42015-01-25 21:05:032262 for i in 6..9 {
Alexis Beingessner865c2db2014-11-23 02:34:112263 d.push_front(i);
2264 }
2265
2266 let mut it = d.into_iter();
2267 assert_eq!(it.size_hint(), (8, Some(8)));
2268 assert_eq!(it.next(), Some(8));
2269 assert_eq!(it.size_hint(), (7, Some(7)));
2270 assert_eq!(it.next_back(), Some(4));
2271 assert_eq!(it.size_hint(), (6, Some(6)));
2272 assert_eq!(it.next(), Some(7));
2273 assert_eq!(it.size_hint(), (5, Some(5)));
2274 }
2275 }
2276
2277 #[test]
Clark Gaebeld57f2592014-12-16 22:45:032278 fn test_drain() {
2279
2280 // Empty iter
2281 {
Aaron Turon5fa9de12015-02-18 07:44:552282 let mut d: VecDeque<i32> = VecDeque::new();
Clark Gaebeld57f2592014-12-16 22:45:032283
2284 {
2285 let mut iter = d.drain();
2286
2287 assert_eq!(iter.size_hint(), (0, Some(0)));
2288 assert_eq!(iter.next(), None);
2289 assert_eq!(iter.size_hint(), (0, Some(0)));
2290 }
2291
2292 assert!(d.is_empty());
2293 }
2294
2295 // simple iter
2296 {
Aaron Turon5fa9de12015-02-18 07:44:552297 let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032298 for i in 0..5 {
Clark Gaebeld57f2592014-12-16 22:45:032299 d.push_back(i);
2300 }
2301
Alex Crichton3a2530d2015-01-30 20:26:442302 assert_eq!(d.drain().collect::<Vec<_>>(), [0, 1, 2, 3, 4]);
Clark Gaebeld57f2592014-12-16 22:45:032303 assert!(d.is_empty());
2304 }
2305
2306 // wrapped iter
2307 {
Aaron Turon5fa9de12015-02-18 07:44:552308 let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032309 for i in 0..5 {
Clark Gaebeld57f2592014-12-16 22:45:032310 d.push_back(i);
2311 }
Alex Crichton3a2530d2015-01-30 20:26:442312 for i in 6..9 {
Clark Gaebeld57f2592014-12-16 22:45:032313 d.push_front(i);
2314 }
2315
Alex Crichton3a2530d2015-01-30 20:26:442316 assert_eq!(d.drain().collect::<Vec<_>>(), [8,7,6,0,1,2,3,4]);
Clark Gaebeld57f2592014-12-16 22:45:032317 assert!(d.is_empty());
2318 }
2319
2320 // partially used
2321 {
Aaron Turon5fa9de12015-02-18 07:44:552322 let mut d: VecDeque<_> = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032323 for i in 0..5 {
Clark Gaebeld57f2592014-12-16 22:45:032324 d.push_back(i);
2325 }
Alex Crichton3a2530d2015-01-30 20:26:442326 for i in 6..9 {
Clark Gaebeld57f2592014-12-16 22:45:032327 d.push_front(i);
2328 }
2329
2330 {
2331 let mut it = d.drain();
2332 assert_eq!(it.size_hint(), (8, Some(8)));
2333 assert_eq!(it.next(), Some(8));
2334 assert_eq!(it.size_hint(), (7, Some(7)));
2335 assert_eq!(it.next_back(), Some(4));
2336 assert_eq!(it.size_hint(), (6, Some(6)));
2337 assert_eq!(it.next(), Some(7));
2338 assert_eq!(it.size_hint(), (5, Some(5)));
2339 }
2340 assert!(d.is_empty());
2341 }
2342 }
2343
2344 #[test]
Brian Andersonee052192014-03-31 04:45:552345 fn test_from_iter() {
Eduard Burtescub45d30d2014-12-19 12:02:222346 use core::iter;
Tobias Bucher7f64fe42015-01-25 21:05:032347 let v = vec!(1,2,3,4,5,6,7);
Aaron Turon5fa9de12015-02-18 07:44:552348 let deq: VecDeque<_> = v.iter().cloned().collect();
Alexise250fe32015-02-05 02:17:192349 let u: Vec<_> = deq.iter().cloned().collect();
blake2-ppc08dc72f2013-07-06 03:42:452350 assert_eq!(u, v);
2351
Alexise250fe32015-02-05 02:17:192352 let seq = iter::count(0, 2).take(256);
Aaron Turon5fa9de12015-02-18 07:44:552353 let deq: VecDeque<_> = seq.collect();
Daniel Micay100894552013-08-03 16:45:232354 for (i, &x) in deq.iter().enumerate() {
blake2-ppc08dc72f2013-07-06 03:42:452355 assert_eq!(2*i, x);
2356 }
2357 assert_eq!(deq.len(), 256);
2358 }
blake2-ppc10c76982013-07-06 13:27:322359
2360 #[test]
2361 fn test_clone() {
Aaron Turon5fa9de12015-02-18 07:44:552362 let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032363 d.push_front(17);
blake2-ppc70523712013-07-10 13:27:142364 d.push_front(42);
Alexis Beingessnercf3b2e42014-11-06 17:24:472365 d.push_back(137);
2366 d.push_back(137);
Alexise250fe32015-02-05 02:17:192367 assert_eq!(d.len(), 4);
blake2-ppc10c76982013-07-06 13:27:322368 let mut e = d.clone();
Alexise250fe32015-02-05 02:17:192369 assert_eq!(e.len(), 4);
blake2-ppc10c76982013-07-06 13:27:322370 while !d.is_empty() {
Alexis Beingessnercf3b2e42014-11-06 17:24:472371 assert_eq!(d.pop_back(), e.pop_back());
blake2-ppc10c76982013-07-06 13:27:322372 }
Alexise250fe32015-02-05 02:17:192373 assert_eq!(d.len(), 0);
2374 assert_eq!(e.len(), 0);
blake2-ppc10c76982013-07-06 13:27:322375 }
2376
2377 #[test]
2378 fn test_eq() {
Aaron Turon5fa9de12015-02-18 07:44:552379 let mut d = VecDeque::new();
2380 assert!(d == VecDeque::with_capacity(0));
Tobias Bucher7f64fe42015-01-25 21:05:032381 d.push_front(137);
blake2-ppc70523712013-07-10 13:27:142382 d.push_front(17);
2383 d.push_front(42);
Alexis Beingessnercf3b2e42014-11-06 17:24:472384 d.push_back(137);
Aaron Turon5fa9de12015-02-18 07:44:552385 let mut e = VecDeque::with_capacity(0);
Alexis Beingessnercf3b2e42014-11-06 17:24:472386 e.push_back(42);
2387 e.push_back(17);
2388 e.push_back(137);
2389 e.push_back(137);
Alex Crichton02882fb2014-02-28 09:23:062390 assert!(&e == &d);
Alexis Beingessnercf3b2e42014-11-06 17:24:472391 e.pop_back();
2392 e.push_back(0);
blake2-ppc10c76982013-07-06 13:27:322393 assert!(e != d);
2394 e.clear();
Aaron Turon5fa9de12015-02-18 07:44:552395 assert!(e == VecDeque::new());
blake2-ppc10c76982013-07-06 13:27:322396 }
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:042397
2398 #[test]
nham1cfa6562014-07-27 02:33:472399 fn test_hash() {
Aaron Turon5fa9de12015-02-18 07:44:552400 let mut x = VecDeque::new();
2401 let mut y = VecDeque::new();
nham1cfa6562014-07-27 02:33:472402
Tobias Bucher7f64fe42015-01-25 21:05:032403 x.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:472404 x.push_back(2);
2405 x.push_back(3);
nham1cfa6562014-07-27 02:33:472406
Tobias Bucher7f64fe42015-01-25 21:05:032407 y.push_back(0);
2408 y.push_back(1);
nham1cfa6562014-07-27 02:33:472409 y.pop_front();
Alexis Beingessnercf3b2e42014-11-06 17:24:472410 y.push_back(2);
2411 y.push_back(3);
nham1cfa6562014-07-27 02:33:472412
Alex Crichton511f0b82014-12-09 20:37:232413 assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
nham1cfa6562014-07-27 02:33:472414 }
2415
2416 #[test]
nham63615772014-07-27 03:18:562417 fn test_ord() {
Aaron Turon5fa9de12015-02-18 07:44:552418 let x = VecDeque::new();
2419 let mut y = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032420 y.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:472421 y.push_back(2);
2422 y.push_back(3);
nham63615772014-07-27 03:18:562423 assert!(x < y);
2424 assert!(y > x);
2425 assert!(x <= x);
2426 assert!(x >= x);
2427 }
2428
2429 #[test]
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:042430 fn test_show() {
Aaron Turon5fa9de12015-02-18 07:44:552431 let ringbuf: VecDeque<_> = (0..10).collect();
Tobias Bucher408f7b52015-02-10 21:12:132432 assert_eq!(format!("{:?}", ringbuf), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:042433
Aaron Turon5fa9de12015-02-18 07:44:552434 let ringbuf: VecDeque<_> = vec!["just", "one", "test", "more"].iter()
Alexise250fe32015-02-05 02:17:192435 .cloned()
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:042436 .collect();
Tobias Bucher408f7b52015-02-10 21:12:132437 assert_eq!(format!("{:?}", ringbuf), "[\"just\", \"one\", \"test\", \"more\"]");
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:042438 }
Colin Sherratt7a666df2014-10-19 20:19:072439
2440 #[test]
2441 fn test_drop() {
Alexise250fe32015-02-05 02:17:192442 static mut drops: i32 = 0;
Colin Sherratt7a666df2014-10-19 20:19:072443 struct Elem;
2444 impl Drop for Elem {
2445 fn drop(&mut self) {
2446 unsafe { drops += 1; }
2447 }
2448 }
2449
Aaron Turon5fa9de12015-02-18 07:44:552450 let mut ring = VecDeque::new();
Colin Sherratt7a666df2014-10-19 20:19:072451 ring.push_back(Elem);
2452 ring.push_front(Elem);
2453 ring.push_back(Elem);
2454 ring.push_front(Elem);
2455 drop(ring);
2456
2457 assert_eq!(unsafe {drops}, 4);
2458 }
2459
2460 #[test]
2461 fn test_drop_with_pop() {
Alexise250fe32015-02-05 02:17:192462 static mut drops: i32 = 0;
Colin Sherratt7a666df2014-10-19 20:19:072463 struct Elem;
2464 impl Drop for Elem {
2465 fn drop(&mut self) {
2466 unsafe { drops += 1; }
2467 }
2468 }
2469
Aaron Turon5fa9de12015-02-18 07:44:552470 let mut ring = VecDeque::new();
Colin Sherratt7a666df2014-10-19 20:19:072471 ring.push_back(Elem);
2472 ring.push_front(Elem);
2473 ring.push_back(Elem);
2474 ring.push_front(Elem);
2475
2476 drop(ring.pop_back());
2477 drop(ring.pop_front());
2478 assert_eq!(unsafe {drops}, 2);
2479
2480 drop(ring);
2481 assert_eq!(unsafe {drops}, 4);
2482 }
2483
2484 #[test]
2485 fn test_drop_clear() {
Alexise250fe32015-02-05 02:17:192486 static mut drops: i32 = 0;
Colin Sherratt7a666df2014-10-19 20:19:072487 struct Elem;
2488 impl Drop for Elem {
2489 fn drop(&mut self) {
2490 unsafe { drops += 1; }
2491 }
2492 }
2493
Aaron Turon5fa9de12015-02-18 07:44:552494 let mut ring = VecDeque::new();
Colin Sherratt7a666df2014-10-19 20:19:072495 ring.push_back(Elem);
2496 ring.push_front(Elem);
2497 ring.push_back(Elem);
2498 ring.push_front(Elem);
2499 ring.clear();
2500 assert_eq!(unsafe {drops}, 4);
2501
2502 drop(ring);
2503 assert_eq!(unsafe {drops}, 4);
2504 }
2505
2506 #[test]
2507 fn test_reserve_grow() {
2508 // test growth path A
2509 // [T o o H] -> [T o o H . . . . ]
Aaron Turon5fa9de12015-02-18 07:44:552510 let mut ring = VecDeque::with_capacity(4);
Tobias Bucher7f64fe42015-01-25 21:05:032511 for i in 0..3 {
Colin Sherratt7a666df2014-10-19 20:19:072512 ring.push_back(i);
2513 }
2514 ring.reserve(7);
Tobias Bucher7f64fe42015-01-25 21:05:032515 for i in 0..3 {
Colin Sherratt7a666df2014-10-19 20:19:072516 assert_eq!(ring.pop_front(), Some(i));
2517 }
2518
2519 // test growth path B
2520 // [H T o o] -> [. T o o H . . . ]
Aaron Turon5fa9de12015-02-18 07:44:552521 let mut ring = VecDeque::with_capacity(4);
Tobias Bucher7f64fe42015-01-25 21:05:032522 for i in 0..1 {
Colin Sherratt7a666df2014-10-19 20:19:072523 ring.push_back(i);
2524 assert_eq!(ring.pop_front(), Some(i));
2525 }
Tobias Bucher7f64fe42015-01-25 21:05:032526 for i in 0..3 {
Colin Sherratt7a666df2014-10-19 20:19:072527 ring.push_back(i);
2528 }
2529 ring.reserve(7);
Tobias Bucher7f64fe42015-01-25 21:05:032530 for i in 0..3 {
Colin Sherratt7a666df2014-10-19 20:19:072531 assert_eq!(ring.pop_front(), Some(i));
2532 }
2533
2534 // test growth path C
2535 // [o o H T] -> [o o H . . . . T ]
Aaron Turon5fa9de12015-02-18 07:44:552536 let mut ring = VecDeque::with_capacity(4);
Tobias Bucher7f64fe42015-01-25 21:05:032537 for i in 0..3 {
Colin Sherratt7a666df2014-10-19 20:19:072538 ring.push_back(i);
2539 assert_eq!(ring.pop_front(), Some(i));
2540 }
Tobias Bucher7f64fe42015-01-25 21:05:032541 for i in 0..3 {
Colin Sherratt7a666df2014-10-19 20:19:072542 ring.push_back(i);
2543 }
2544 ring.reserve(7);
Tobias Bucher7f64fe42015-01-25 21:05:032545 for i in 0..3 {
Colin Sherratt7a666df2014-10-19 20:19:072546 assert_eq!(ring.pop_front(), Some(i));
2547 }
2548 }
2549
2550 #[test]
2551 fn test_get() {
Aaron Turon5fa9de12015-02-18 07:44:552552 let mut ring = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032553 ring.push_back(0);
Colin Sherratt7a666df2014-10-19 20:19:072554 assert_eq!(ring.get(0), Some(&0));
2555 assert_eq!(ring.get(1), None);
2556
2557 ring.push_back(1);
2558 assert_eq!(ring.get(0), Some(&0));
2559 assert_eq!(ring.get(1), Some(&1));
2560 assert_eq!(ring.get(2), None);
2561
2562 ring.push_back(2);
2563 assert_eq!(ring.get(0), Some(&0));
2564 assert_eq!(ring.get(1), Some(&1));
2565 assert_eq!(ring.get(2), Some(&2));
2566 assert_eq!(ring.get(3), None);
2567
2568 assert_eq!(ring.pop_front(), Some(0));
2569 assert_eq!(ring.get(0), Some(&1));
2570 assert_eq!(ring.get(1), Some(&2));
2571 assert_eq!(ring.get(2), None);
2572
2573 assert_eq!(ring.pop_front(), Some(1));
2574 assert_eq!(ring.get(0), Some(&2));
2575 assert_eq!(ring.get(1), None);
2576
2577 assert_eq!(ring.pop_front(), Some(2));
2578 assert_eq!(ring.get(0), None);
2579 assert_eq!(ring.get(1), None);
2580 }
2581
2582 #[test]
2583 fn test_get_mut() {
Aaron Turon5fa9de12015-02-18 07:44:552584 let mut ring = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032585 for i in 0..3 {
Colin Sherratt7a666df2014-10-19 20:19:072586 ring.push_back(i);
2587 }
2588
2589 match ring.get_mut(1) {
2590 Some(x) => *x = -1,
2591 None => ()
2592 };
2593
2594 assert_eq!(ring.get_mut(0), Some(&mut 0));
2595 assert_eq!(ring.get_mut(1), Some(&mut -1));
2596 assert_eq!(ring.get_mut(2), Some(&mut 2));
2597 assert_eq!(ring.get_mut(3), None);
2598
2599 assert_eq!(ring.pop_front(), Some(0));
2600 assert_eq!(ring.get_mut(0), Some(&mut -1));
2601 assert_eq!(ring.get_mut(1), Some(&mut 2));
2602 assert_eq!(ring.get_mut(2), None);
2603 }
Matt Murphy40f28c72014-12-03 17:12:302604
2605 #[test]
Piotr Czarnecki156a1c32015-01-05 14:48:582606 fn test_swap_front_back_remove() {
2607 fn test(back: bool) {
2608 // This test checks that every single combination of tail position and length is tested.
2609 // Capacity 15 should be large enough to cover every case.
Aaron Turon5fa9de12015-02-18 07:44:552610 let mut tester = VecDeque::with_capacity(15);
Piotr Czarnecki156a1c32015-01-05 14:48:582611 let usable_cap = tester.capacity();
2612 let final_len = usable_cap / 2;
2613
Jorge Aparicio7d661af2015-01-26 20:46:122614 for len in 0..final_len {
Piotr Czarnecki156a1c32015-01-05 14:48:582615 let expected = if back {
Jorge Aparicioc300d682015-01-26 20:44:222616 (0..len).collect()
Piotr Czarnecki156a1c32015-01-05 14:48:582617 } else {
Jorge Aparicioc300d682015-01-26 20:44:222618 (0..len).rev().collect()
Piotr Czarnecki156a1c32015-01-05 14:48:582619 };
Jorge Aparicio7d661af2015-01-26 20:46:122620 for tail_pos in 0..usable_cap {
Piotr Czarnecki156a1c32015-01-05 14:48:582621 tester.tail = tail_pos;
2622 tester.head = tail_pos;
2623 if back {
Jorge Aparicio7d661af2015-01-26 20:46:122624 for i in 0..len * 2 {
Piotr Czarnecki156a1c32015-01-05 14:48:582625 tester.push_front(i);
2626 }
Jorge Aparicio7d661af2015-01-26 20:46:122627 for i in 0..len {
Piotr Czarnecki156a1c32015-01-05 14:48:582628 assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
2629 }
2630 } else {
Jorge Aparicio7d661af2015-01-26 20:46:122631 for i in 0..len * 2 {
Piotr Czarnecki156a1c32015-01-05 14:48:582632 tester.push_back(i);
2633 }
Jorge Aparicio7d661af2015-01-26 20:46:122634 for i in 0..len {
Piotr Czarnecki156a1c32015-01-05 14:48:582635 let idx = tester.len() - 1 - i;
2636 assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
2637 }
2638 }
2639 assert!(tester.tail < tester.cap);
2640 assert!(tester.head < tester.cap);
2641 assert_eq!(tester, expected);
2642 }
2643 }
2644 }
2645 test(true);
2646 test(false);
2647 }
2648
2649 #[test]
Matt Murphy40f28c72014-12-03 17:12:302650 fn test_insert() {
2651 // This test checks that every single combination of tail position, length, and
Piotr Czarnecki59d41532014-12-16 23:37:552652 // insertion position is tested. Capacity 15 should be large enough to cover every case.
Matt Murphy40f28c72014-12-03 17:12:302653
Aaron Turon5fa9de12015-02-18 07:44:552654 let mut tester = VecDeque::with_capacity(15);
Piotr Czarnecki59d41532014-12-16 23:37:552655 // can't guarantee we got 15, so have to get what we got.
2656 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
Matt Murphy40f28c72014-12-03 17:12:302657 // this test isn't covering what it wants to
2658 let cap = tester.capacity();
2659
2660
2661 // len is the length *after* insertion
Jorge Aparicio7d661af2015-01-26 20:46:122662 for len in 1..cap {
Matt Murphy40f28c72014-12-03 17:12:302663 // 0, 1, 2, .., len - 1
2664 let expected = iter::count(0, 1).take(len).collect();
Jorge Aparicio7d661af2015-01-26 20:46:122665 for tail_pos in 0..cap {
2666 for to_insert in 0..len {
Matt Murphy40f28c72014-12-03 17:12:302667 tester.tail = tail_pos;
2668 tester.head = tail_pos;
Jorge Aparicio7d661af2015-01-26 20:46:122669 for i in 0..len {
Matt Murphy40f28c72014-12-03 17:12:302670 if i != to_insert {
2671 tester.push_back(i);
2672 }
2673 }
2674 tester.insert(to_insert, to_insert);
Piotr Czarnecki59d41532014-12-16 23:37:552675 assert!(tester.tail < tester.cap);
2676 assert!(tester.head < tester.cap);
2677 assert_eq!(tester, expected);
2678 }
2679 }
2680 }
2681 }
2682
2683 #[test]
2684 fn test_remove() {
2685 // This test checks that every single combination of tail position, length, and
2686 // removal position is tested. Capacity 15 should be large enough to cover every case.
2687
Aaron Turon5fa9de12015-02-18 07:44:552688 let mut tester = VecDeque::with_capacity(15);
Piotr Czarnecki59d41532014-12-16 23:37:552689 // can't guarantee we got 15, so have to get what we got.
2690 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2691 // this test isn't covering what it wants to
2692 let cap = tester.capacity();
2693
2694 // len is the length *after* removal
Jorge Aparicio7d661af2015-01-26 20:46:122695 for len in 0..cap - 1 {
Piotr Czarnecki59d41532014-12-16 23:37:552696 // 0, 1, 2, .., len - 1
2697 let expected = iter::count(0, 1).take(len).collect();
Jorge Aparicio7d661af2015-01-26 20:46:122698 for tail_pos in 0..cap {
2699 for to_remove in 0..len + 1 {
Piotr Czarnecki59d41532014-12-16 23:37:552700 tester.tail = tail_pos;
2701 tester.head = tail_pos;
Jorge Aparicio7d661af2015-01-26 20:46:122702 for i in 0..len {
Piotr Czarnecki59d41532014-12-16 23:37:552703 if i == to_remove {
2704 tester.push_back(1234);
2705 }
2706 tester.push_back(i);
2707 }
2708 if to_remove == len {
2709 tester.push_back(1234);
2710 }
2711 tester.remove(to_remove);
2712 assert!(tester.tail < tester.cap);
2713 assert!(tester.head < tester.cap);
Matt Murphy40f28c72014-12-03 17:12:302714 assert_eq!(tester, expected);
2715 }
2716 }
2717 }
2718 }
2719
2720 #[test]
Piotr Czarnecki156a1c32015-01-05 14:48:582721 fn test_shrink_to_fit() {
2722 // This test checks that every single combination of head and tail position,
2723 // is tested. Capacity 15 should be large enough to cover every case.
2724
Aaron Turon5fa9de12015-02-18 07:44:552725 let mut tester = VecDeque::with_capacity(15);
Piotr Czarnecki156a1c32015-01-05 14:48:582726 // can't guarantee we got 15, so have to get what we got.
2727 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2728 // this test isn't covering what it wants to
2729 let cap = tester.capacity();
2730 tester.reserve(63);
2731 let max_cap = tester.capacity();
2732
Jorge Aparicio7d661af2015-01-26 20:46:122733 for len in 0..cap + 1 {
Piotr Czarnecki156a1c32015-01-05 14:48:582734 // 0, 1, 2, .., len - 1
2735 let expected = iter::count(0, 1).take(len).collect();
Jorge Aparicio7d661af2015-01-26 20:46:122736 for tail_pos in 0..max_cap + 1 {
Piotr Czarnecki156a1c32015-01-05 14:48:582737 tester.tail = tail_pos;
2738 tester.head = tail_pos;
2739 tester.reserve(63);
Jorge Aparicio7d661af2015-01-26 20:46:122740 for i in 0..len {
Piotr Czarnecki156a1c32015-01-05 14:48:582741 tester.push_back(i);
2742 }
2743 tester.shrink_to_fit();
2744 assert!(tester.capacity() <= cap);
2745 assert!(tester.tail < tester.cap);
2746 assert!(tester.head < tester.cap);
2747 assert_eq!(tester, expected);
2748 }
2749 }
2750 }
2751
2752 #[test]
Matt Murphy40f28c72014-12-03 17:12:302753 fn test_front() {
Aaron Turon5fa9de12015-02-18 07:44:552754 let mut ring = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:032755 ring.push_back(10);
2756 ring.push_back(20);
Matt Murphy40f28c72014-12-03 17:12:302757 assert_eq!(ring.front(), Some(&10));
2758 ring.pop_front();
2759 assert_eq!(ring.front(), Some(&20));
2760 ring.pop_front();
2761 assert_eq!(ring.front(), None);
2762 }
Clark Gaebel525f65e2014-12-16 04:01:582763
2764 #[test]
2765 fn test_as_slices() {
Aaron Turon5fa9de12015-02-18 07:44:552766 let mut ring: VecDeque<i32> = VecDeque::with_capacity(127);
Alex Crichton3a2530d2015-01-30 20:26:442767 let cap = ring.capacity() as i32;
Clark Gaebel525f65e2014-12-16 04:01:582768 let first = cap/2;
2769 let last = cap - first;
Jorge Aparicio7d661af2015-01-26 20:46:122770 for i in 0..first {
Clark Gaebel525f65e2014-12-16 04:01:582771 ring.push_back(i);
2772
2773 let (left, right) = ring.as_slices();
Jorge Aparicioc300d682015-01-26 20:44:222774 let expected: Vec<_> = (0..i+1).collect();
Clark Gaebel525f65e2014-12-16 04:01:582775 assert_eq!(left, expected);
2776 assert_eq!(right, []);
2777 }
2778
Jorge Aparicio7d661af2015-01-26 20:46:122779 for j in -last..0 {
Clark Gaebel525f65e2014-12-16 04:01:582780 ring.push_front(j);
2781 let (left, right) = ring.as_slices();
Jorge Aparicioc300d682015-01-26 20:44:222782 let expected_left: Vec<_> = (-last..j+1).rev().collect();
2783 let expected_right: Vec<_> = (0..first).collect();
Clark Gaebel525f65e2014-12-16 04:01:582784 assert_eq!(left, expected_left);
2785 assert_eq!(right, expected_right);
2786 }
2787
Alex Crichton3a2530d2015-01-30 20:26:442788 assert_eq!(ring.len() as i32, cap);
2789 assert_eq!(ring.capacity() as i32, cap);
Clark Gaebel525f65e2014-12-16 04:01:582790 }
2791
2792 #[test]
2793 fn test_as_mut_slices() {
Aaron Turon5fa9de12015-02-18 07:44:552794 let mut ring: VecDeque<i32> = VecDeque::with_capacity(127);
Alex Crichton3a2530d2015-01-30 20:26:442795 let cap = ring.capacity() as i32;
Clark Gaebel525f65e2014-12-16 04:01:582796 let first = cap/2;
2797 let last = cap - first;
Jorge Aparicio7d661af2015-01-26 20:46:122798 for i in 0..first {
Clark Gaebel525f65e2014-12-16 04:01:582799 ring.push_back(i);
2800
2801 let (left, right) = ring.as_mut_slices();
Jorge Aparicioc300d682015-01-26 20:44:222802 let expected: Vec<_> = (0..i+1).collect();
Clark Gaebel525f65e2014-12-16 04:01:582803 assert_eq!(left, expected);
2804 assert_eq!(right, []);
2805 }
2806
Jorge Aparicio7d661af2015-01-26 20:46:122807 for j in -last..0 {
Clark Gaebel525f65e2014-12-16 04:01:582808 ring.push_front(j);
2809 let (left, right) = ring.as_mut_slices();
Jorge Aparicioc300d682015-01-26 20:44:222810 let expected_left: Vec<_> = (-last..j+1).rev().collect();
2811 let expected_right: Vec<_> = (0..first).collect();
Clark Gaebel525f65e2014-12-16 04:01:582812 assert_eq!(left, expected_left);
2813 assert_eq!(right, expected_right);
2814 }
2815
Alex Crichton3a2530d2015-01-30 20:26:442816 assert_eq!(ring.len() as i32, cap);
2817 assert_eq!(ring.capacity() as i32, cap);
Clark Gaebel525f65e2014-12-16 04:01:582818 }
Alexisdc930b12015-02-07 16:46:162819
2820 #[test]
2821 fn test_split_off() {
2822 // This test checks that every single combination of tail position, length, and
2823 // split position is tested. Capacity 15 should be large enough to cover every case.
2824
Aaron Turon5fa9de12015-02-18 07:44:552825 let mut tester = VecDeque::with_capacity(15);
Alexisdc930b12015-02-07 16:46:162826 // can't guarantee we got 15, so have to get what we got.
2827 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2828 // this test isn't covering what it wants to
2829 let cap = tester.capacity();
2830
2831 // len is the length *before* splitting
2832 for len in 0..cap {
2833 // index to split at
2834 for at in 0..len + 1 {
2835 // 0, 1, 2, .., at - 1 (may be empty)
2836 let expected_self = iter::count(0, 1).take(at).collect();
2837 // at, at + 1, .., len - 1 (may be empty)
2838 let expected_other = iter::count(at, 1).take(len - at).collect();
2839
2840 for tail_pos in 0..cap {
2841 tester.tail = tail_pos;
2842 tester.head = tail_pos;
2843 for i in 0..len {
2844 tester.push_back(i);
2845 }
2846 let result = tester.split_off(at);
2847 assert!(tester.tail < tester.cap);
2848 assert!(tester.head < tester.cap);
2849 assert!(result.tail < result.cap);
2850 assert!(result.head < result.cap);
2851 assert_eq!(tester, expected_self);
2852 assert_eq!(result, expected_other);
2853 }
2854 }
2855 }
2856 }
Alexis3c18bc42015-02-07 17:13:322857
2858 #[test]
2859 fn test_append() {
Aaron Turon5fa9de12015-02-18 07:44:552860 let mut a: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
2861 let mut b: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
Alexis3c18bc42015-02-07 17:13:322862
2863 // normal append
2864 a.append(&mut b);
Vadim Petrochenkovc11807d2015-02-24 20:42:092865 assert_eq!(a.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
2866 assert_eq!(b.iter().cloned().collect::<Vec<_>>(), []);
Alexis3c18bc42015-02-07 17:13:322867
2868 // append nothing to something
2869 a.append(&mut b);
Vadim Petrochenkovc11807d2015-02-24 20:42:092870 assert_eq!(a.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
2871 assert_eq!(b.iter().cloned().collect::<Vec<_>>(), []);
Alexis3c18bc42015-02-07 17:13:322872
2873 // append something to nothing
2874 b.append(&mut a);
Vadim Petrochenkovc11807d2015-02-24 20:42:092875 assert_eq!(b.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
2876 assert_eq!(a.iter().cloned().collect::<Vec<_>>(), []);
Alexis3c18bc42015-02-07 17:13:322877 }
Michael Sullivanc854d6e2012-07-03 17:52:322878}