blob: abe8e7cf3aa0fd9de1df96657391104ac3b381f2 [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;
Felix S. Klock IIe7c98612015-02-19 07:33:3228use core::num::wrapping::WrappingOps;
Alex Crichton56290a02014-12-22 17:04:2329use core::ops::{Index, IndexMut};
Niko Matsakis8dbdcdb2015-02-12 15:38:4530use core::ptr::{self, Unique};
Oliver Schneider6584ae52015-03-13 08:56:1831use core::slice;
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
Florian Zeitzf35f9732015-02-27 14:36:5342const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
43const 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:5562impl<T: Clone> Clone for VecDeque<T> {
63 fn clone(&self) -> VecDeque<T> {
Alexise250fe32015-02-05 02:17:1964 self.iter().cloned().collect()
Colin Sherratt7a666df2014-10-19 20:19:0765 }
66}
67
68#[unsafe_destructor]
Brian Andersonb44ee372015-01-24 05:48:2069#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5570impl<T> Drop for VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:0771 fn drop(&mut self) {
72 self.clear();
73 unsafe {
74 if mem::size_of::<T>() != 0 {
Niko Matsakis8dbdcdb2015-02-12 15:38:4575 heap::deallocate(*self.ptr as *mut u8,
Colin Sherratt7a666df2014-10-19 20:19:0776 self.cap * mem::size_of::<T>(),
77 mem::min_align_of::<T>())
78 }
79 }
80 }
Marijn Haverbeke26610db2012-01-11 11:49:3381}
Roy Frostig9c818892010-07-21 01:03:0982
Brian Andersonb44ee372015-01-24 05:48:2083#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5584impl<T> Default for VecDeque<T> {
Tom Jakubowskid6a39412014-06-09 07:30:0485 #[inline]
Aaron Turon5fa9de12015-02-18 07:44:5586 fn default() -> VecDeque<T> { VecDeque::new() }
Tom Jakubowskid6a39412014-06-09 07:30:0487}
88
Aaron Turon5fa9de12015-02-18 07:44:5589impl<T> VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:0790 /// Turn ptr into a slice
91 #[inline]
Alexis Beingessner8dbaa712014-12-31 00:07:5392 unsafe fn buffer_as_slice(&self) -> &[T] {
Oliver Schneider6584ae52015-03-13 08:56:1893 slice::from_raw_parts(*self.ptr, self.cap)
Clark Gaebel525f65e2014-12-16 04:01:5894 }
95
96 /// Turn ptr into a mut slice
97 #[inline]
Alexis Beingessner8dbaa712014-12-31 00:07:5398 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
Oliver Schneider6584ae52015-03-13 08:56:1899 slice::from_raw_parts_mut(*self.ptr, self.cap)
Colin Sherratt7a666df2014-10-19 20:19:07100 }
101
102 /// Moves an element out of the buffer
103 #[inline]
Alexise250fe32015-02-05 02:17:19104 unsafe fn buffer_read(&mut self, off: usize) -> T {
105 ptr::read(self.ptr.offset(off as isize))
Colin Sherratt7a666df2014-10-19 20:19:07106 }
107
108 /// Writes an element into the buffer, moving it.
109 #[inline]
Alexise250fe32015-02-05 02:17:19110 unsafe fn buffer_write(&mut self, off: usize, t: T) {
111 ptr::write(self.ptr.offset(off as isize), t);
Colin Sherratt7a666df2014-10-19 20:19:07112 }
113
114 /// Returns true iff the buffer is at capacity
115 #[inline]
116 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
Colin Sherratt40191182014-11-12 01:22:07117
Alex Crichton665ea962015-02-18 03:00:20118 /// Returns the index in the underlying buffer for a given logical element
119 /// index.
Colin Sherratt40191182014-11-12 01:22:07120 #[inline]
Alexise250fe32015-02-05 02:17:19121 fn wrap_index(&self, idx: usize) -> usize { wrap_index(idx, self.cap) }
Matt Murphy40f28c72014-12-03 17:12:30122
Felix S. Klock IIe7c98612015-02-19 07:33:32123 /// Returns the index in the underlying buffer for a given logical element
124 /// index + addend.
125 #[inline]
126 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
127 wrap_index(idx.wrapping_add(addend), self.cap)
128 }
129
130 /// Returns the index in the underlying buffer for a given logical element
131 /// index - subtrahend.
132 #[inline]
133 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
134 wrap_index(idx.wrapping_sub(subtrahend), self.cap)
135 }
136
Matt Murphy40f28c72014-12-03 17:12:30137 /// Copies a contiguous block of memory len long from src to dst
138 #[inline]
Alexise250fe32015-02-05 02:17:19139 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
Piotr Czarnecki59d41532014-12-16 23:37:55140 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
141 self.cap);
142 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
143 self.cap);
Alex Crichtonab456942015-02-23 19:39:16144 ptr::copy(
Alexise250fe32015-02-05 02:17:19145 self.ptr.offset(src as isize),
Alex Crichtonacd48a22015-03-27 18:12:28146 self.ptr.offset(dst as isize),
Piotr Czarnecki156a1c32015-01-05 14:48:58147 len);
148 }
149
150 /// Copies a contiguous block of memory len long from src to dst
151 #[inline]
Alexise250fe32015-02-05 02:17:19152 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
Piotr Czarnecki156a1c32015-01-05 14:48:58153 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
154 self.cap);
155 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
156 self.cap);
Alex Crichtonab456942015-02-23 19:39:16157 ptr::copy_nonoverlapping(
Alexise250fe32015-02-05 02:17:19158 self.ptr.offset(src as isize),
Alex Crichtonacd48a22015-03-27 18:12:28159 self.ptr.offset(dst as isize),
Piotr Czarnecki59d41532014-12-16 23:37:55160 len);
Matt Murphy40f28c72014-12-03 17:12:30161 }
Colin Sherratt7a666df2014-10-19 20:19:07162}
163
Aaron Turon5fa9de12015-02-18 07:44:55164impl<T> VecDeque<T> {
165 /// Creates an empty `VecDeque`.
Brian Andersonb44ee372015-01-24 05:48:20166 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55167 pub fn new() -> VecDeque<T> {
168 VecDeque::with_capacity(INITIAL_CAPACITY)
blake2-ppc70523712013-07-10 13:27:14169 }
170
Aaron Turon5fa9de12015-02-18 07:44:55171 /// Creates an empty `VecDeque` with space for at least `n` elements.
Brian Andersonb44ee372015-01-24 05:48:20172 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55173 pub fn with_capacity(n: usize) -> VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:07174 // +1 since the ringbuffer always leaves one space empty
Piotr Czarnecki156a1c32015-01-05 14:48:58175 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
176 assert!(cap > n, "capacity overflow");
Colin Sherratt6277e3b2014-11-14 09:21:44177 let size = cap.checked_mul(mem::size_of::<T>())
Colin Sherratt7a666df2014-10-19 20:19:07178 .expect("capacity overflow");
179
Niko Matsakis8dbdcdb2015-02-12 15:38:45180 let ptr = unsafe {
181 if mem::size_of::<T>() != 0 {
Colin Sherrattba24e332014-11-10 03:34:53182 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
183 if ptr.is_null() { ::alloc::oom() }
Niko Matsakis8dbdcdb2015-02-12 15:38:45184 Unique::new(ptr)
185 } else {
186 Unique::new(heap::EMPTY as *mut T)
Colin Sherrattba24e332014-11-10 03:34:53187 }
Colin Sherrattba24e332014-11-10 03:34:53188 };
189
Aaron Turon5fa9de12015-02-18 07:44:55190 VecDeque {
Colin Sherratt7a666df2014-10-19 20:19:07191 tail: 0,
192 head: 0,
193 cap: cap,
Niko Matsakis8dbdcdb2015-02-12 15:38:45194 ptr: ptr,
Colin Sherratt7a666df2014-10-19 20:19:07195 }
blake2-ppc70523712013-07-10 13:27:14196 }
197
Aaron Turon5fa9de12015-02-18 07:44:55198 /// Retrieves an element in the `VecDeque` by index.
blake2-ppc70523712013-07-10 13:27:14199 ///
jbranchaudc09defa2014-12-09 05:28:07200 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47201 ///
Joseph Crailfcf3f322015-03-13 02:42:38202 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55203 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47204 ///
Aaron Turon5fa9de12015-02-18 07:44:55205 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03206 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47207 /// buf.push_back(4);
208 /// buf.push_back(5);
209 /// assert_eq!(buf.get(1).unwrap(), &4);
210 /// ```
Brian Andersonb44ee372015-01-24 05:48:20211 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19212 pub fn get(&self, i: usize) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07213 if i < self.len() {
Felix S. Klock IIe7c98612015-02-19 07:33:32214 let idx = self.wrap_add(self.tail, i);
Alexise250fe32015-02-05 02:17:19215 unsafe { Some(&*self.ptr.offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07216 } else {
217 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47218 }
219 }
220
Aaron Turon5fa9de12015-02-18 07:44:55221 /// Retrieves an element in the `VecDeque` mutably by index.
nhamebe80972014-07-17 23:19:51222 ///
jbranchaudc09defa2014-12-09 05:28:07223 /// # Examples
nhamebe80972014-07-17 23:19:51224 ///
Joseph Crailfcf3f322015-03-13 02:42:38225 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55226 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51227 ///
Aaron Turon5fa9de12015-02-18 07:44:55228 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03229 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47230 /// buf.push_back(4);
231 /// buf.push_back(5);
232 /// match buf.get_mut(1) {
233 /// None => {}
234 /// Some(elem) => {
235 /// *elem = 7;
236 /// }
237 /// }
238 ///
P1startfd10d202014-08-02 06:39:39239 /// assert_eq!(buf[1], 7);
nhamebe80972014-07-17 23:19:51240 /// ```
Brian Andersonb44ee372015-01-24 05:48:20241 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19242 pub fn get_mut(&mut self, i: usize) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07243 if i < self.len() {
Felix S. Klock IIe7c98612015-02-19 07:33:32244 let idx = self.wrap_add(self.tail, i);
Alexise250fe32015-02-05 02:17:19245 unsafe { Some(&mut *self.ptr.offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07246 } else {
247 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47248 }
blake2-ppc70523712013-07-10 13:27:14249 }
250
P1startf2aa88c2014-08-04 10:48:39251 /// Swaps elements at indices `i` and `j`.
blake2-ppc57757a82013-09-26 07:19:26252 ///
253 /// `i` and `j` may be equal.
254 ///
P1startf2aa88c2014-08-04 10:48:39255 /// Fails if there is no element with either index.
nhamebe80972014-07-17 23:19:51256 ///
jbranchaudc09defa2014-12-09 05:28:07257 /// # Examples
nhamebe80972014-07-17 23:19:51258 ///
Joseph Crailfcf3f322015-03-13 02:42:38259 /// ```
Brian Andersone9019102015-03-13 22:28:35260 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55261 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51262 ///
Aaron Turon5fa9de12015-02-18 07:44:55263 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03264 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47265 /// buf.push_back(4);
266 /// buf.push_back(5);
nhamebe80972014-07-17 23:19:51267 /// buf.swap(0, 2);
P1startfd10d202014-08-02 06:39:39268 /// assert_eq!(buf[0], 5);
269 /// assert_eq!(buf[2], 3);
nhamebe80972014-07-17 23:19:51270 /// ```
Brian Andersonb44ee372015-01-24 05:48:20271 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19272 pub fn swap(&mut self, i: usize, j: usize) {
blake2-ppc57757a82013-09-26 07:19:26273 assert!(i < self.len());
274 assert!(j < self.len());
Felix S. Klock IIe7c98612015-02-19 07:33:32275 let ri = self.wrap_add(self.tail, i);
276 let rj = self.wrap_add(self.tail, j);
Colin Sherratt7a666df2014-10-19 20:19:07277 unsafe {
Alexise250fe32015-02-05 02:17:19278 ptr::swap(self.ptr.offset(ri as isize), self.ptr.offset(rj as isize))
Colin Sherratt7a666df2014-10-19 20:19:07279 }
blake2-ppc70523712013-07-10 13:27:14280 }
281
Aaron Turon5fa9de12015-02-18 07:44:55282 /// Returns the number of elements the `VecDeque` can hold without
Alexis Beingessnercf3b2e42014-11-06 17:24:47283 /// reallocating.
284 ///
jbranchaudc09defa2014-12-09 05:28:07285 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47286 ///
287 /// ```
Brian Andersone9019102015-03-13 22:28:35288 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55289 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47290 ///
Aaron Turon5fa9de12015-02-18 07:44:55291 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
Colin Sherratt7a666df2014-10-19 20:19:07292 /// assert!(buf.capacity() >= 10);
Alexis Beingessnercf3b2e42014-11-06 17:24:47293 /// ```
294 #[inline]
Brian Andersonb44ee372015-01-24 05:48:20295 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19296 pub fn capacity(&self) -> usize { self.cap - 1 }
Tim Chevalier77de84b2013-05-27 18:47:38297
Alexis Beingessnercf3b2e42014-11-06 17:24:47298 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
Aaron Turon5fa9de12015-02-18 07:44:55299 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
Tim Chevalier77de84b2013-05-27 18:47:38300 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47301 /// Note that the allocator may give the collection more space than it requests. Therefore
302 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
303 /// insertions are expected.
304 ///
305 /// # Panics
306 ///
Alexise250fe32015-02-05 02:17:19307 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47308 ///
jbranchaudc09defa2014-12-09 05:28:07309 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47310 ///
311 /// ```
Brian Andersone9019102015-03-13 22:28:35312 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55313 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47314 ///
Aaron Turon5fa9de12015-02-18 07:44:55315 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47316 /// buf.reserve_exact(10);
317 /// assert!(buf.capacity() >= 11);
318 /// ```
Brian Andersonb44ee372015-01-24 05:48:20319 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19320 pub fn reserve_exact(&mut self, additional: usize) {
Colin Sherratt7a666df2014-10-19 20:19:07321 self.reserve(additional);
Alexis Beingessnercf3b2e42014-11-06 17:24:47322 }
323
324 /// Reserves capacity for at least `additional` more elements to be inserted in the given
325 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
326 ///
327 /// # Panics
328 ///
Alexise250fe32015-02-05 02:17:19329 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47330 ///
jbranchaudc09defa2014-12-09 05:28:07331 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47332 ///
333 /// ```
Brian Andersone9019102015-03-13 22:28:35334 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55335 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47336 ///
Aaron Turon5fa9de12015-02-18 07:44:55337 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47338 /// buf.reserve(10);
339 /// assert!(buf.capacity() >= 11);
340 /// ```
Brian Andersonb44ee372015-01-24 05:48:20341 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19342 pub fn reserve(&mut self, additional: usize) {
Colin Sherratt7a666df2014-10-19 20:19:07343 let new_len = self.len() + additional;
344 assert!(new_len + 1 > self.len(), "capacity overflow");
345 if new_len > self.capacity() {
Colin Sherratt6277e3b2014-11-14 09:21:44346 let count = (new_len + 1).next_power_of_two();
Colin Sherratt7a666df2014-10-19 20:19:07347 assert!(count >= new_len + 1);
348
349 if mem::size_of::<T>() != 0 {
350 let old = self.cap * mem::size_of::<T>();
Colin Sherratt6277e3b2014-11-14 09:21:44351 let new = count.checked_mul(mem::size_of::<T>())
Colin Sherratt7a666df2014-10-19 20:19:07352 .expect("capacity overflow");
353 unsafe {
Niko Matsakis8dbdcdb2015-02-12 15:38:45354 let ptr = heap::reallocate(*self.ptr as *mut u8,
355 old,
356 new,
357 mem::min_align_of::<T>()) as *mut T;
358 if ptr.is_null() { ::alloc::oom() }
359 self.ptr = Unique::new(ptr);
Colin Sherratt7a666df2014-10-19 20:19:07360 }
361 }
362
363 // Move the shortest contiguous section of the ring buffer
364 // T H
365 // [o o o o o o o . ]
366 // T H
367 // A [o o o o o o o . . . . . . . . . ]
368 // H T
369 // [o o . o o o o o ]
370 // T H
371 // B [. . . o o o o o o o . . . . . . ]
372 // H T
373 // [o o o o o . o o ]
374 // H T
375 // C [o o o o o . . . . . . . . . o o ]
376
377 let oldcap = self.cap;
378 self.cap = count;
379
380 if self.tail <= self.head { // A
381 // Nop
382 } else if self.head < oldcap - self.tail { // B
383 unsafe {
Piotr Czarnecki156a1c32015-01-05 14:48:58384 self.copy_nonoverlapping(oldcap, 0, self.head);
Colin Sherratt7a666df2014-10-19 20:19:07385 }
386 self.head += oldcap;
Colin Sherratt4cae9ad2014-11-11 02:16:29387 debug_assert!(self.head > self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07388 } else { // C
Piotr Czarnecki156a1c32015-01-05 14:48:58389 let new_tail = count - (oldcap - self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07390 unsafe {
Piotr Czarnecki156a1c32015-01-05 14:48:58391 self.copy_nonoverlapping(new_tail, self.tail, oldcap - self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07392 }
Piotr Czarnecki156a1c32015-01-05 14:48:58393 self.tail = new_tail;
Colin Sherratt4cae9ad2014-11-11 02:16:29394 debug_assert!(self.head < self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07395 }
Colin Sherratt4cae9ad2014-11-11 02:16:29396 debug_assert!(self.head < self.cap);
397 debug_assert!(self.tail < self.cap);
Colin Sherratt40191182014-11-12 01:22:07398 debug_assert!(self.cap.count_ones() == 1);
Colin Sherratt7a666df2014-10-19 20:19:07399 }
Tim Chevalier77de84b2013-05-27 18:47:38400 }
Jed Estep4f7a7422013-06-25 19:08:47401
Piotr Czarnecki156a1c32015-01-05 14:48:58402 /// Shrinks the capacity of the ringbuf as much as possible.
403 ///
404 /// It will drop down as close as possible to the length but the allocator may still inform the
405 /// ringbuf that there is space for a few more elements.
406 ///
407 /// # Examples
408 ///
409 /// ```
Brian Andersone9019102015-03-13 22:28:35410 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55411 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58412 ///
Aaron Turon5fa9de12015-02-18 07:44:55413 /// let mut buf = VecDeque::with_capacity(15);
Alexise15538d2015-02-06 18:57:13414 /// buf.extend(0..4);
Piotr Czarnecki156a1c32015-01-05 14:48:58415 /// assert_eq!(buf.capacity(), 15);
416 /// buf.shrink_to_fit();
417 /// assert!(buf.capacity() >= 4);
418 /// ```
419 pub fn shrink_to_fit(&mut self) {
420 // +1 since the ringbuffer always leaves one space empty
421 // len + 1 can't overflow for an existing, well-formed ringbuf.
422 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
423 if target_cap < self.cap {
424 // There are three cases of interest:
425 // All elements are out of desired bounds
426 // Elements are contiguous, and head is out of desired bounds
427 // Elements are discontiguous, and tail is out of desired bounds
428 //
429 // At all other times, element positions are unaffected.
430 //
431 // Indicates that elements at the head should be moved.
432 let head_outside = self.head == 0 || self.head >= target_cap;
433 // Move elements from out of desired bounds (positions after target_cap)
434 if self.tail >= target_cap && head_outside {
435 // T H
436 // [. . . . . . . . o o o o o o o . ]
437 // T H
438 // [o o o o o o o . ]
439 unsafe {
440 self.copy_nonoverlapping(0, self.tail, self.len());
441 }
442 self.head = self.len();
443 self.tail = 0;
444 } else if self.tail != 0 && self.tail < target_cap && head_outside {
445 // T H
446 // [. . . o o o o o o o . . . . . . ]
447 // H T
448 // [o o . o o o o o ]
Felix S. Klock IIe7c98612015-02-19 07:33:32449 let len = self.wrap_sub(self.head, target_cap);
Piotr Czarnecki156a1c32015-01-05 14:48:58450 unsafe {
451 self.copy_nonoverlapping(0, target_cap, len);
452 }
453 self.head = len;
454 debug_assert!(self.head < self.tail);
455 } else if self.tail >= target_cap {
456 // H T
457 // [o o o o o . . . . . . . . . o o ]
458 // H T
459 // [o o o o o . o o ]
Felix S. Klock IIe7c98612015-02-19 07:33:32460 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
Piotr Czarnecki156a1c32015-01-05 14:48:58461 let len = self.cap - self.tail;
462 let new_tail = target_cap - len;
463 unsafe {
464 self.copy_nonoverlapping(new_tail, self.tail, len);
465 }
466 self.tail = new_tail;
467 debug_assert!(self.head < self.tail);
468 }
469
470 if mem::size_of::<T>() != 0 {
471 let old = self.cap * mem::size_of::<T>();
472 let new_size = target_cap * mem::size_of::<T>();
473 unsafe {
Niko Matsakis8dbdcdb2015-02-12 15:38:45474 let ptr = heap::reallocate(*self.ptr as *mut u8,
475 old,
476 new_size,
477 mem::min_align_of::<T>()) as *mut T;
478 if ptr.is_null() { ::alloc::oom() }
479 self.ptr = Unique::new(ptr);
Piotr Czarnecki156a1c32015-01-05 14:48:58480 }
481 }
482 self.cap = target_cap;
483 debug_assert!(self.head < self.cap);
484 debug_assert!(self.tail < self.cap);
485 debug_assert!(self.cap.count_ones() == 1);
486 }
487 }
488
489 /// Shorten a ringbuf, dropping excess elements from the back.
490 ///
491 /// If `len` is greater than the ringbuf's current length, this has no
492 /// effect.
493 ///
494 /// # Examples
495 ///
496 /// ```
Brian Andersone9019102015-03-13 22:28:35497 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55498 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58499 ///
Aaron Turon5fa9de12015-02-18 07:44:55500 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03501 /// buf.push_back(5);
502 /// buf.push_back(10);
Piotr Czarnecki156a1c32015-01-05 14:48:58503 /// buf.push_back(15);
504 /// buf.truncate(1);
505 /// assert_eq!(buf.len(), 1);
506 /// assert_eq!(Some(&5), buf.get(0));
507 /// ```
Brian Andersoncd6d9ea2015-01-23 02:22:03508 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19509 reason = "matches collection reform specification; waiting on panic semantics")]
Alexise250fe32015-02-05 02:17:19510 pub fn truncate(&mut self, len: usize) {
Jorge Aparicioefc97a52015-01-26 21:05:07511 for _ in len..self.len() {
Piotr Czarnecki156a1c32015-01-05 14:48:58512 self.pop_back();
513 }
514 }
515
P1startf2aa88c2014-08-04 10:48:39516 /// Returns a front-to-back iterator.
nhamebe80972014-07-17 23:19:51517 ///
jbranchaudc09defa2014-12-09 05:28:07518 /// # Examples
nhamebe80972014-07-17 23:19:51519 ///
Joseph Crailfcf3f322015-03-13 02:42:38520 /// ```
Brian Andersone9019102015-03-13 22:28:35521 /// # #![feature(core)]
Aaron Turon5fa9de12015-02-18 07:44:55522 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51523 ///
Aaron Turon5fa9de12015-02-18 07:44:55524 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03525 /// buf.push_back(5);
Alexis Beingessnercf3b2e42014-11-06 17:24:47526 /// buf.push_back(3);
527 /// buf.push_back(4);
Nick Cameron52ef4622014-08-06 09:59:40528 /// let b: &[_] = &[&5, &3, &4];
Tobias Bucher7f64fe42015-01-25 21:05:03529 /// assert_eq!(buf.iter().collect::<Vec<&i32>>().as_slice(), b);
nhamebe80972014-07-17 23:19:51530 /// ```
Brian Andersonb44ee372015-01-24 05:48:20531 #[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:10532 pub fn iter(&self) -> Iter<T> {
533 Iter {
Colin Sherratt7a666df2014-10-19 20:19:07534 tail: self.tail,
535 head: self.head,
536 ring: unsafe { self.buffer_as_slice() }
537 }
blake2-ppc3385e792013-07-15 23:13:26538 }
539
Andrew Wagner8fcc8322014-12-15 09:22:49540 /// Returns a front-to-back iterator that returns mutable references.
nhamebe80972014-07-17 23:19:51541 ///
jbranchaudc09defa2014-12-09 05:28:07542 /// # Examples
nhamebe80972014-07-17 23:19:51543 ///
Joseph Crailfcf3f322015-03-13 02:42:38544 /// ```
Brian Andersone9019102015-03-13 22:28:35545 /// # #![feature(core)]
Aaron Turon5fa9de12015-02-18 07:44:55546 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51547 ///
Aaron Turon5fa9de12015-02-18 07:44:55548 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03549 /// buf.push_back(5);
Alexis Beingessnercf3b2e42014-11-06 17:24:47550 /// buf.push_back(3);
551 /// buf.push_back(4);
Aaron Turonfc525ee2014-09-15 03:27:36552 /// for num in buf.iter_mut() {
nhamebe80972014-07-17 23:19:51553 /// *num = *num - 2;
554 /// }
Nick Cameron52ef4622014-08-06 09:59:40555 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
Alex Crichton77de3ee2015-03-26 16:57:58556 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
nhamebe80972014-07-17 23:19:51557 /// ```
Brian Andersonb44ee372015-01-24 05:48:20558 #[stable(feature = "rust1", since = "1.0.0")]
Alexis1420ceb2015-02-05 18:48:20559 pub fn iter_mut(&mut self) -> IterMut<T> {
Florian Wilkensf8cfd242014-12-19 20:52:10560 IterMut {
Colin Sherratt7a666df2014-10-19 20:19:07561 tail: self.tail,
562 head: self.head,
Edward Wang101498c2015-02-25 10:11:23563 ring: unsafe { self.buffer_as_mut_slice() },
Niko Matsakisbc4164d2013-11-16 22:29:39564 }
Jed Estep4f7a7422013-06-25 19:08:47565 }
Alex Crichton21ac9852014-10-30 20:43:24566
Andrew Paseltiner88edf972015-03-23 12:51:29567 /// Consumes the list into a front-to-back iterator yielding elements by value.
Brian Andersonb44ee372015-01-24 05:48:20568 #[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:10569 pub fn into_iter(self) -> IntoIter<T> {
570 IntoIter {
Alexis Beingessner865c2db2014-11-23 02:34:11571 inner: self,
572 }
573 }
574
Clark Gaebel525f65e2014-12-16 04:01:58575 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55576 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58577 #[inline]
Brian Andersoncd6d9ea2015-01-23 02:22:03578 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19579 reason = "matches collection reform specification, waiting for dust to settle")]
Alexis1420ceb2015-02-05 18:48:20580 pub fn as_slices(&self) -> (&[T], &[T]) {
Clark Gaebel525f65e2014-12-16 04:01:58581 unsafe {
582 let contiguous = self.is_contiguous();
583 let buf = self.buffer_as_slice();
584 if contiguous {
585 let (empty, buf) = buf.split_at(0);
Jorge Aparicio517f1cc2015-01-07 16:58:31586 (&buf[self.tail..self.head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58587 } else {
588 let (mid, right) = buf.split_at(self.tail);
589 let (left, _) = mid.split_at(self.head);
590 (right, left)
591 }
592 }
593 }
594
595 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55596 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58597 #[inline]
Brian Andersoncd6d9ea2015-01-23 02:22:03598 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19599 reason = "matches collection reform specification, waiting for dust to settle")]
Alexis1420ceb2015-02-05 18:48:20600 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
Clark Gaebel525f65e2014-12-16 04:01:58601 unsafe {
602 let contiguous = self.is_contiguous();
603 let head = self.head;
604 let tail = self.tail;
605 let buf = self.buffer_as_mut_slice();
606
607 if contiguous {
608 let (empty, buf) = buf.split_at_mut(0);
Aaron Turona506d4c2015-01-18 00:15:52609 (&mut buf[tail .. head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58610 } else {
611 let (mid, right) = buf.split_at_mut(tail);
612 let (left, _) = mid.split_at_mut(head);
613
614 (right, left)
615 }
616 }
617 }
618
Aaron Turon5fa9de12015-02-18 07:44:55619 /// Returns the number of elements in the `VecDeque`.
Alex Crichton21ac9852014-10-30 20:43:24620 ///
jbranchaudc09defa2014-12-09 05:28:07621 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24622 ///
623 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55624 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24625 ///
Aaron Turon5fa9de12015-02-18 07:44:55626 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24627 /// assert_eq!(v.len(), 0);
Tobias Bucher7f64fe42015-01-25 21:05:03628 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24629 /// assert_eq!(v.len(), 1);
630 /// ```
Brian Andersonb44ee372015-01-24 05:48:20631 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19632 pub fn len(&self) -> usize { count(self.tail, self.head, self.cap) }
Alex Crichton21ac9852014-10-30 20:43:24633
634 /// Returns true if the buffer contains no elements
635 ///
jbranchaudc09defa2014-12-09 05:28:07636 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24637 ///
638 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55639 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24640 ///
Aaron Turon5fa9de12015-02-18 07:44:55641 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24642 /// assert!(v.is_empty());
Tobias Bucher7f64fe42015-01-25 21:05:03643 /// v.push_front(1);
Alex Crichton21ac9852014-10-30 20:43:24644 /// assert!(!v.is_empty());
645 /// ```
Brian Andersonb44ee372015-01-24 05:48:20646 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24647 pub fn is_empty(&self) -> bool { self.len() == 0 }
648
Aaron Turon5fa9de12015-02-18 07:44:55649 /// Creates a draining iterator that clears the `VecDeque` and iterates over
Clark Gaebeld57f2592014-12-16 22:45:03650 /// the removed items from start to end.
651 ///
652 /// # Examples
653 ///
654 /// ```
Brian Andersone9019102015-03-13 22:28:35655 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55656 /// use std::collections::VecDeque;
Clark Gaebeld57f2592014-12-16 22:45:03657 ///
Aaron Turon5fa9de12015-02-18 07:44:55658 /// let mut v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03659 /// v.push_back(1);
Clark Gaebeld57f2592014-12-16 22:45:03660 /// assert_eq!(v.drain().next(), Some(1));
661 /// assert!(v.is_empty());
662 /// ```
663 #[inline]
Brian Andersoncd6d9ea2015-01-23 02:22:03664 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19665 reason = "matches collection reform specification, waiting for dust to settle")]
Alexis Beingessner8dbaa712014-12-31 00:07:53666 pub fn drain(&mut self) -> Drain<T> {
Clark Gaebeld57f2592014-12-16 22:45:03667 Drain {
668 inner: self,
669 }
670 }
671
Alex Crichton21ac9852014-10-30 20:43:24672 /// Clears the buffer, removing all values.
673 ///
jbranchaudc09defa2014-12-09 05:28:07674 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24675 ///
676 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55677 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24678 ///
Aaron Turon5fa9de12015-02-18 07:44:55679 /// let mut v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03680 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24681 /// v.clear();
682 /// assert!(v.is_empty());
683 /// ```
Brian Andersonb44ee372015-01-24 05:48:20684 #[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:03685 #[inline]
Alex Crichton21ac9852014-10-30 20:43:24686 pub fn clear(&mut self) {
Clark Gaebeld57f2592014-12-16 22:45:03687 self.drain();
Alex Crichton21ac9852014-10-30 20:43:24688 }
689
690 /// Provides a reference to the front element, or `None` if the sequence is
691 /// empty.
692 ///
jbranchaudc09defa2014-12-09 05:28:07693 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24694 ///
695 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55696 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24697 ///
Aaron Turon5fa9de12015-02-18 07:44:55698 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24699 /// assert_eq!(d.front(), None);
700 ///
Tobias Bucher7f64fe42015-01-25 21:05:03701 /// d.push_back(1);
702 /// d.push_back(2);
703 /// assert_eq!(d.front(), Some(&1));
Alex Crichton21ac9852014-10-30 20:43:24704 /// ```
Brian Andersonb44ee372015-01-24 05:48:20705 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24706 pub fn front(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07707 if !self.is_empty() { Some(&self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24708 }
709
710 /// Provides a mutable reference to the front element, or `None` if the
711 /// sequence is empty.
712 ///
jbranchaudc09defa2014-12-09 05:28:07713 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24714 ///
715 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55716 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24717 ///
Aaron Turon5fa9de12015-02-18 07:44:55718 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24719 /// assert_eq!(d.front_mut(), None);
720 ///
Tobias Bucher7f64fe42015-01-25 21:05:03721 /// d.push_back(1);
722 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24723 /// match d.front_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03724 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24725 /// None => (),
726 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03727 /// assert_eq!(d.front(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24728 /// ```
Brian Andersonb44ee372015-01-24 05:48:20729 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24730 pub fn front_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07731 if !self.is_empty() { Some(&mut self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24732 }
733
734 /// Provides a reference to the back element, or `None` if the sequence is
735 /// empty.
736 ///
jbranchaudc09defa2014-12-09 05:28:07737 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24738 ///
739 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55740 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24741 ///
Aaron Turon5fa9de12015-02-18 07:44:55742 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24743 /// assert_eq!(d.back(), None);
744 ///
Tobias Bucher7f64fe42015-01-25 21:05:03745 /// d.push_back(1);
746 /// d.push_back(2);
747 /// assert_eq!(d.back(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24748 /// ```
Brian Andersonb44ee372015-01-24 05:48:20749 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24750 pub fn back(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07751 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24752 }
753
754 /// Provides a mutable reference to the back element, or `None` if the
755 /// sequence is empty.
756 ///
jbranchaudc09defa2014-12-09 05:28:07757 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24758 ///
759 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55760 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24761 ///
Aaron Turon5fa9de12015-02-18 07:44:55762 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24763 /// assert_eq!(d.back(), None);
764 ///
Tobias Bucher7f64fe42015-01-25 21:05:03765 /// d.push_back(1);
766 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24767 /// match d.back_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03768 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24769 /// None => (),
770 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03771 /// assert_eq!(d.back(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24772 /// ```
Brian Andersonb44ee372015-01-24 05:48:20773 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24774 pub fn back_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07775 let len = self.len();
776 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24777 }
778
779 /// Removes the first element and returns it, or `None` if the sequence is
780 /// empty.
781 ///
jbranchaudc09defa2014-12-09 05:28:07782 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24783 ///
784 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55785 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24786 ///
Aaron Turon5fa9de12015-02-18 07:44:55787 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03788 /// d.push_back(1);
789 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24790 ///
Tobias Bucher7f64fe42015-01-25 21:05:03791 /// assert_eq!(d.pop_front(), Some(1));
792 /// assert_eq!(d.pop_front(), Some(2));
Alex Crichton21ac9852014-10-30 20:43:24793 /// assert_eq!(d.pop_front(), None);
794 /// ```
Brian Andersonb44ee372015-01-24 05:48:20795 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24796 pub fn pop_front(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07797 if self.is_empty() {
798 None
799 } else {
800 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:32801 self.tail = self.wrap_add(self.tail, 1);
Colin Sherratt7a666df2014-10-19 20:19:07802 unsafe { Some(self.buffer_read(tail)) }
Alex Crichton21ac9852014-10-30 20:43:24803 }
Alex Crichton21ac9852014-10-30 20:43:24804 }
805
806 /// Inserts an element first in the sequence.
807 ///
jbranchaudc09defa2014-12-09 05:28:07808 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24809 ///
810 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55811 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24812 ///
Aaron Turon5fa9de12015-02-18 07:44:55813 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03814 /// d.push_front(1);
815 /// d.push_front(2);
816 /// assert_eq!(d.front(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24817 /// ```
Brian Andersonb44ee372015-01-24 05:48:20818 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24819 pub fn push_front(&mut self, t: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29820 if self.is_full() {
821 self.reserve(1);
822 debug_assert!(!self.is_full());
823 }
Colin Sherratt7a666df2014-10-19 20:19:07824
Felix S. Klock IIe7c98612015-02-19 07:33:32825 self.tail = self.wrap_sub(self.tail, 1);
Colin Sherratt7a666df2014-10-19 20:19:07826 let tail = self.tail;
827 unsafe { self.buffer_write(tail, t); }
Alex Crichton21ac9852014-10-30 20:43:24828 }
829
830 /// Appends an element to the back of a buffer
831 ///
jbranchaudc09defa2014-12-09 05:28:07832 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24833 ///
Joseph Crailfcf3f322015-03-13 02:42:38834 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55835 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24836 ///
Aaron Turon5fa9de12015-02-18 07:44:55837 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03838 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:47839 /// buf.push_back(3);
Alex Crichton21ac9852014-10-30 20:43:24840 /// assert_eq!(3, *buf.back().unwrap());
841 /// ```
Brian Andersonb44ee372015-01-24 05:48:20842 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnercf3b2e42014-11-06 17:24:47843 pub fn push_back(&mut self, t: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29844 if self.is_full() {
845 self.reserve(1);
846 debug_assert!(!self.is_full());
847 }
Colin Sherratt7a666df2014-10-19 20:19:07848
849 let head = self.head;
Felix S. Klock IIe7c98612015-02-19 07:33:32850 self.head = self.wrap_add(self.head, 1);
Colin Sherratt7a666df2014-10-19 20:19:07851 unsafe { self.buffer_write(head, t) }
Alex Crichton21ac9852014-10-30 20:43:24852 }
853
854 /// Removes the last element from a buffer and returns it, or `None` if
855 /// it is empty.
856 ///
jbranchaudc09defa2014-12-09 05:28:07857 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24858 ///
Joseph Crailfcf3f322015-03-13 02:42:38859 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55860 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24861 ///
Aaron Turon5fa9de12015-02-18 07:44:55862 /// let mut buf = VecDeque::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47863 /// assert_eq!(buf.pop_back(), None);
Tobias Bucher7f64fe42015-01-25 21:05:03864 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:47865 /// buf.push_back(3);
866 /// assert_eq!(buf.pop_back(), Some(3));
Alex Crichton21ac9852014-10-30 20:43:24867 /// ```
Brian Andersonb44ee372015-01-24 05:48:20868 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnercf3b2e42014-11-06 17:24:47869 pub fn pop_back(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07870 if self.is_empty() {
Alex Crichton21ac9852014-10-30 20:43:24871 None
Colin Sherratt7a666df2014-10-19 20:19:07872 } else {
Felix S. Klock IIe7c98612015-02-19 07:33:32873 self.head = self.wrap_sub(self.head, 1);
Colin Sherratt7a666df2014-10-19 20:19:07874 let head = self.head;
875 unsafe { Some(self.buffer_read(head)) }
Alex Crichton21ac9852014-10-30 20:43:24876 }
877 }
Matt Murphy40f28c72014-12-03 17:12:30878
Clark Gaebel525f65e2014-12-16 04:01:58879 #[inline]
880 fn is_contiguous(&self) -> bool {
881 self.tail <= self.head
882 }
883
Piotr Czarnecki156a1c32015-01-05 14:48:58884 /// Removes an element from anywhere in the ringbuf and returns it, replacing it with the last
885 /// element.
886 ///
887 /// This does not preserve ordering, but is O(1).
888 ///
889 /// Returns `None` if `index` is out of bounds.
890 ///
891 /// # Examples
892 ///
893 /// ```
Brian Andersone9019102015-03-13 22:28:35894 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55895 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58896 ///
Aaron Turon5fa9de12015-02-18 07:44:55897 /// let mut buf = VecDeque::new();
Piotr Czarnecki156a1c32015-01-05 14:48:58898 /// assert_eq!(buf.swap_back_remove(0), None);
Tobias Bucher7f64fe42015-01-25 21:05:03899 /// buf.push_back(5);
Piotr Czarnecki156a1c32015-01-05 14:48:58900 /// buf.push_back(99);
901 /// buf.push_back(15);
902 /// buf.push_back(20);
903 /// buf.push_back(10);
904 /// assert_eq!(buf.swap_back_remove(1), Some(99));
905 /// ```
Brian Andersoncd6d9ea2015-01-23 02:22:03906 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19907 reason = "the naming of this function may be altered")]
Alexise250fe32015-02-05 02:17:19908 pub fn swap_back_remove(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:58909 let length = self.len();
910 if length > 0 && index < length - 1 {
911 self.swap(index, length - 1);
912 } else if index >= length {
913 return None;
914 }
915 self.pop_back()
916 }
917
918 /// Removes an element from anywhere in the ringbuf and returns it, replacing it with the first
919 /// element.
920 ///
921 /// This does not preserve ordering, but is O(1).
922 ///
923 /// Returns `None` if `index` is out of bounds.
924 ///
925 /// # Examples
926 ///
927 /// ```
Brian Andersone9019102015-03-13 22:28:35928 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55929 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58930 ///
Aaron Turon5fa9de12015-02-18 07:44:55931 /// let mut buf = VecDeque::new();
Piotr Czarnecki156a1c32015-01-05 14:48:58932 /// assert_eq!(buf.swap_front_remove(0), None);
Tobias Bucher7f64fe42015-01-25 21:05:03933 /// buf.push_back(15);
Piotr Czarnecki156a1c32015-01-05 14:48:58934 /// buf.push_back(5);
935 /// buf.push_back(10);
936 /// buf.push_back(99);
Tobias Bucher7f64fe42015-01-25 21:05:03937 /// buf.push_back(20);
Piotr Czarnecki156a1c32015-01-05 14:48:58938 /// assert_eq!(buf.swap_front_remove(3), Some(99));
939 /// ```
Brian Andersoncd6d9ea2015-01-23 02:22:03940 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:19941 reason = "the naming of this function may be altered")]
Alexise250fe32015-02-05 02:17:19942 pub fn swap_front_remove(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:58943 let length = self.len();
944 if length > 0 && index < length && index != 0 {
945 self.swap(index, 0);
946 } else if index >= length {
947 return None;
948 }
949 self.pop_front()
950 }
951
Matt Murphy40f28c72014-12-03 17:12:30952 /// Inserts an element at position `i` within the ringbuf. Whichever
953 /// end is closer to the insertion point will be moved to make room,
954 /// and all the affected elements will be moved to new positions.
955 ///
956 /// # Panics
957 ///
958 /// Panics if `i` is greater than ringbuf's length
959 ///
Piotr Czarnecki156a1c32015-01-05 14:48:58960 /// # Examples
Joseph Crailfcf3f322015-03-13 02:42:38961 /// ```
Brian Andersone9019102015-03-13 22:28:35962 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55963 /// use std::collections::VecDeque;
Matt Murphy40f28c72014-12-03 17:12:30964 ///
Aaron Turon5fa9de12015-02-18 07:44:55965 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03966 /// buf.push_back(10);
Matt Murphy40f28c72014-12-03 17:12:30967 /// buf.push_back(12);
968 /// buf.insert(1,11);
969 /// assert_eq!(Some(&11), buf.get(1));
970 /// ```
Alexise250fe32015-02-05 02:17:19971 pub fn insert(&mut self, i: usize, t: T) {
Matt Murphy40f28c72014-12-03 17:12:30972 assert!(i <= self.len(), "index out of bounds");
973 if self.is_full() {
974 self.reserve(1);
975 debug_assert!(!self.is_full());
976 }
977
978 // Move the least number of elements in the ring buffer and insert
979 // the given object
980 //
981 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
982 //
983 // There are three main cases:
984 // Elements are contiguous
985 // - special case when tail is 0
986 // Elements are discontiguous and the insert is in the tail section
987 // Elements are discontiguous and the insert is in the head section
988 //
989 // For each of those there are two more cases:
990 // Insert is closer to tail
991 // Insert is closer to head
992 //
993 // Key: H - self.head
994 // T - self.tail
995 // o - Valid element
996 // I - Insertion element
997 // A - The element that should be after the insertion point
998 // M - Indicates element was moved
999
Felix S. Klock IIe7c98612015-02-19 07:33:321000 let idx = self.wrap_add(self.tail, i);
Matt Murphy40f28c72014-12-03 17:12:301001
1002 let distance_to_tail = i;
1003 let distance_to_head = self.len() - i;
1004
Clark Gaebel525f65e2014-12-16 04:01:581005 let contiguous = self.is_contiguous();
Matt Murphy40f28c72014-12-03 17:12:301006
1007 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1008 (true, true, _) if i == 0 => {
1009 // push_front
1010 //
1011 // T
1012 // I H
1013 // [A o o o o o o . . . . . . . . .]
1014 //
1015 // H T
1016 // [A o o o o o o o . . . . . I]
1017 //
1018
Felix S. Klock IIe7c98612015-02-19 07:33:321019 self.tail = self.wrap_sub(self.tail, 1);
Matt Murphy40f28c72014-12-03 17:12:301020 },
Piotr Czarnecki59d41532014-12-16 23:37:551021 (true, true, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:301022 // contiguous, insert closer to tail:
1023 //
1024 // T I H
1025 // [. . . o o A o o o o . . . . . .]
1026 //
1027 // T H
1028 // [. . o o I A o o o o . . . . . .]
1029 // M M
1030 //
1031 // contiguous, insert closer to tail and tail is 0:
1032 //
1033 //
1034 // T I H
1035 // [o o A o o o o . . . . . . . . .]
1036 //
1037 // H T
1038 // [o I A o o o o o . . . . . . . o]
1039 // M M
1040
Felix S. Klock IIe7c98612015-02-19 07:33:321041 let new_tail = self.wrap_sub(self.tail, 1);
Matt Murphy40f28c72014-12-03 17:12:301042
Piotr Czarnecki59d41532014-12-16 23:37:551043 self.copy(new_tail, self.tail, 1);
1044 // Already moved the tail, so we only copy `i - 1` elements.
1045 self.copy(self.tail, self.tail + 1, i - 1);
1046
1047 self.tail = new_tail;
Matt Murphy40f28c72014-12-03 17:12:301048 },
Piotr Czarnecki59d41532014-12-16 23:37:551049 (true, false, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:301050 // contiguous, insert closer to head:
1051 //
1052 // T I H
1053 // [. . . o o o o A o o . . . . . .]
1054 //
1055 // T H
1056 // [. . . o o o o I A o o . . . . .]
1057 // M M M
1058
Piotr Czarnecki59d41532014-12-16 23:37:551059 self.copy(idx + 1, idx, self.head - idx);
Felix S. Klock IIe7c98612015-02-19 07:33:321060 self.head = self.wrap_add(self.head, 1);
Matt Murphy40f28c72014-12-03 17:12:301061 },
Piotr Czarnecki59d41532014-12-16 23:37:551062 (false, true, true) => unsafe {
1063 // discontiguous, insert closer to tail, tail section:
Matt Murphy40f28c72014-12-03 17:12:301064 //
1065 // H T I
1066 // [o o o o o o . . . . . o o A o o]
1067 //
1068 // H T
1069 // [o o o o o o . . . . o o I A o o]
1070 // M M
1071
Piotr Czarnecki59d41532014-12-16 23:37:551072 self.copy(self.tail - 1, self.tail, i);
1073 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301074 },
Piotr Czarnecki59d41532014-12-16 23:37:551075 (false, false, true) => unsafe {
1076 // discontiguous, insert closer to head, tail section:
Matt Murphy40f28c72014-12-03 17:12:301077 //
1078 // H T I
1079 // [o o . . . . . . . o o o o o A o]
1080 //
1081 // H T
1082 // [o o o . . . . . . o o o o o I A]
1083 // M M M M
1084
Matt Murphy40f28c72014-12-03 17:12:301085 // copy elements up to new head
Piotr Czarnecki59d41532014-12-16 23:37:551086 self.copy(1, 0, self.head);
Matt Murphy40f28c72014-12-03 17:12:301087
1088 // copy last element into empty spot at bottom of buffer
1089 self.copy(0, self.cap - 1, 1);
1090
1091 // move elements from idx to end forward not including ^ element
1092 self.copy(idx + 1, idx, self.cap - 1 - idx);
Piotr Czarnecki59d41532014-12-16 23:37:551093
1094 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301095 },
Piotr Czarnecki59d41532014-12-16 23:37:551096 (false, true, false) if idx == 0 => unsafe {
1097 // discontiguous, insert is closer to tail, head section,
Matt Murphy40f28c72014-12-03 17:12:301098 // and is at index zero in the internal buffer:
1099 //
1100 // I H T
1101 // [A o o o o o o o o o . . . o o o]
1102 //
1103 // H T
1104 // [A o o o o o o o o o . . o o o I]
1105 // M M M
1106
Matt Murphy40f28c72014-12-03 17:12:301107 // copy elements up to new tail
Piotr Czarnecki59d41532014-12-16 23:37:551108 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301109
1110 // copy last element into empty spot at bottom of buffer
1111 self.copy(self.cap - 1, 0, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551112
1113 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301114 },
Piotr Czarnecki59d41532014-12-16 23:37:551115 (false, true, false) => unsafe {
1116 // discontiguous, insert closer to tail, head section:
Matt Murphy40f28c72014-12-03 17:12:301117 //
1118 // I H T
1119 // [o o o A o o o o o o . . . o o o]
1120 //
1121 // H T
1122 // [o o I A o o o o o o . . o o o o]
1123 // M M M M M M
1124
Matt Murphy40f28c72014-12-03 17:12:301125 // copy elements up to new tail
Piotr Czarnecki59d41532014-12-16 23:37:551126 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301127
1128 // copy last element into empty spot at bottom of buffer
1129 self.copy(self.cap - 1, 0, 1);
1130
1131 // move elements from idx-1 to end forward not including ^ element
1132 self.copy(0, 1, idx - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551133
1134 self.tail -= 1;
1135 },
1136 (false, false, false) => unsafe {
1137 // discontiguous, insert closer to head, head section:
Matt Murphy40f28c72014-12-03 17:12:301138 //
1139 // I H T
1140 // [o o o o A o o . . . . . . o o o]
1141 //
1142 // H T
1143 // [o o o o I A o o . . . . . o o o]
1144 // M M M
1145
Piotr Czarnecki59d41532014-12-16 23:37:551146 self.copy(idx + 1, idx, self.head - idx);
1147 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301148 }
1149 }
1150
1151 // tail might've been changed so we need to recalculate
Felix S. Klock IIe7c98612015-02-19 07:33:321152 let new_idx = self.wrap_add(self.tail, i);
Matt Murphy40f28c72014-12-03 17:12:301153 unsafe {
1154 self.buffer_write(new_idx, t);
1155 }
1156 }
Piotr Czarnecki59d41532014-12-16 23:37:551157
1158 /// Removes and returns the element at position `i` from the ringbuf.
1159 /// Whichever end is closer to the removal point will be moved to make
1160 /// room, and all the affected elements will be moved to new positions.
1161 /// Returns `None` if `i` is out of bounds.
1162 ///
Piotr Czarnecki156a1c32015-01-05 14:48:581163 /// # Examples
Joseph Crailfcf3f322015-03-13 02:42:381164 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551165 /// use std::collections::VecDeque;
Piotr Czarnecki59d41532014-12-16 23:37:551166 ///
Aaron Turon5fa9de12015-02-18 07:44:551167 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031168 /// buf.push_back(5);
1169 /// buf.push_back(10);
1170 /// buf.push_back(12);
Piotr Czarnecki59d41532014-12-16 23:37:551171 /// buf.push_back(15);
1172 /// buf.remove(2);
1173 /// assert_eq!(Some(&15), buf.get(2));
1174 /// ```
Brian Andersonb44ee372015-01-24 05:48:201175 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:191176 pub fn remove(&mut self, i: usize) -> Option<T> {
Piotr Czarnecki59d41532014-12-16 23:37:551177 if self.is_empty() || self.len() <= i {
1178 return None;
1179 }
1180
1181 // There are three main cases:
1182 // Elements are contiguous
1183 // Elements are discontiguous and the removal is in the tail section
1184 // Elements are discontiguous and the removal is in the head section
1185 // - special case when elements are technically contiguous,
1186 // but self.head = 0
1187 //
1188 // For each of those there are two more cases:
1189 // Insert is closer to tail
1190 // Insert is closer to head
1191 //
1192 // Key: H - self.head
1193 // T - self.tail
1194 // o - Valid element
1195 // x - Element marked for removal
1196 // R - Indicates element that is being removed
1197 // M - Indicates element was moved
1198
Felix S. Klock IIe7c98612015-02-19 07:33:321199 let idx = self.wrap_add(self.tail, i);
Piotr Czarnecki59d41532014-12-16 23:37:551200
1201 let elem = unsafe {
1202 Some(self.buffer_read(idx))
1203 };
1204
1205 let distance_to_tail = i;
1206 let distance_to_head = self.len() - i;
1207
Piotr Czarnecki156a1c32015-01-05 14:48:581208 let contiguous = self.is_contiguous();
Piotr Czarnecki59d41532014-12-16 23:37:551209
1210 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1211 (true, true, _) => unsafe {
1212 // contiguous, remove closer to tail:
1213 //
1214 // T R H
1215 // [. . . o o x o o o o . . . . . .]
1216 //
1217 // T H
1218 // [. . . . o o o o o o . . . . . .]
1219 // M M
1220
1221 self.copy(self.tail + 1, self.tail, i);
1222 self.tail += 1;
1223 },
1224 (true, false, _) => unsafe {
1225 // contiguous, remove closer to head:
1226 //
1227 // T R H
1228 // [. . . o o o o x o o . . . . . .]
1229 //
1230 // T H
1231 // [. . . o o o o o o . . . . . . .]
1232 // M M
1233
1234 self.copy(idx, idx + 1, self.head - idx - 1);
1235 self.head -= 1;
1236 },
1237 (false, true, true) => unsafe {
1238 // discontiguous, remove closer to tail, tail section:
1239 //
1240 // H T R
1241 // [o o o o o o . . . . . o o x o o]
1242 //
1243 // H T
1244 // [o o o o o o . . . . . . o o o o]
1245 // M M
1246
1247 self.copy(self.tail + 1, self.tail, i);
Felix S. Klock IIe7c98612015-02-19 07:33:321248 self.tail = self.wrap_add(self.tail, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551249 },
1250 (false, false, false) => unsafe {
1251 // discontiguous, remove closer to head, head section:
1252 //
1253 // R H T
1254 // [o o o o x o o . . . . . . o o o]
1255 //
1256 // H T
1257 // [o o o o o o . . . . . . . o o o]
1258 // M M
1259
1260 self.copy(idx, idx + 1, self.head - idx - 1);
1261 self.head -= 1;
1262 },
1263 (false, false, true) => unsafe {
1264 // discontiguous, remove closer to head, tail section:
1265 //
1266 // H T R
1267 // [o o o . . . . . . o o o o o x o]
1268 //
1269 // H T
1270 // [o o . . . . . . . o o o o o o o]
1271 // M M M M
1272 //
1273 // or quasi-discontiguous, remove next to head, tail section:
1274 //
1275 // H T R
1276 // [. . . . . . . . . o o o o o x o]
1277 //
1278 // T H
1279 // [. . . . . . . . . o o o o o o .]
1280 // M
1281
1282 // draw in elements in the tail section
1283 self.copy(idx, idx + 1, self.cap - idx - 1);
1284
1285 // Prevents underflow.
1286 if self.head != 0 {
1287 // copy first element into empty spot
1288 self.copy(self.cap - 1, 0, 1);
1289
1290 // move elements in the head section backwards
1291 self.copy(0, 1, self.head - 1);
1292 }
1293
Felix S. Klock IIe7c98612015-02-19 07:33:321294 self.head = self.wrap_sub(self.head, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551295 },
1296 (false, true, false) => unsafe {
1297 // discontiguous, remove closer to tail, head section:
1298 //
1299 // R H T
1300 // [o o x o o o o o o o . . . o o o]
1301 //
1302 // H T
1303 // [o o o o o o o o o o . . . . o o]
1304 // M M M M M
1305
1306 // draw in elements up to idx
1307 self.copy(1, 0, idx);
1308
1309 // copy last element into empty spot
1310 self.copy(0, self.cap - 1, 1);
1311
1312 // move elements from tail to end forward, excluding the last one
1313 self.copy(self.tail + 1, self.tail, self.cap - self.tail - 1);
1314
Felix S. Klock IIe7c98612015-02-19 07:33:321315 self.tail = self.wrap_add(self.tail, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551316 }
1317 }
1318
1319 return elem;
1320 }
Alexisdc930b12015-02-07 16:46:161321
1322 /// Splits the collection into two at the given index.
1323 ///
1324 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1325 /// and the returned `Self` contains elements `[at, len)`.
1326 ///
1327 /// Note that the capacity of `self` does not change.
1328 ///
1329 /// # Panics
1330 ///
1331 /// Panics if `at > len`
1332 ///
1333 /// # Examples
Alexis3c18bc42015-02-07 17:13:321334 ///
1335 /// ```
Brian Andersone9019102015-03-13 22:28:351336 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:551337 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321338 ///
Aaron Turon5fa9de12015-02-18 07:44:551339 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
Alexisdc930b12015-02-07 16:46:161340 /// let buf2 = buf.split_off(1);
1341 /// // buf = [1], buf2 = [2, 3]
1342 /// assert_eq!(buf.len(), 1);
1343 /// assert_eq!(buf2.len(), 2);
1344 /// ```
1345 #[inline]
1346 #[unstable(feature = "collections",
1347 reason = "new API, waiting for dust to settle")]
1348 pub fn split_off(&mut self, at: usize) -> Self {
1349 let len = self.len();
1350 assert!(at <= len, "`at` out of bounds");
1351
1352 let other_len = len - at;
Aaron Turon5fa9de12015-02-18 07:44:551353 let mut other = VecDeque::with_capacity(other_len);
Alexisdc930b12015-02-07 16:46:161354
1355 unsafe {
1356 let (first_half, second_half) = self.as_slices();
1357
1358 let first_len = first_half.len();
1359 let second_len = second_half.len();
1360 if at < first_len {
1361 // `at` lies in the first half.
1362 let amount_in_first = first_len - at;
1363
Alex Crichtonacd48a22015-03-27 18:12:281364 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1365 *other.ptr,
Alex Crichtonab456942015-02-23 19:39:161366 amount_in_first);
Alexisdc930b12015-02-07 16:46:161367
1368 // just take all of the second half.
Alex Crichtonacd48a22015-03-27 18:12:281369 ptr::copy_nonoverlapping(second_half.as_ptr(),
1370 other.ptr.offset(amount_in_first as isize),
Alex Crichtonab456942015-02-23 19:39:161371 second_len);
Alexisdc930b12015-02-07 16:46:161372 } else {
1373 // `at` lies in the second half, need to factor in the elements we skipped
1374 // in the first half.
1375 let offset = at - first_len;
1376 let amount_in_second = second_len - offset;
Alex Crichtonacd48a22015-03-27 18:12:281377 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1378 *other.ptr,
Alex Crichtonab456942015-02-23 19:39:161379 amount_in_second);
Alexisdc930b12015-02-07 16:46:161380 }
1381 }
1382
1383 // Cleanup where the ends of the buffers are
Felix S. Klock IIe7c98612015-02-19 07:33:321384 self.head = self.wrap_sub(self.head, other_len);
Alexisdc930b12015-02-07 16:46:161385 other.head = other.wrap_index(other_len);
1386
1387 other
1388 }
Alexis3c18bc42015-02-07 17:13:321389
1390 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1391 ///
1392 /// # Panics
1393 ///
1394 /// Panics if the new number of elements in self overflows a `usize`.
1395 ///
1396 /// # Examples
1397 ///
1398 /// ```
Brian Andersone9019102015-03-13 22:28:351399 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:551400 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321401 ///
Aaron Turon5fa9de12015-02-18 07:44:551402 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1403 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
Alexis3c18bc42015-02-07 17:13:321404 /// buf.append(&mut buf2);
1405 /// assert_eq!(buf.len(), 6);
1406 /// assert_eq!(buf2.len(), 0);
1407 /// ```
1408 #[inline]
1409 #[unstable(feature = "collections",
1410 reason = "new API, waiting for dust to settle")]
1411 pub fn append(&mut self, other: &mut Self) {
1412 // naive impl
1413 self.extend(other.drain());
1414 }
Jed Estep4f7a7422013-06-25 19:08:471415}
1416
Aaron Turon5fa9de12015-02-18 07:44:551417impl<T: Clone> VecDeque<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:581418 /// Modifies the ringbuf in-place so that `len()` is equal to new_len,
1419 /// either by removing excess elements or by appending copies of a value to the back.
1420 ///
1421 /// # Examples
1422 ///
1423 /// ```
Brian Andersone9019102015-03-13 22:28:351424 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:551425 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:581426 ///
Aaron Turon5fa9de12015-02-18 07:44:551427 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031428 /// buf.push_back(5);
1429 /// buf.push_back(10);
Piotr Czarnecki156a1c32015-01-05 14:48:581430 /// buf.push_back(15);
1431 /// buf.resize(2, 0);
1432 /// buf.resize(6, 20);
1433 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(buf.iter()) {
1434 /// assert_eq!(a, b);
1435 /// }
1436 /// ```
Brian Andersoncd6d9ea2015-01-23 02:22:031437 #[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:191438 reason = "matches collection reform specification; waiting on panic semantics")]
Alexise250fe32015-02-05 02:17:191439 pub fn resize(&mut self, new_len: usize, value: T) {
Piotr Czarnecki156a1c32015-01-05 14:48:581440 let len = self.len();
1441
1442 if new_len > len {
1443 self.extend(repeat(value).take(new_len - len))
1444 } else {
1445 self.truncate(new_len);
1446 }
1447 }
1448}
1449
Colin Sherratt7a666df2014-10-19 20:19:071450/// Returns the index in the underlying buffer for a given logical element index.
1451#[inline]
Alexise250fe32015-02-05 02:17:191452fn wrap_index(index: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071453 // size is always a power of 2
Colin Sherratt40191182014-11-12 01:22:071454 index & (size - 1)
Colin Sherratt7a666df2014-10-19 20:19:071455}
1456
1457/// Calculate the number of elements left to be read in the buffer
1458#[inline]
Alexise250fe32015-02-05 02:17:191459fn count(tail: usize, head: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071460 // size is always a power of 2
Felix S. Klock IIe7c98612015-02-19 07:33:321461 (head.wrapping_sub(tail)) & (size - 1)
Colin Sherratt7a666df2014-10-19 20:19:071462}
1463
Aaron Turon5fa9de12015-02-18 07:44:551464/// `VecDeque` iterator.
Brian Andersonb44ee372015-01-24 05:48:201465#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101466pub struct Iter<'a, T:'a> {
Colin Sherratt7a666df2014-10-19 20:19:071467 ring: &'a [T],
Alexise250fe32015-02-05 02:17:191468 tail: usize,
1469 head: usize
Niko Matsakis1b487a82014-08-28 01:46:521470}
1471
Jorge Aparicio351409a2015-01-04 03:54:181472// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
Huon Wilsonb7832ed2014-12-30 10:01:361473impl<'a, T> Clone for Iter<'a, T> {
1474 fn clone(&self) -> Iter<'a, T> {
1475 Iter {
1476 ring: self.ring,
1477 tail: self.tail,
1478 head: self.head
1479 }
1480 }
1481}
1482
Brian Andersonb44ee372015-01-24 05:48:201483#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351484impl<'a, T> Iterator for Iter<'a, T> {
1485 type Item = &'a T;
1486
Niko Matsakisbc4164d2013-11-16 22:29:391487 #[inline]
Erik Price5731ca32013-12-10 07:16:181488 fn next(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071489 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391490 return None;
1491 }
Colin Sherratt7a666df2014-10-19 20:19:071492 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:321493 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181494 unsafe { Some(self.ring.get_unchecked(tail)) }
Niko Matsakisbc4164d2013-11-16 22:29:391495 }
1496
1497 #[inline]
Alexise250fe32015-02-05 02:17:191498 fn size_hint(&self) -> (usize, Option<usize>) {
Colin Sherratt7a666df2014-10-19 20:19:071499 let len = count(self.tail, self.head, self.ring.len());
Niko Matsakisbc4164d2013-11-16 22:29:391500 (len, Some(len))
1501 }
1502}
1503
Brian Andersonb44ee372015-01-24 05:48:201504#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351505impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391506 #[inline]
Erik Price5731ca32013-12-10 07:16:181507 fn next_back(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071508 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391509 return None;
1510 }
Felix S. Klock IIe7c98612015-02-19 07:33:321511 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181512 unsafe { Some(self.ring.get_unchecked(self.head)) }
Niko Matsakisbc4164d2013-11-16 22:29:391513 }
1514}
Jed Estep35314c92013-06-26 15:38:291515
Brian Andersonb44ee372015-01-24 05:48:201516#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351517impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241518
Brian Andersonb44ee372015-01-24 05:48:201519#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351520impl<'a, T> RandomAccessIterator for Iter<'a, T> {
blake2-ppcf6862132013-07-29 18:16:261521 #[inline]
Alexise250fe32015-02-05 02:17:191522 fn indexable(&self) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071523 let (len, _) = self.size_hint();
1524 len
1525 }
blake2-ppcf6862132013-07-29 18:16:261526
1527 #[inline]
Alexise250fe32015-02-05 02:17:191528 fn idx(&mut self, j: usize) -> Option<&'a T> {
blake2-ppcf6862132013-07-29 18:16:261529 if j >= self.indexable() {
1530 None
1531 } else {
Felix S. Klock IIe7c98612015-02-19 07:33:321532 let idx = wrap_index(self.tail.wrapping_add(j), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181533 unsafe { Some(self.ring.get_unchecked(idx)) }
blake2-ppcf6862132013-07-29 18:16:261534 }
1535 }
1536}
1537
Aaron Turon5fa9de12015-02-18 07:44:551538/// `VecDeque` mutable iterator.
Brian Andersonb44ee372015-01-24 05:48:201539#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101540pub struct IterMut<'a, T:'a> {
Edward Wang101498c2015-02-25 10:11:231541 ring: &'a mut [T],
Alexise250fe32015-02-05 02:17:191542 tail: usize,
1543 head: usize,
Niko Matsakis1b487a82014-08-28 01:46:521544}
1545
Brian Andersonb44ee372015-01-24 05:48:201546#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351547impl<'a, T> Iterator for IterMut<'a, T> {
1548 type Item = &'a mut T;
1549
Niko Matsakisbc4164d2013-11-16 22:29:391550 #[inline]
Erik Price5731ca32013-12-10 07:16:181551 fn next(&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 }
Colin Sherratt7a666df2014-10-19 20:19:071555 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:321556 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111557
1558 unsafe {
Edward Wang101498c2015-02-25 10:11:231559 let elem = self.ring.get_unchecked_mut(tail);
1560 Some(&mut *(elem as *mut _))
Alex Crichton9d5d97b2014-10-15 06:05:011561 }
Niko Matsakisbc4164d2013-11-16 22:29:391562 }
1563
1564 #[inline]
Alexise250fe32015-02-05 02:17:191565 fn size_hint(&self) -> (usize, Option<usize>) {
Edward Wang101498c2015-02-25 10:11:231566 let len = count(self.tail, self.head, self.ring.len());
Colin Sherratt7a666df2014-10-19 20:19:071567 (len, Some(len))
Niko Matsakisbc4164d2013-11-16 22:29:391568 }
1569}
1570
Brian Andersonb44ee372015-01-24 05:48:201571#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351572impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391573 #[inline]
Erik Price5731ca32013-12-10 07:16:181574 fn next_back(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:071575 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391576 return None;
1577 }
Felix S. Klock IIe7c98612015-02-19 07:33:321578 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111579
1580 unsafe {
Edward Wang101498c2015-02-25 10:11:231581 let elem = self.ring.get_unchecked_mut(self.head);
1582 Some(&mut *(elem as *mut _))
Alexis Beingessner865c2db2014-11-23 02:34:111583 }
Niko Matsakisbc4164d2013-11-16 22:29:391584 }
1585}
Daniel Micayb47e1e92013-02-16 22:55:551586
Brian Andersonb44ee372015-01-24 05:48:201587#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351588impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241589
Aaron Turon5fa9de12015-02-18 07:44:551590/// A by-value VecDeque iterator
Andrew Paseltiner64532f72015-03-23 12:50:471591#[derive(Clone)]
Brian Andersonb44ee372015-01-24 05:48:201592#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101593pub struct IntoIter<T> {
Aaron Turon5fa9de12015-02-18 07:44:551594 inner: VecDeque<T>,
Alexis Beingessner865c2db2014-11-23 02:34:111595}
1596
Brian Andersonb44ee372015-01-24 05:48:201597#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351598impl<T> Iterator for IntoIter<T> {
1599 type Item = T;
1600
Alexis Beingessner865c2db2014-11-23 02:34:111601 #[inline]
1602 fn next(&mut self) -> Option<T> {
1603 self.inner.pop_front()
1604 }
1605
1606 #[inline]
Alexise250fe32015-02-05 02:17:191607 fn size_hint(&self) -> (usize, Option<usize>) {
Alexis Beingessner865c2db2014-11-23 02:34:111608 let len = self.inner.len();
1609 (len, Some(len))
1610 }
1611}
1612
Brian Andersonb44ee372015-01-24 05:48:201613#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351614impl<T> DoubleEndedIterator for IntoIter<T> {
Alexis Beingessner865c2db2014-11-23 02:34:111615 #[inline]
1616 fn next_back(&mut self) -> Option<T> {
1617 self.inner.pop_back()
1618 }
1619}
1620
Brian Andersonb44ee372015-01-24 05:48:201621#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351622impl<T> ExactSizeIterator for IntoIter<T> {}
Alexis Beingessner865c2db2014-11-23 02:34:111623
Aaron Turon5fa9de12015-02-18 07:44:551624/// A draining VecDeque iterator
Brian Andersoncd6d9ea2015-01-23 02:22:031625#[unstable(feature = "collections",
Brian Anderson94ca8a32015-01-13 02:40:191626 reason = "matches collection reform specification, waiting for dust to settle")]
Clark Gaebeld57f2592014-12-16 22:45:031627pub struct Drain<'a, T: 'a> {
Aaron Turon5fa9de12015-02-18 07:44:551628 inner: &'a mut VecDeque<T>,
Clark Gaebeld57f2592014-12-16 22:45:031629}
1630
1631#[unsafe_destructor]
Brian Andersonb44ee372015-01-24 05:48:201632#[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:031633impl<'a, T: 'a> Drop for Drain<'a, T> {
1634 fn drop(&mut self) {
Jorge Apariciof9865ea2015-01-11 02:50:071635 for _ in self.by_ref() {}
Clark Gaebeld57f2592014-12-16 22:45:031636 self.inner.head = 0;
1637 self.inner.tail = 0;
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> Iterator for Drain<'a, T> {
1643 type Item = T;
1644
Clark Gaebeld57f2592014-12-16 22:45:031645 #[inline]
1646 fn next(&mut self) -> Option<T> {
1647 self.inner.pop_front()
1648 }
1649
1650 #[inline]
Alexise250fe32015-02-05 02:17:191651 fn size_hint(&self) -> (usize, Option<usize>) {
Clark Gaebeld57f2592014-12-16 22:45:031652 let len = self.inner.len();
1653 (len, Some(len))
1654 }
1655}
1656
Brian Andersonb44ee372015-01-24 05:48:201657#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351658impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
Clark Gaebeld57f2592014-12-16 22:45:031659 #[inline]
1660 fn next_back(&mut self) -> Option<T> {
1661 self.inner.pop_back()
1662 }
1663}
1664
Brian Andersonb44ee372015-01-24 05:48:201665#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351666impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
Clark Gaebeld57f2592014-12-16 22:45:031667
Brian Andersonb44ee372015-01-24 05:48:201668#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551669impl<A: PartialEq> PartialEq for VecDeque<A> {
1670 fn eq(&self, other: &VecDeque<A>) -> bool {
Colin Sherratt7a666df2014-10-19 20:19:071671 self.len() == other.len() &&
blake2-ppc10c76982013-07-06 13:27:321672 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
1673 }
blake2-ppc10c76982013-07-06 13:27:321674}
1675
Brian Andersonb44ee372015-01-24 05:48:201676#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551677impl<A: Eq> Eq for VecDeque<A> {}
nham25acfde2014-08-01 20:05:031678
Brian Andersonb44ee372015-01-24 05:48:201679#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551680impl<A: PartialOrd> PartialOrd for VecDeque<A> {
1681 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
nham63615772014-07-27 03:18:561682 iter::order::partial_cmp(self.iter(), other.iter())
1683 }
1684}
1685
Brian Andersonb44ee372015-01-24 05:48:201686#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551687impl<A: Ord> Ord for VecDeque<A> {
nham3737c532014-08-01 20:22:481688 #[inline]
Aaron Turon5fa9de12015-02-18 07:44:551689 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
nham3737c532014-08-01 20:22:481690 iter::order::cmp(self.iter(), other.iter())
1691 }
1692}
1693
Brian Andersonb44ee372015-01-24 05:48:201694#[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton5a32b4a2015-02-18 22:34:081695impl<A: Hash> Hash for VecDeque<A> {
Alex Crichtonf83e23a2015-02-18 04:48:071696 fn hash<H: Hasher>(&self, state: &mut H) {
1697 self.len().hash(state);
1698 for elt in self {
1699 elt.hash(state);
1700 }
1701 }
1702}
nham1cfa6562014-07-27 02:33:471703
Brian Andersonb44ee372015-01-24 05:48:201704#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551705impl<A> Index<usize> for VecDeque<A> {
Jorge Aparicio32dd5922015-01-03 15:40:101706 type Output = A;
1707
Niko Matsakisb4d4daf2015-03-21 23:33:271708 #[inline]
1709 fn index(&self, i: usize) -> &A {
1710 self.get(i).expect("Out of bounds access")
1711 }
Jorge Aparicio32dd5922015-01-03 15:40:101712}
1713
Brian Andersonb44ee372015-01-24 05:48:201714#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551715impl<A> IndexMut<usize> for VecDeque<A> {
Niko Matsakisb4d4daf2015-03-21 23:33:271716 #[inline]
1717 fn index_mut(&mut self, i: usize) -> &mut A {
1718 self.get_mut(i).expect("Out of bounds access")
1719 }
Jorge Aparicio32dd5922015-01-03 15:40:101720}
1721
Brian Andersonb44ee372015-01-24 05:48:201722#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551723impl<A> FromIterator<A> for VecDeque<A> {
Alexis66613e22015-02-18 18:06:211724 fn from_iter<T: IntoIterator<Item=A>>(iterable: T) -> VecDeque<A> {
1725 let iterator = iterable.into_iter();
blake2-ppcf8ae5262013-07-30 00:06:491726 let (lower, _) = iterator.size_hint();
Aaron Turon5fa9de12015-02-18 07:44:551727 let mut deq = VecDeque::with_capacity(lower);
blake2-ppcf8ae5262013-07-30 00:06:491728 deq.extend(iterator);
blake2-ppc08dc72f2013-07-06 03:42:451729 deq
1730 }
1731}
1732
Alex Crichtoncc687862015-02-17 18:06:241733#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551734impl<T> IntoIterator for VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101735 type Item = T;
1736 type IntoIter = IntoIter<T>;
1737
1738 fn into_iter(self) -> IntoIter<T> {
1739 self.into_iter()
1740 }
1741}
1742
Alex Crichtoncc687862015-02-17 18:06:241743#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551744impl<'a, T> IntoIterator for &'a VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101745 type Item = &'a T;
1746 type IntoIter = Iter<'a, T>;
1747
1748 fn into_iter(self) -> Iter<'a, T> {
1749 self.iter()
1750 }
1751}
1752
Alex Crichtoncc687862015-02-17 18:06:241753#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551754impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101755 type Item = &'a mut T;
1756 type IntoIter = IterMut<'a, T>;
1757
1758 fn into_iter(mut self) -> IterMut<'a, T> {
1759 self.iter_mut()
1760 }
1761}
1762
Brian Andersonb44ee372015-01-24 05:48:201763#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551764impl<A> Extend<A> for VecDeque<A> {
Alexis4a9d1902015-02-18 15:04:301765 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
1766 for elt in iter {
Alexis Beingessnercf3b2e42014-11-06 17:24:471767 self.push_back(elt);
blake2-ppcf8ae5262013-07-30 00:06:491768 }
1769 }
1770}
1771
Brian Andersonb44ee372015-01-24 05:48:201772#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551773impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041774 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Tobias Bucher408f7b52015-02-10 21:12:131775 try!(write!(f, "["));
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041776
1777 for (i, e) in self.iter().enumerate() {
1778 if i != 0 { try!(write!(f, ", ")); }
Sean McArthur44440e52014-12-20 08:09:351779 try!(write!(f, "{:?}", *e));
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041780 }
1781
1782 write!(f, "]")
1783 }
1784}
Jorge Apariciocb5e4292015-03-12 00:44:021785
1786#[cfg(test)]
1787mod test {
Steven Facklerd502f422015-03-12 05:41:241788 use core::iter::{Iterator, self};
Jorge Apariciocb5e4292015-03-12 00:44:021789 use core::option::Option::Some;
1790
1791 use test;
1792
1793 use super::VecDeque;
1794
1795 #[bench]
1796 fn bench_push_back_100(b: &mut test::Bencher) {
1797 let mut deq = VecDeque::with_capacity(101);
1798 b.iter(|| {
1799 for i in 0..100 {
1800 deq.push_back(i);
1801 }
1802 deq.head = 0;
1803 deq.tail = 0;
1804 })
1805 }
1806
1807 #[bench]
1808 fn bench_push_front_100(b: &mut test::Bencher) {
1809 let mut deq = VecDeque::with_capacity(101);
1810 b.iter(|| {
1811 for i in 0..100 {
1812 deq.push_front(i);
1813 }
1814 deq.head = 0;
1815 deq.tail = 0;
1816 })
1817 }
1818
1819 #[bench]
1820 fn bench_pop_back_100(b: &mut test::Bencher) {
1821 let mut deq= VecDeque::<i32>::with_capacity(101);
1822
1823 b.iter(|| {
1824 deq.head = 100;
1825 deq.tail = 0;
1826 while !deq.is_empty() {
1827 test::black_box(deq.pop_back());
1828 }
1829 })
1830 }
1831
1832 #[bench]
1833 fn bench_pop_front_100(b: &mut test::Bencher) {
1834 let mut deq = VecDeque::<i32>::with_capacity(101);
1835
1836 b.iter(|| {
1837 deq.head = 100;
1838 deq.tail = 0;
1839 while !deq.is_empty() {
1840 test::black_box(deq.pop_front());
1841 }
1842 })
1843 }
1844
1845 #[test]
1846 fn test_swap_front_back_remove() {
1847 fn test(back: bool) {
1848 // This test checks that every single combination of tail position and length is tested.
1849 // Capacity 15 should be large enough to cover every case.
1850 let mut tester = VecDeque::with_capacity(15);
1851 let usable_cap = tester.capacity();
1852 let final_len = usable_cap / 2;
1853
1854 for len in 0..final_len {
1855 let expected = if back {
1856 (0..len).collect()
1857 } else {
1858 (0..len).rev().collect()
1859 };
1860 for tail_pos in 0..usable_cap {
1861 tester.tail = tail_pos;
1862 tester.head = tail_pos;
1863 if back {
1864 for i in 0..len * 2 {
1865 tester.push_front(i);
1866 }
1867 for i in 0..len {
1868 assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
1869 }
1870 } else {
1871 for i in 0..len * 2 {
1872 tester.push_back(i);
1873 }
1874 for i in 0..len {
1875 let idx = tester.len() - 1 - i;
1876 assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
1877 }
1878 }
1879 assert!(tester.tail < tester.cap);
1880 assert!(tester.head < tester.cap);
1881 assert_eq!(tester, expected);
1882 }
1883 }
1884 }
1885 test(true);
1886 test(false);
1887 }
1888
1889 #[test]
1890 fn test_insert() {
1891 // This test checks that every single combination of tail position, length, and
1892 // insertion position is tested. Capacity 15 should be large enough to cover every case.
1893
1894 let mut tester = VecDeque::with_capacity(15);
1895 // can't guarantee we got 15, so have to get what we got.
1896 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
1897 // this test isn't covering what it wants to
1898 let cap = tester.capacity();
1899
1900
1901 // len is the length *after* insertion
1902 for len in 1..cap {
1903 // 0, 1, 2, .., len - 1
1904 let expected = iter::count(0, 1).take(len).collect();
1905 for tail_pos in 0..cap {
1906 for to_insert in 0..len {
1907 tester.tail = tail_pos;
1908 tester.head = tail_pos;
1909 for i in 0..len {
1910 if i != to_insert {
1911 tester.push_back(i);
1912 }
1913 }
1914 tester.insert(to_insert, to_insert);
1915 assert!(tester.tail < tester.cap);
1916 assert!(tester.head < tester.cap);
1917 assert_eq!(tester, expected);
1918 }
1919 }
1920 }
1921 }
1922
1923 #[test]
1924 fn test_remove() {
1925 // This test checks that every single combination of tail position, length, and
1926 // removal position is tested. Capacity 15 should be large enough to cover every case.
1927
1928 let mut tester = VecDeque::with_capacity(15);
1929 // can't guarantee we got 15, so have to get what we got.
1930 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
1931 // this test isn't covering what it wants to
1932 let cap = tester.capacity();
1933
1934 // len is the length *after* removal
1935 for len in 0..cap - 1 {
1936 // 0, 1, 2, .., len - 1
1937 let expected = iter::count(0, 1).take(len).collect();
1938 for tail_pos in 0..cap {
1939 for to_remove in 0..len + 1 {
1940 tester.tail = tail_pos;
1941 tester.head = tail_pos;
1942 for i in 0..len {
1943 if i == to_remove {
1944 tester.push_back(1234);
1945 }
1946 tester.push_back(i);
1947 }
1948 if to_remove == len {
1949 tester.push_back(1234);
1950 }
1951 tester.remove(to_remove);
1952 assert!(tester.tail < tester.cap);
1953 assert!(tester.head < tester.cap);
1954 assert_eq!(tester, expected);
1955 }
1956 }
1957 }
1958 }
1959
1960 #[test]
1961 fn test_shrink_to_fit() {
1962 // This test checks that every single combination of head and tail position,
1963 // is tested. Capacity 15 should be large enough to cover every case.
1964
1965 let mut tester = VecDeque::with_capacity(15);
1966 // can't guarantee we got 15, so have to get what we got.
1967 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
1968 // this test isn't covering what it wants to
1969 let cap = tester.capacity();
1970 tester.reserve(63);
1971 let max_cap = tester.capacity();
1972
1973 for len in 0..cap + 1 {
1974 // 0, 1, 2, .., len - 1
1975 let expected = iter::count(0, 1).take(len).collect();
1976 for tail_pos in 0..max_cap + 1 {
1977 tester.tail = tail_pos;
1978 tester.head = tail_pos;
1979 tester.reserve(63);
1980 for i in 0..len {
1981 tester.push_back(i);
1982 }
1983 tester.shrink_to_fit();
1984 assert!(tester.capacity() <= cap);
1985 assert!(tester.tail < tester.cap);
1986 assert!(tester.head < tester.cap);
1987 assert_eq!(tester, expected);
1988 }
1989 }
1990 }
1991
1992 #[test]
1993 fn test_split_off() {
1994 // This test checks that every single combination of tail position, length, and
1995 // split position is tested. Capacity 15 should be large enough to cover every case.
1996
1997 let mut tester = VecDeque::with_capacity(15);
1998 // can't guarantee we got 15, so have to get what we got.
1999 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2000 // this test isn't covering what it wants to
2001 let cap = tester.capacity();
2002
2003 // len is the length *before* splitting
2004 for len in 0..cap {
2005 // index to split at
2006 for at in 0..len + 1 {
2007 // 0, 1, 2, .., at - 1 (may be empty)
2008 let expected_self = iter::count(0, 1).take(at).collect();
2009 // at, at + 1, .., len - 1 (may be empty)
2010 let expected_other = iter::count(at, 1).take(len - at).collect();
2011
2012 for tail_pos in 0..cap {
2013 tester.tail = tail_pos;
2014 tester.head = tail_pos;
2015 for i in 0..len {
2016 tester.push_back(i);
2017 }
2018 let result = tester.split_off(at);
2019 assert!(tester.tail < tester.cap);
2020 assert!(tester.head < tester.cap);
2021 assert!(result.tail < result.cap);
2022 assert!(result.head < result.cap);
2023 assert_eq!(tester, expected_self);
2024 assert_eq!(result, expected_other);
2025 }
2026 }
2027 }
2028 }
2029}