blob: c80fcfc5fedccd143fbc839ddd39a523042552c4 [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;
Alex Crichton6a585372014-05-30 01:50:1224use core::fmt;
Alex Crichton8f5b5f92015-04-17 21:31:3025use core::iter::{self, repeat, FromIterator, RandomAccessIterator};
Colin Sherratt7a666df2014-10-19 20:19:0726use core::mem;
Alex Crichton56290a02014-12-22 17:04:2327use core::ops::{Index, IndexMut};
Niko Matsakis8dbdcdb2015-02-12 15:38:4528use core::ptr::{self, Unique};
Oliver Schneider6584ae52015-03-13 08:56:1829use core::slice;
Alex Crichton998fece2013-05-06 04:42:5430
Alex Crichtonf83e23a2015-02-18 04:48:0731use core::hash::{Hash, Hasher};
Keegan McAllister67350bc2014-09-07 21:57:2632use core::cmp;
Colin Sherratt7a666df2014-10-19 20:19:0733
34use alloc::heap;
blake2-ppc70523712013-07-10 13:27:1435
Florian Zeitzf35f9732015-02-27 14:36:5336const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
37const MINIMUM_CAPACITY: usize = 1; // 2 - 1
Alexis Beingessnercf3b2e42014-11-06 17:24:4738
Aaron Turon5fa9de12015-02-18 07:44:5539/// `VecDeque` is a growable ring buffer, which can be used as a
40/// double-ended queue efficiently.
Brian Andersonb44ee372015-01-24 05:48:2041#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5542pub struct VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:0743 // tail and head are pointers into the buffer. Tail always points
44 // to the first element that could be read, Head always points
45 // to where data should be written.
46 // If tail == head the buffer is empty. The length of the ringbuf
47 // is defined as the distance between the two.
48
Alexise250fe32015-02-05 02:17:1949 tail: usize,
50 head: usize,
51 cap: usize,
Niko Matsakis8dbdcdb2015-02-12 15:38:4552 ptr: Unique<T>,
Colin Sherratt7a666df2014-10-19 20:19:0753}
54
Brian Andersonb44ee372015-01-24 05:48:2055#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5556impl<T: Clone> Clone for VecDeque<T> {
57 fn clone(&self) -> VecDeque<T> {
Alexise250fe32015-02-05 02:17:1958 self.iter().cloned().collect()
Colin Sherratt7a666df2014-10-19 20:19:0759 }
60}
61
Brian Andersonb44ee372015-01-24 05:48:2062#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5563impl<T> Drop for VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:0764 fn drop(&mut self) {
65 self.clear();
66 unsafe {
67 if mem::size_of::<T>() != 0 {
Niko Matsakis8dbdcdb2015-02-12 15:38:4568 heap::deallocate(*self.ptr as *mut u8,
Colin Sherratt7a666df2014-10-19 20:19:0769 self.cap * mem::size_of::<T>(),
70 mem::min_align_of::<T>())
71 }
72 }
73 }
Marijn Haverbeke26610db2012-01-11 11:49:3374}
Roy Frostig9c818892010-07-21 01:03:0975
Brian Andersonb44ee372015-01-24 05:48:2076#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5577impl<T> Default for VecDeque<T> {
Tom Jakubowskid6a39412014-06-09 07:30:0478 #[inline]
Aaron Turon5fa9de12015-02-18 07:44:5579 fn default() -> VecDeque<T> { VecDeque::new() }
Tom Jakubowskid6a39412014-06-09 07:30:0480}
81
Aaron Turon5fa9de12015-02-18 07:44:5582impl<T> VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:0783 /// Turn ptr into a slice
84 #[inline]
Alexis Beingessner8dbaa712014-12-31 00:07:5385 unsafe fn buffer_as_slice(&self) -> &[T] {
Oliver Schneider6584ae52015-03-13 08:56:1886 slice::from_raw_parts(*self.ptr, self.cap)
Clark Gaebel525f65e2014-12-16 04:01:5887 }
88
89 /// Turn ptr into a mut slice
90 #[inline]
Alexis Beingessner8dbaa712014-12-31 00:07:5391 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
Oliver Schneider6584ae52015-03-13 08:56:1892 slice::from_raw_parts_mut(*self.ptr, self.cap)
Colin Sherratt7a666df2014-10-19 20:19:0793 }
94
95 /// Moves an element out of the buffer
96 #[inline]
Alexise250fe32015-02-05 02:17:1997 unsafe fn buffer_read(&mut self, off: usize) -> T {
98 ptr::read(self.ptr.offset(off as isize))
Colin Sherratt7a666df2014-10-19 20:19:0799 }
100
101 /// Writes an element into the buffer, moving it.
102 #[inline]
Alexise250fe32015-02-05 02:17:19103 unsafe fn buffer_write(&mut self, off: usize, t: T) {
104 ptr::write(self.ptr.offset(off as isize), t);
Colin Sherratt7a666df2014-10-19 20:19:07105 }
106
107 /// Returns true iff the buffer is at capacity
108 #[inline]
109 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
Colin Sherratt40191182014-11-12 01:22:07110
Alex Crichton665ea962015-02-18 03:00:20111 /// Returns the index in the underlying buffer for a given logical element
112 /// index.
Colin Sherratt40191182014-11-12 01:22:07113 #[inline]
Alexise250fe32015-02-05 02:17:19114 fn wrap_index(&self, idx: usize) -> usize { wrap_index(idx, self.cap) }
Matt Murphy40f28c72014-12-03 17:12:30115
Felix S. Klock IIe7c98612015-02-19 07:33:32116 /// Returns the index in the underlying buffer for a given logical element
117 /// index + addend.
118 #[inline]
119 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
120 wrap_index(idx.wrapping_add(addend), self.cap)
121 }
122
123 /// Returns the index in the underlying buffer for a given logical element
124 /// index - subtrahend.
125 #[inline]
126 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
127 wrap_index(idx.wrapping_sub(subtrahend), self.cap)
128 }
129
Matt Murphy40f28c72014-12-03 17:12:30130 /// Copies a contiguous block of memory len long from src to dst
131 #[inline]
Alexise250fe32015-02-05 02:17:19132 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
Piotr Czarnecki59d41532014-12-16 23:37:55133 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
134 self.cap);
135 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
136 self.cap);
Alex Crichtonab456942015-02-23 19:39:16137 ptr::copy(
Alexise250fe32015-02-05 02:17:19138 self.ptr.offset(src as isize),
Alex Crichtonacd48a22015-03-27 18:12:28139 self.ptr.offset(dst as isize),
Piotr Czarnecki156a1c32015-01-05 14:48:58140 len);
141 }
142
143 /// Copies a contiguous block of memory len long from src to dst
144 #[inline]
Alexise250fe32015-02-05 02:17:19145 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
Piotr Czarnecki156a1c32015-01-05 14:48:58146 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
147 self.cap);
148 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
149 self.cap);
Alex Crichtonab456942015-02-23 19:39:16150 ptr::copy_nonoverlapping(
Alexise250fe32015-02-05 02:17:19151 self.ptr.offset(src as isize),
Alex Crichtonacd48a22015-03-27 18:12:28152 self.ptr.offset(dst as isize),
Piotr Czarnecki59d41532014-12-16 23:37:55153 len);
Matt Murphy40f28c72014-12-03 17:12:30154 }
Colin Sherratt7a666df2014-10-19 20:19:07155}
156
Aaron Turon5fa9de12015-02-18 07:44:55157impl<T> VecDeque<T> {
158 /// Creates an empty `VecDeque`.
Brian Andersonb44ee372015-01-24 05:48:20159 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55160 pub fn new() -> VecDeque<T> {
161 VecDeque::with_capacity(INITIAL_CAPACITY)
blake2-ppc70523712013-07-10 13:27:14162 }
163
Aaron Turon5fa9de12015-02-18 07:44:55164 /// Creates an empty `VecDeque` with space for at least `n` elements.
Brian Andersonb44ee372015-01-24 05:48:20165 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55166 pub fn with_capacity(n: usize) -> VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:07167 // +1 since the ringbuffer always leaves one space empty
Piotr Czarnecki156a1c32015-01-05 14:48:58168 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
169 assert!(cap > n, "capacity overflow");
Colin Sherratt6277e3b2014-11-14 09:21:44170 let size = cap.checked_mul(mem::size_of::<T>())
Colin Sherratt7a666df2014-10-19 20:19:07171 .expect("capacity overflow");
172
Niko Matsakis8dbdcdb2015-02-12 15:38:45173 let ptr = unsafe {
174 if mem::size_of::<T>() != 0 {
Colin Sherrattba24e332014-11-10 03:34:53175 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
176 if ptr.is_null() { ::alloc::oom() }
Niko Matsakis8dbdcdb2015-02-12 15:38:45177 Unique::new(ptr)
178 } else {
179 Unique::new(heap::EMPTY as *mut T)
Colin Sherrattba24e332014-11-10 03:34:53180 }
Colin Sherrattba24e332014-11-10 03:34:53181 };
182
Aaron Turon5fa9de12015-02-18 07:44:55183 VecDeque {
Colin Sherratt7a666df2014-10-19 20:19:07184 tail: 0,
185 head: 0,
186 cap: cap,
Niko Matsakis8dbdcdb2015-02-12 15:38:45187 ptr: ptr,
Colin Sherratt7a666df2014-10-19 20:19:07188 }
blake2-ppc70523712013-07-10 13:27:14189 }
190
Aaron Turon5fa9de12015-02-18 07:44:55191 /// Retrieves an element in the `VecDeque` by index.
blake2-ppc70523712013-07-10 13:27:14192 ///
jbranchaudc09defa2014-12-09 05:28:07193 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47194 ///
Joseph Crailfcf3f322015-03-13 02:42:38195 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55196 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47197 ///
Aaron Turon5fa9de12015-02-18 07:44:55198 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03199 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47200 /// buf.push_back(4);
201 /// buf.push_back(5);
202 /// assert_eq!(buf.get(1).unwrap(), &4);
203 /// ```
Brian Andersonb44ee372015-01-24 05:48:20204 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19205 pub fn get(&self, i: usize) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07206 if i < self.len() {
Felix S. Klock IIe7c98612015-02-19 07:33:32207 let idx = self.wrap_add(self.tail, i);
Alexise250fe32015-02-05 02:17:19208 unsafe { Some(&*self.ptr.offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07209 } else {
210 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47211 }
212 }
213
Aaron Turon5fa9de12015-02-18 07:44:55214 /// Retrieves an element in the `VecDeque` mutably by index.
nhamebe80972014-07-17 23:19:51215 ///
jbranchaudc09defa2014-12-09 05:28:07216 /// # Examples
nhamebe80972014-07-17 23:19:51217 ///
Joseph Crailfcf3f322015-03-13 02:42:38218 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55219 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51220 ///
Aaron Turon5fa9de12015-02-18 07:44:55221 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03222 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47223 /// buf.push_back(4);
224 /// buf.push_back(5);
Corey Farwell68d003c2015-04-18 16:45:05225 /// if let Some(elem) = buf.get_mut(1) {
226 /// *elem = 7;
Alexis Beingessnercf3b2e42014-11-06 17:24:47227 /// }
228 ///
P1startfd10d202014-08-02 06:39:39229 /// assert_eq!(buf[1], 7);
nhamebe80972014-07-17 23:19:51230 /// ```
Brian Andersonb44ee372015-01-24 05:48:20231 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19232 pub fn get_mut(&mut self, i: usize) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07233 if i < self.len() {
Felix S. Klock IIe7c98612015-02-19 07:33:32234 let idx = self.wrap_add(self.tail, i);
Alexise250fe32015-02-05 02:17:19235 unsafe { Some(&mut *self.ptr.offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07236 } else {
237 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47238 }
blake2-ppc70523712013-07-10 13:27:14239 }
240
P1startf2aa88c2014-08-04 10:48:39241 /// Swaps elements at indices `i` and `j`.
blake2-ppc57757a82013-09-26 07:19:26242 ///
243 /// `i` and `j` may be equal.
244 ///
P1startf2aa88c2014-08-04 10:48:39245 /// Fails if there is no element with either index.
nhamebe80972014-07-17 23:19:51246 ///
jbranchaudc09defa2014-12-09 05:28:07247 /// # Examples
nhamebe80972014-07-17 23:19:51248 ///
Joseph Crailfcf3f322015-03-13 02:42:38249 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55250 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51251 ///
Aaron Turon5fa9de12015-02-18 07:44:55252 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03253 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47254 /// buf.push_back(4);
255 /// buf.push_back(5);
nhamebe80972014-07-17 23:19:51256 /// buf.swap(0, 2);
P1startfd10d202014-08-02 06:39:39257 /// assert_eq!(buf[0], 5);
258 /// assert_eq!(buf[2], 3);
nhamebe80972014-07-17 23:19:51259 /// ```
Brian Andersonb44ee372015-01-24 05:48:20260 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19261 pub fn swap(&mut self, i: usize, j: usize) {
blake2-ppc57757a82013-09-26 07:19:26262 assert!(i < self.len());
263 assert!(j < self.len());
Felix S. Klock IIe7c98612015-02-19 07:33:32264 let ri = self.wrap_add(self.tail, i);
265 let rj = self.wrap_add(self.tail, j);
Colin Sherratt7a666df2014-10-19 20:19:07266 unsafe {
Alexise250fe32015-02-05 02:17:19267 ptr::swap(self.ptr.offset(ri as isize), self.ptr.offset(rj as isize))
Colin Sherratt7a666df2014-10-19 20:19:07268 }
blake2-ppc70523712013-07-10 13:27:14269 }
270
Aaron Turon5fa9de12015-02-18 07:44:55271 /// Returns the number of elements the `VecDeque` can hold without
Alexis Beingessnercf3b2e42014-11-06 17:24:47272 /// reallocating.
273 ///
jbranchaudc09defa2014-12-09 05:28:07274 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47275 ///
276 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55277 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47278 ///
Aaron Turon5fa9de12015-02-18 07:44:55279 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
Colin Sherratt7a666df2014-10-19 20:19:07280 /// assert!(buf.capacity() >= 10);
Alexis Beingessnercf3b2e42014-11-06 17:24:47281 /// ```
282 #[inline]
Brian Andersonb44ee372015-01-24 05:48:20283 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19284 pub fn capacity(&self) -> usize { self.cap - 1 }
Tim Chevalier77de84b2013-05-27 18:47:38285
Alexis Beingessnercf3b2e42014-11-06 17:24:47286 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
Aaron Turon5fa9de12015-02-18 07:44:55287 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
Tim Chevalier77de84b2013-05-27 18:47:38288 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47289 /// Note that the allocator may give the collection more space than it requests. Therefore
290 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
291 /// insertions are expected.
292 ///
293 /// # Panics
294 ///
Alexise250fe32015-02-05 02:17:19295 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47296 ///
jbranchaudc09defa2014-12-09 05:28:07297 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47298 ///
299 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55300 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47301 ///
Aaron Turon5fa9de12015-02-18 07:44:55302 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47303 /// buf.reserve_exact(10);
304 /// assert!(buf.capacity() >= 11);
305 /// ```
Brian Andersonb44ee372015-01-24 05:48:20306 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19307 pub fn reserve_exact(&mut self, additional: usize) {
Colin Sherratt7a666df2014-10-19 20:19:07308 self.reserve(additional);
Alexis Beingessnercf3b2e42014-11-06 17:24:47309 }
310
311 /// Reserves capacity for at least `additional` more elements to be inserted in the given
312 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
313 ///
314 /// # Panics
315 ///
Alexise250fe32015-02-05 02:17:19316 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47317 ///
jbranchaudc09defa2014-12-09 05:28:07318 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47319 ///
320 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55321 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47322 ///
Aaron Turon5fa9de12015-02-18 07:44:55323 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47324 /// buf.reserve(10);
325 /// assert!(buf.capacity() >= 11);
326 /// ```
Brian Andersonb44ee372015-01-24 05:48:20327 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19328 pub fn reserve(&mut self, additional: usize) {
Colin Sherratt7a666df2014-10-19 20:19:07329 let new_len = self.len() + additional;
330 assert!(new_len + 1 > self.len(), "capacity overflow");
331 if new_len > self.capacity() {
Colin Sherratt6277e3b2014-11-14 09:21:44332 let count = (new_len + 1).next_power_of_two();
Colin Sherratt7a666df2014-10-19 20:19:07333 assert!(count >= new_len + 1);
334
335 if mem::size_of::<T>() != 0 {
336 let old = self.cap * mem::size_of::<T>();
Colin Sherratt6277e3b2014-11-14 09:21:44337 let new = count.checked_mul(mem::size_of::<T>())
Colin Sherratt7a666df2014-10-19 20:19:07338 .expect("capacity overflow");
339 unsafe {
Niko Matsakis8dbdcdb2015-02-12 15:38:45340 let ptr = heap::reallocate(*self.ptr as *mut u8,
341 old,
342 new,
343 mem::min_align_of::<T>()) as *mut T;
344 if ptr.is_null() { ::alloc::oom() }
345 self.ptr = Unique::new(ptr);
Colin Sherratt7a666df2014-10-19 20:19:07346 }
347 }
348
349 // Move the shortest contiguous section of the ring buffer
350 // T H
351 // [o o o o o o o . ]
352 // T H
353 // A [o o o o o o o . . . . . . . . . ]
354 // H T
355 // [o o . o o o o o ]
356 // T H
357 // B [. . . o o o o o o o . . . . . . ]
358 // H T
359 // [o o o o o . o o ]
360 // H T
361 // C [o o o o o . . . . . . . . . o o ]
362
363 let oldcap = self.cap;
364 self.cap = count;
365
366 if self.tail <= self.head { // A
367 // Nop
368 } else if self.head < oldcap - self.tail { // B
369 unsafe {
Piotr Czarnecki156a1c32015-01-05 14:48:58370 self.copy_nonoverlapping(oldcap, 0, self.head);
Colin Sherratt7a666df2014-10-19 20:19:07371 }
372 self.head += oldcap;
Colin Sherratt4cae9ad2014-11-11 02:16:29373 debug_assert!(self.head > self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07374 } else { // C
Piotr Czarnecki156a1c32015-01-05 14:48:58375 let new_tail = count - (oldcap - self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07376 unsafe {
Piotr Czarnecki156a1c32015-01-05 14:48:58377 self.copy_nonoverlapping(new_tail, self.tail, oldcap - self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07378 }
Piotr Czarnecki156a1c32015-01-05 14:48:58379 self.tail = new_tail;
Colin Sherratt4cae9ad2014-11-11 02:16:29380 debug_assert!(self.head < self.tail);
Colin Sherratt7a666df2014-10-19 20:19:07381 }
Colin Sherratt4cae9ad2014-11-11 02:16:29382 debug_assert!(self.head < self.cap);
383 debug_assert!(self.tail < self.cap);
Colin Sherratt40191182014-11-12 01:22:07384 debug_assert!(self.cap.count_ones() == 1);
Colin Sherratt7a666df2014-10-19 20:19:07385 }
Tim Chevalier77de84b2013-05-27 18:47:38386 }
Jed Estep4f7a7422013-06-25 19:08:47387
Piotr Czarnecki156a1c32015-01-05 14:48:58388 /// Shrinks the capacity of the ringbuf as much as possible.
389 ///
390 /// It will drop down as close as possible to the length but the allocator may still inform the
391 /// ringbuf that there is space for a few more elements.
392 ///
393 /// # Examples
394 ///
395 /// ```
Brian Andersone9019102015-03-13 22:28:35396 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55397 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58398 ///
Aaron Turon5fa9de12015-02-18 07:44:55399 /// let mut buf = VecDeque::with_capacity(15);
Alexise15538d2015-02-06 18:57:13400 /// buf.extend(0..4);
Piotr Czarnecki156a1c32015-01-05 14:48:58401 /// assert_eq!(buf.capacity(), 15);
402 /// buf.shrink_to_fit();
403 /// assert!(buf.capacity() >= 4);
404 /// ```
405 pub fn shrink_to_fit(&mut self) {
406 // +1 since the ringbuffer always leaves one space empty
407 // len + 1 can't overflow for an existing, well-formed ringbuf.
408 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
409 if target_cap < self.cap {
410 // There are three cases of interest:
411 // All elements are out of desired bounds
412 // Elements are contiguous, and head is out of desired bounds
413 // Elements are discontiguous, and tail is out of desired bounds
414 //
415 // At all other times, element positions are unaffected.
416 //
417 // Indicates that elements at the head should be moved.
418 let head_outside = self.head == 0 || self.head >= target_cap;
419 // Move elements from out of desired bounds (positions after target_cap)
420 if self.tail >= target_cap && head_outside {
421 // T H
422 // [. . . . . . . . o o o o o o o . ]
423 // T H
424 // [o o o o o o o . ]
425 unsafe {
426 self.copy_nonoverlapping(0, self.tail, self.len());
427 }
428 self.head = self.len();
429 self.tail = 0;
430 } else if self.tail != 0 && self.tail < target_cap && head_outside {
431 // T H
432 // [. . . o o o o o o o . . . . . . ]
433 // H T
434 // [o o . o o o o o ]
Felix S. Klock IIe7c98612015-02-19 07:33:32435 let len = self.wrap_sub(self.head, target_cap);
Piotr Czarnecki156a1c32015-01-05 14:48:58436 unsafe {
437 self.copy_nonoverlapping(0, target_cap, len);
438 }
439 self.head = len;
440 debug_assert!(self.head < self.tail);
441 } else if self.tail >= target_cap {
442 // H T
443 // [o o o o o . . . . . . . . . o o ]
444 // H T
445 // [o o o o o . o o ]
Felix S. Klock IIe7c98612015-02-19 07:33:32446 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
Piotr Czarnecki156a1c32015-01-05 14:48:58447 let len = self.cap - self.tail;
448 let new_tail = target_cap - len;
449 unsafe {
450 self.copy_nonoverlapping(new_tail, self.tail, len);
451 }
452 self.tail = new_tail;
453 debug_assert!(self.head < self.tail);
454 }
455
456 if mem::size_of::<T>() != 0 {
457 let old = self.cap * mem::size_of::<T>();
458 let new_size = target_cap * mem::size_of::<T>();
459 unsafe {
Niko Matsakis8dbdcdb2015-02-12 15:38:45460 let ptr = heap::reallocate(*self.ptr as *mut u8,
461 old,
462 new_size,
463 mem::min_align_of::<T>()) as *mut T;
464 if ptr.is_null() { ::alloc::oom() }
465 self.ptr = Unique::new(ptr);
Piotr Czarnecki156a1c32015-01-05 14:48:58466 }
467 }
468 self.cap = target_cap;
469 debug_assert!(self.head < self.cap);
470 debug_assert!(self.tail < self.cap);
471 debug_assert!(self.cap.count_ones() == 1);
472 }
473 }
474
Andrew Paseltiner6fa16d62015-04-13 14:21:32475 /// Shortens a ringbuf, dropping excess elements from the back.
Piotr Czarnecki156a1c32015-01-05 14:48:58476 ///
477 /// If `len` is greater than the ringbuf's current length, this has no
478 /// effect.
479 ///
480 /// # Examples
481 ///
482 /// ```
Alex Crichtonce1a9652015-06-10 20:33:52483 /// # #![feature(deque_extras)]
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 /// ```
Alex Crichtond444d0c2015-06-09 21:39:23494 #[unstable(feature = "deque_extras",
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 ///
Joseph Crailfcf3f322015-03-13 02:42:38506 /// ```
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];
Emeliov Dmitriidf65f592015-03-30 16:22:46514 /// let c: Vec<&i32> = buf.iter().collect();
515 /// assert_eq!(&c[..], b);
nhamebe80972014-07-17 23:19:51516 /// ```
Brian Andersonb44ee372015-01-24 05:48:20517 #[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:10518 pub fn iter(&self) -> Iter<T> {
519 Iter {
Colin Sherratt7a666df2014-10-19 20:19:07520 tail: self.tail,
521 head: self.head,
522 ring: unsafe { self.buffer_as_slice() }
523 }
blake2-ppc3385e792013-07-15 23:13:26524 }
525
Andrew Wagner8fcc8322014-12-15 09:22:49526 /// Returns a front-to-back iterator that returns mutable references.
nhamebe80972014-07-17 23:19:51527 ///
jbranchaudc09defa2014-12-09 05:28:07528 /// # Examples
nhamebe80972014-07-17 23:19:51529 ///
Joseph Crailfcf3f322015-03-13 02:42:38530 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55531 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51532 ///
Aaron Turon5fa9de12015-02-18 07:44:55533 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03534 /// buf.push_back(5);
Alexis Beingessnercf3b2e42014-11-06 17:24:47535 /// buf.push_back(3);
536 /// buf.push_back(4);
Aaron Turonfc525ee2014-09-15 03:27:36537 /// for num in buf.iter_mut() {
nhamebe80972014-07-17 23:19:51538 /// *num = *num - 2;
539 /// }
Nick Cameron52ef4622014-08-06 09:59:40540 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
Alex Crichton77de3ee2015-03-26 16:57:58541 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
nhamebe80972014-07-17 23:19:51542 /// ```
Brian Andersonb44ee372015-01-24 05:48:20543 #[stable(feature = "rust1", since = "1.0.0")]
Alexis1420ceb2015-02-05 18:48:20544 pub fn iter_mut(&mut self) -> IterMut<T> {
Florian Wilkensf8cfd242014-12-19 20:52:10545 IterMut {
Colin Sherratt7a666df2014-10-19 20:19:07546 tail: self.tail,
547 head: self.head,
Edward Wang101498c2015-02-25 10:11:23548 ring: unsafe { self.buffer_as_mut_slice() },
Niko Matsakisbc4164d2013-11-16 22:29:39549 }
Jed Estep4f7a7422013-06-25 19:08:47550 }
Alex Crichton21ac9852014-10-30 20:43:24551
Clark Gaebel525f65e2014-12-16 04:01:58552 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55553 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58554 #[inline]
Alex Crichtond444d0c2015-06-09 21:39:23555 #[unstable(feature = "deque_extras",
Brian Anderson94ca8a32015-01-13 02:40:19556 reason = "matches collection reform specification, waiting for dust to settle")]
Alexis1420ceb2015-02-05 18:48:20557 pub fn as_slices(&self) -> (&[T], &[T]) {
Clark Gaebel525f65e2014-12-16 04:01:58558 unsafe {
559 let contiguous = self.is_contiguous();
560 let buf = self.buffer_as_slice();
561 if contiguous {
562 let (empty, buf) = buf.split_at(0);
Jorge Aparicio517f1cc2015-01-07 16:58:31563 (&buf[self.tail..self.head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58564 } else {
565 let (mid, right) = buf.split_at(self.tail);
566 let (left, _) = mid.split_at(self.head);
567 (right, left)
568 }
569 }
570 }
571
572 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55573 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58574 #[inline]
Alex Crichtond444d0c2015-06-09 21:39:23575 #[unstable(feature = "deque_extras",
Brian Anderson94ca8a32015-01-13 02:40:19576 reason = "matches collection reform specification, waiting for dust to settle")]
Alexis1420ceb2015-02-05 18:48:20577 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
Clark Gaebel525f65e2014-12-16 04:01:58578 unsafe {
579 let contiguous = self.is_contiguous();
580 let head = self.head;
581 let tail = self.tail;
582 let buf = self.buffer_as_mut_slice();
583
584 if contiguous {
585 let (empty, buf) = buf.split_at_mut(0);
Aaron Turona506d4c2015-01-18 00:15:52586 (&mut buf[tail .. head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58587 } else {
588 let (mid, right) = buf.split_at_mut(tail);
589 let (left, _) = mid.split_at_mut(head);
590
591 (right, left)
592 }
593 }
594 }
595
Aaron Turon5fa9de12015-02-18 07:44:55596 /// Returns the number of elements in the `VecDeque`.
Alex Crichton21ac9852014-10-30 20:43:24597 ///
jbranchaudc09defa2014-12-09 05:28:07598 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24599 ///
600 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55601 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24602 ///
Aaron Turon5fa9de12015-02-18 07:44:55603 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24604 /// assert_eq!(v.len(), 0);
Tobias Bucher7f64fe42015-01-25 21:05:03605 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24606 /// assert_eq!(v.len(), 1);
607 /// ```
Brian Andersonb44ee372015-01-24 05:48:20608 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19609 pub fn len(&self) -> usize { count(self.tail, self.head, self.cap) }
Alex Crichton21ac9852014-10-30 20:43:24610
611 /// Returns true if the buffer contains no elements
612 ///
jbranchaudc09defa2014-12-09 05:28:07613 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24614 ///
615 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55616 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24617 ///
Aaron Turon5fa9de12015-02-18 07:44:55618 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24619 /// assert!(v.is_empty());
Tobias Bucher7f64fe42015-01-25 21:05:03620 /// v.push_front(1);
Alex Crichton21ac9852014-10-30 20:43:24621 /// assert!(!v.is_empty());
622 /// ```
Brian Andersonb44ee372015-01-24 05:48:20623 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24624 pub fn is_empty(&self) -> bool { self.len() == 0 }
625
Aaron Turon5fa9de12015-02-18 07:44:55626 /// Creates a draining iterator that clears the `VecDeque` and iterates over
Clark Gaebeld57f2592014-12-16 22:45:03627 /// the removed items from start to end.
628 ///
629 /// # Examples
630 ///
631 /// ```
Alex Crichtonce1a9652015-06-10 20:33:52632 /// # #![feature(drain)]
Aaron Turon5fa9de12015-02-18 07:44:55633 /// use std::collections::VecDeque;
Clark Gaebeld57f2592014-12-16 22:45:03634 ///
Aaron Turon5fa9de12015-02-18 07:44:55635 /// let mut v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03636 /// v.push_back(1);
Clark Gaebeld57f2592014-12-16 22:45:03637 /// assert_eq!(v.drain().next(), Some(1));
638 /// assert!(v.is_empty());
639 /// ```
640 #[inline]
Alex Crichtond444d0c2015-06-09 21:39:23641 #[unstable(feature = "drain",
Brian Anderson94ca8a32015-01-13 02:40:19642 reason = "matches collection reform specification, waiting for dust to settle")]
Alexis Beingessner8dbaa712014-12-31 00:07:53643 pub fn drain(&mut self) -> Drain<T> {
Clark Gaebeld57f2592014-12-16 22:45:03644 Drain {
645 inner: self,
646 }
647 }
648
Alex Crichton21ac9852014-10-30 20:43:24649 /// Clears the buffer, removing all values.
650 ///
jbranchaudc09defa2014-12-09 05:28:07651 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24652 ///
653 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55654 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24655 ///
Aaron Turon5fa9de12015-02-18 07:44:55656 /// let mut v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03657 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24658 /// v.clear();
659 /// assert!(v.is_empty());
660 /// ```
Brian Andersonb44ee372015-01-24 05:48:20661 #[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:03662 #[inline]
Alex Crichton21ac9852014-10-30 20:43:24663 pub fn clear(&mut self) {
Clark Gaebeld57f2592014-12-16 22:45:03664 self.drain();
Alex Crichton21ac9852014-10-30 20:43:24665 }
666
667 /// Provides a reference to the front element, or `None` if the sequence is
668 /// empty.
669 ///
jbranchaudc09defa2014-12-09 05:28:07670 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24671 ///
672 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55673 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24674 ///
Aaron Turon5fa9de12015-02-18 07:44:55675 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24676 /// assert_eq!(d.front(), None);
677 ///
Tobias Bucher7f64fe42015-01-25 21:05:03678 /// d.push_back(1);
679 /// d.push_back(2);
680 /// assert_eq!(d.front(), Some(&1));
Alex Crichton21ac9852014-10-30 20:43:24681 /// ```
Brian Andersonb44ee372015-01-24 05:48:20682 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24683 pub fn front(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07684 if !self.is_empty() { Some(&self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24685 }
686
687 /// Provides a mutable reference to the front element, or `None` if the
688 /// sequence is empty.
689 ///
jbranchaudc09defa2014-12-09 05:28:07690 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24691 ///
692 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55693 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24694 ///
Aaron Turon5fa9de12015-02-18 07:44:55695 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24696 /// assert_eq!(d.front_mut(), None);
697 ///
Tobias Bucher7f64fe42015-01-25 21:05:03698 /// d.push_back(1);
699 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24700 /// match d.front_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03701 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24702 /// None => (),
703 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03704 /// assert_eq!(d.front(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24705 /// ```
Brian Andersonb44ee372015-01-24 05:48:20706 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24707 pub fn front_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07708 if !self.is_empty() { Some(&mut self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24709 }
710
711 /// Provides a reference to the back element, or `None` if the sequence is
712 /// empty.
713 ///
jbranchaudc09defa2014-12-09 05:28:07714 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24715 ///
716 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55717 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24718 ///
Aaron Turon5fa9de12015-02-18 07:44:55719 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24720 /// assert_eq!(d.back(), None);
721 ///
Tobias Bucher7f64fe42015-01-25 21:05:03722 /// d.push_back(1);
723 /// d.push_back(2);
724 /// assert_eq!(d.back(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24725 /// ```
Brian Andersonb44ee372015-01-24 05:48:20726 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24727 pub fn back(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07728 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24729 }
730
731 /// Provides a mutable reference to the back element, or `None` if the
732 /// sequence is empty.
733 ///
jbranchaudc09defa2014-12-09 05:28:07734 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24735 ///
736 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55737 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24738 ///
Aaron Turon5fa9de12015-02-18 07:44:55739 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24740 /// assert_eq!(d.back(), None);
741 ///
Tobias Bucher7f64fe42015-01-25 21:05:03742 /// d.push_back(1);
743 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24744 /// match d.back_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03745 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24746 /// None => (),
747 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03748 /// assert_eq!(d.back(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24749 /// ```
Brian Andersonb44ee372015-01-24 05:48:20750 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24751 pub fn back_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07752 let len = self.len();
753 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24754 }
755
756 /// Removes the first element and returns it, or `None` if the sequence is
757 /// empty.
758 ///
jbranchaudc09defa2014-12-09 05:28:07759 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24760 ///
761 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55762 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24763 ///
Aaron Turon5fa9de12015-02-18 07:44:55764 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03765 /// d.push_back(1);
766 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24767 ///
Tobias Bucher7f64fe42015-01-25 21:05:03768 /// assert_eq!(d.pop_front(), Some(1));
769 /// assert_eq!(d.pop_front(), Some(2));
Alex Crichton21ac9852014-10-30 20:43:24770 /// assert_eq!(d.pop_front(), None);
771 /// ```
Brian Andersonb44ee372015-01-24 05:48:20772 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24773 pub fn pop_front(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07774 if self.is_empty() {
775 None
776 } else {
777 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:32778 self.tail = self.wrap_add(self.tail, 1);
Colin Sherratt7a666df2014-10-19 20:19:07779 unsafe { Some(self.buffer_read(tail)) }
Alex Crichton21ac9852014-10-30 20:43:24780 }
Alex Crichton21ac9852014-10-30 20:43:24781 }
782
783 /// Inserts an element first in the sequence.
784 ///
jbranchaudc09defa2014-12-09 05:28:07785 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24786 ///
787 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55788 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24789 ///
Aaron Turon5fa9de12015-02-18 07:44:55790 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03791 /// d.push_front(1);
792 /// d.push_front(2);
793 /// assert_eq!(d.front(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24794 /// ```
Brian Andersonb44ee372015-01-24 05:48:20795 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24796 pub fn push_front(&mut self, t: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29797 if self.is_full() {
798 self.reserve(1);
799 debug_assert!(!self.is_full());
800 }
Colin Sherratt7a666df2014-10-19 20:19:07801
Felix S. Klock IIe7c98612015-02-19 07:33:32802 self.tail = self.wrap_sub(self.tail, 1);
Colin Sherratt7a666df2014-10-19 20:19:07803 let tail = self.tail;
804 unsafe { self.buffer_write(tail, t); }
Alex Crichton21ac9852014-10-30 20:43:24805 }
806
807 /// Appends an element to the back of a buffer
808 ///
jbranchaudc09defa2014-12-09 05:28:07809 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24810 ///
Joseph Crailfcf3f322015-03-13 02:42:38811 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55812 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24813 ///
Aaron Turon5fa9de12015-02-18 07:44:55814 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03815 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:47816 /// buf.push_back(3);
Alex Crichton21ac9852014-10-30 20:43:24817 /// assert_eq!(3, *buf.back().unwrap());
818 /// ```
Brian Andersonb44ee372015-01-24 05:48:20819 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnercf3b2e42014-11-06 17:24:47820 pub fn push_back(&mut self, t: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29821 if self.is_full() {
822 self.reserve(1);
823 debug_assert!(!self.is_full());
824 }
Colin Sherratt7a666df2014-10-19 20:19:07825
826 let head = self.head;
Felix S. Klock IIe7c98612015-02-19 07:33:32827 self.head = self.wrap_add(self.head, 1);
Colin Sherratt7a666df2014-10-19 20:19:07828 unsafe { self.buffer_write(head, t) }
Alex Crichton21ac9852014-10-30 20:43:24829 }
830
831 /// Removes the last element from a buffer and returns it, or `None` if
832 /// it is empty.
833 ///
jbranchaudc09defa2014-12-09 05:28:07834 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24835 ///
Joseph Crailfcf3f322015-03-13 02:42:38836 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55837 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24838 ///
Aaron Turon5fa9de12015-02-18 07:44:55839 /// let mut buf = VecDeque::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47840 /// assert_eq!(buf.pop_back(), None);
Tobias Bucher7f64fe42015-01-25 21:05:03841 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:47842 /// buf.push_back(3);
843 /// assert_eq!(buf.pop_back(), Some(3));
Alex Crichton21ac9852014-10-30 20:43:24844 /// ```
Brian Andersonb44ee372015-01-24 05:48:20845 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnercf3b2e42014-11-06 17:24:47846 pub fn pop_back(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07847 if self.is_empty() {
Alex Crichton21ac9852014-10-30 20:43:24848 None
Colin Sherratt7a666df2014-10-19 20:19:07849 } else {
Felix S. Klock IIe7c98612015-02-19 07:33:32850 self.head = self.wrap_sub(self.head, 1);
Colin Sherratt7a666df2014-10-19 20:19:07851 let head = self.head;
852 unsafe { Some(self.buffer_read(head)) }
Alex Crichton21ac9852014-10-30 20:43:24853 }
854 }
Matt Murphy40f28c72014-12-03 17:12:30855
Clark Gaebel525f65e2014-12-16 04:01:58856 #[inline]
857 fn is_contiguous(&self) -> bool {
858 self.tail <= self.head
859 }
860
Piotr Czarnecki156a1c32015-01-05 14:48:58861 /// Removes an element from anywhere in the ringbuf and returns it, replacing it with the last
862 /// element.
863 ///
864 /// This does not preserve ordering, but is O(1).
865 ///
866 /// Returns `None` if `index` is out of bounds.
867 ///
868 /// # Examples
869 ///
870 /// ```
Alex Crichtonce1a9652015-06-10 20:33:52871 /// # #![feature(deque_extras)]
Aaron Turon5fa9de12015-02-18 07:44:55872 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58873 ///
Aaron Turon5fa9de12015-02-18 07:44:55874 /// let mut buf = VecDeque::new();
Piotr Czarnecki156a1c32015-01-05 14:48:58875 /// assert_eq!(buf.swap_back_remove(0), None);
Tobias Bucher7f64fe42015-01-25 21:05:03876 /// buf.push_back(5);
Piotr Czarnecki156a1c32015-01-05 14:48:58877 /// buf.push_back(99);
878 /// buf.push_back(15);
879 /// buf.push_back(20);
880 /// buf.push_back(10);
881 /// assert_eq!(buf.swap_back_remove(1), Some(99));
882 /// ```
Alex Crichtond444d0c2015-06-09 21:39:23883 #[unstable(feature = "deque_extras",
Brian Anderson94ca8a32015-01-13 02:40:19884 reason = "the naming of this function may be altered")]
Alexise250fe32015-02-05 02:17:19885 pub fn swap_back_remove(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:58886 let length = self.len();
887 if length > 0 && index < length - 1 {
888 self.swap(index, length - 1);
889 } else if index >= length {
890 return None;
891 }
892 self.pop_back()
893 }
894
Alex Crichtonce1a9652015-06-10 20:33:52895 /// Removes an element from anywhere in the ringbuf and returns it,
896 /// replacing it with the first element.
Piotr Czarnecki156a1c32015-01-05 14:48:58897 ///
898 /// This does not preserve ordering, but is O(1).
899 ///
900 /// Returns `None` if `index` is out of bounds.
901 ///
902 /// # Examples
903 ///
904 /// ```
Alex Crichtonce1a9652015-06-10 20:33:52905 /// # #![feature(deque_extras)]
Aaron Turon5fa9de12015-02-18 07:44:55906 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58907 ///
Aaron Turon5fa9de12015-02-18 07:44:55908 /// let mut buf = VecDeque::new();
Piotr Czarnecki156a1c32015-01-05 14:48:58909 /// assert_eq!(buf.swap_front_remove(0), None);
Tobias Bucher7f64fe42015-01-25 21:05:03910 /// buf.push_back(15);
Piotr Czarnecki156a1c32015-01-05 14:48:58911 /// buf.push_back(5);
912 /// buf.push_back(10);
913 /// buf.push_back(99);
Tobias Bucher7f64fe42015-01-25 21:05:03914 /// buf.push_back(20);
Piotr Czarnecki156a1c32015-01-05 14:48:58915 /// assert_eq!(buf.swap_front_remove(3), Some(99));
916 /// ```
Alex Crichtond444d0c2015-06-09 21:39:23917 #[unstable(feature = "deque_extras",
Brian Anderson94ca8a32015-01-13 02:40:19918 reason = "the naming of this function may be altered")]
Alexise250fe32015-02-05 02:17:19919 pub fn swap_front_remove(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:58920 let length = self.len();
921 if length > 0 && index < length && index != 0 {
922 self.swap(index, 0);
923 } else if index >= length {
924 return None;
925 }
926 self.pop_front()
927 }
928
Matt Murphy40f28c72014-12-03 17:12:30929 /// Inserts an element at position `i` within the ringbuf. Whichever
930 /// end is closer to the insertion point will be moved to make room,
931 /// and all the affected elements will be moved to new positions.
932 ///
933 /// # Panics
934 ///
935 /// Panics if `i` is greater than ringbuf's length
936 ///
Piotr Czarnecki156a1c32015-01-05 14:48:58937 /// # Examples
Joseph Crailfcf3f322015-03-13 02:42:38938 /// ```
Brian Andersone9019102015-03-13 22:28:35939 /// # #![feature(collections)]
Aaron Turon5fa9de12015-02-18 07:44:55940 /// use std::collections::VecDeque;
Matt Murphy40f28c72014-12-03 17:12:30941 ///
Aaron Turon5fa9de12015-02-18 07:44:55942 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03943 /// buf.push_back(10);
Matt Murphy40f28c72014-12-03 17:12:30944 /// buf.push_back(12);
945 /// buf.insert(1,11);
946 /// assert_eq!(Some(&11), buf.get(1));
947 /// ```
Alexise250fe32015-02-05 02:17:19948 pub fn insert(&mut self, i: usize, t: T) {
Matt Murphy40f28c72014-12-03 17:12:30949 assert!(i <= self.len(), "index out of bounds");
950 if self.is_full() {
951 self.reserve(1);
952 debug_assert!(!self.is_full());
953 }
954
955 // Move the least number of elements in the ring buffer and insert
956 // the given object
957 //
958 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
959 //
960 // There are three main cases:
961 // Elements are contiguous
962 // - special case when tail is 0
963 // Elements are discontiguous and the insert is in the tail section
964 // Elements are discontiguous and the insert is in the head section
965 //
966 // For each of those there are two more cases:
967 // Insert is closer to tail
968 // Insert is closer to head
969 //
970 // Key: H - self.head
971 // T - self.tail
972 // o - Valid element
973 // I - Insertion element
974 // A - The element that should be after the insertion point
975 // M - Indicates element was moved
976
Felix S. Klock IIe7c98612015-02-19 07:33:32977 let idx = self.wrap_add(self.tail, i);
Matt Murphy40f28c72014-12-03 17:12:30978
979 let distance_to_tail = i;
980 let distance_to_head = self.len() - i;
981
Clark Gaebel525f65e2014-12-16 04:01:58982 let contiguous = self.is_contiguous();
Matt Murphy40f28c72014-12-03 17:12:30983
984 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
985 (true, true, _) if i == 0 => {
986 // push_front
987 //
988 // T
989 // I H
990 // [A o o o o o o . . . . . . . . .]
991 //
992 // H T
993 // [A o o o o o o o . . . . . I]
994 //
995
Felix S. Klock IIe7c98612015-02-19 07:33:32996 self.tail = self.wrap_sub(self.tail, 1);
Matt Murphy40f28c72014-12-03 17:12:30997 },
Piotr Czarnecki59d41532014-12-16 23:37:55998 (true, true, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:30999 // contiguous, insert closer to tail:
1000 //
1001 // T I H
1002 // [. . . o o A o o o o . . . . . .]
1003 //
1004 // T H
1005 // [. . o o I A o o o o . . . . . .]
1006 // M M
1007 //
1008 // contiguous, insert closer to tail and tail is 0:
1009 //
1010 //
1011 // T I H
1012 // [o o A o o o o . . . . . . . . .]
1013 //
1014 // H T
1015 // [o I A o o o o o . . . . . . . o]
1016 // M M
1017
Felix S. Klock IIe7c98612015-02-19 07:33:321018 let new_tail = self.wrap_sub(self.tail, 1);
Matt Murphy40f28c72014-12-03 17:12:301019
Piotr Czarnecki59d41532014-12-16 23:37:551020 self.copy(new_tail, self.tail, 1);
1021 // Already moved the tail, so we only copy `i - 1` elements.
1022 self.copy(self.tail, self.tail + 1, i - 1);
1023
1024 self.tail = new_tail;
Matt Murphy40f28c72014-12-03 17:12:301025 },
Piotr Czarnecki59d41532014-12-16 23:37:551026 (true, false, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:301027 // contiguous, insert closer to head:
1028 //
1029 // T I H
1030 // [. . . o o o o A o o . . . . . .]
1031 //
1032 // T H
1033 // [. . . o o o o I A o o . . . . .]
1034 // M M M
1035
Piotr Czarnecki59d41532014-12-16 23:37:551036 self.copy(idx + 1, idx, self.head - idx);
Felix S. Klock IIe7c98612015-02-19 07:33:321037 self.head = self.wrap_add(self.head, 1);
Matt Murphy40f28c72014-12-03 17:12:301038 },
Piotr Czarnecki59d41532014-12-16 23:37:551039 (false, true, true) => unsafe {
1040 // discontiguous, insert closer to tail, tail section:
Matt Murphy40f28c72014-12-03 17:12:301041 //
1042 // H T I
1043 // [o o o o o o . . . . . o o A o o]
1044 //
1045 // H T
1046 // [o o o o o o . . . . o o I A o o]
1047 // M M
1048
Piotr Czarnecki59d41532014-12-16 23:37:551049 self.copy(self.tail - 1, self.tail, i);
1050 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301051 },
Piotr Czarnecki59d41532014-12-16 23:37:551052 (false, false, true) => unsafe {
1053 // discontiguous, insert closer to head, tail section:
Matt Murphy40f28c72014-12-03 17:12:301054 //
1055 // H T I
1056 // [o o . . . . . . . o o o o o A o]
1057 //
1058 // H T
1059 // [o o o . . . . . . o o o o o I A]
1060 // M M M M
1061
Matt Murphy40f28c72014-12-03 17:12:301062 // copy elements up to new head
Piotr Czarnecki59d41532014-12-16 23:37:551063 self.copy(1, 0, self.head);
Matt Murphy40f28c72014-12-03 17:12:301064
1065 // copy last element into empty spot at bottom of buffer
1066 self.copy(0, self.cap - 1, 1);
1067
1068 // move elements from idx to end forward not including ^ element
1069 self.copy(idx + 1, idx, self.cap - 1 - idx);
Piotr Czarnecki59d41532014-12-16 23:37:551070
1071 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301072 },
Piotr Czarnecki59d41532014-12-16 23:37:551073 (false, true, false) if idx == 0 => unsafe {
1074 // discontiguous, insert is closer to tail, head section,
Matt Murphy40f28c72014-12-03 17:12:301075 // and is at index zero in the internal buffer:
1076 //
1077 // I H T
1078 // [A o o o o o o o o o . . . o o o]
1079 //
1080 // H T
1081 // [A o o o o o o o o o . . o o o I]
1082 // M M M
1083
Matt Murphy40f28c72014-12-03 17:12:301084 // copy elements up to new tail
Piotr Czarnecki59d41532014-12-16 23:37:551085 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301086
1087 // copy last element into empty spot at bottom of buffer
1088 self.copy(self.cap - 1, 0, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551089
1090 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301091 },
Piotr Czarnecki59d41532014-12-16 23:37:551092 (false, true, false) => unsafe {
1093 // discontiguous, insert closer to tail, head section:
Matt Murphy40f28c72014-12-03 17:12:301094 //
1095 // I H T
1096 // [o o o A o o o o o o . . . o o o]
1097 //
1098 // H T
1099 // [o o I A o o o o o o . . o o o o]
1100 // M M M M M M
1101
Matt Murphy40f28c72014-12-03 17:12:301102 // copy elements up to new tail
Piotr Czarnecki59d41532014-12-16 23:37:551103 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301104
1105 // copy last element into empty spot at bottom of buffer
1106 self.copy(self.cap - 1, 0, 1);
1107
1108 // move elements from idx-1 to end forward not including ^ element
1109 self.copy(0, 1, idx - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551110
1111 self.tail -= 1;
1112 },
1113 (false, false, false) => unsafe {
1114 // discontiguous, insert closer to head, head section:
Matt Murphy40f28c72014-12-03 17:12:301115 //
1116 // I H T
1117 // [o o o o A o o . . . . . . o o o]
1118 //
1119 // H T
1120 // [o o o o I A o o . . . . . o o o]
1121 // M M M
1122
Piotr Czarnecki59d41532014-12-16 23:37:551123 self.copy(idx + 1, idx, self.head - idx);
1124 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301125 }
1126 }
1127
1128 // tail might've been changed so we need to recalculate
Felix S. Klock IIe7c98612015-02-19 07:33:321129 let new_idx = self.wrap_add(self.tail, i);
Matt Murphy40f28c72014-12-03 17:12:301130 unsafe {
1131 self.buffer_write(new_idx, t);
1132 }
1133 }
Piotr Czarnecki59d41532014-12-16 23:37:551134
1135 /// Removes and returns the element at position `i` from the ringbuf.
1136 /// Whichever end is closer to the removal point will be moved to make
1137 /// room, and all the affected elements will be moved to new positions.
1138 /// Returns `None` if `i` is out of bounds.
1139 ///
Piotr Czarnecki156a1c32015-01-05 14:48:581140 /// # Examples
Joseph Crailfcf3f322015-03-13 02:42:381141 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551142 /// use std::collections::VecDeque;
Piotr Czarnecki59d41532014-12-16 23:37:551143 ///
Aaron Turon5fa9de12015-02-18 07:44:551144 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031145 /// buf.push_back(5);
1146 /// buf.push_back(10);
1147 /// buf.push_back(12);
Piotr Czarnecki59d41532014-12-16 23:37:551148 /// buf.push_back(15);
1149 /// buf.remove(2);
1150 /// assert_eq!(Some(&15), buf.get(2));
1151 /// ```
Brian Andersonb44ee372015-01-24 05:48:201152 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:191153 pub fn remove(&mut self, i: usize) -> Option<T> {
Piotr Czarnecki59d41532014-12-16 23:37:551154 if self.is_empty() || self.len() <= i {
1155 return None;
1156 }
1157
1158 // There are three main cases:
1159 // Elements are contiguous
1160 // Elements are discontiguous and the removal is in the tail section
1161 // Elements are discontiguous and the removal is in the head section
1162 // - special case when elements are technically contiguous,
1163 // but self.head = 0
1164 //
1165 // For each of those there are two more cases:
1166 // Insert is closer to tail
1167 // Insert is closer to head
1168 //
1169 // Key: H - self.head
1170 // T - self.tail
1171 // o - Valid element
1172 // x - Element marked for removal
1173 // R - Indicates element that is being removed
1174 // M - Indicates element was moved
1175
Felix S. Klock IIe7c98612015-02-19 07:33:321176 let idx = self.wrap_add(self.tail, i);
Piotr Czarnecki59d41532014-12-16 23:37:551177
1178 let elem = unsafe {
1179 Some(self.buffer_read(idx))
1180 };
1181
1182 let distance_to_tail = i;
1183 let distance_to_head = self.len() - i;
1184
Piotr Czarnecki156a1c32015-01-05 14:48:581185 let contiguous = self.is_contiguous();
Piotr Czarnecki59d41532014-12-16 23:37:551186
1187 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1188 (true, true, _) => unsafe {
1189 // contiguous, remove closer to tail:
1190 //
1191 // T R H
1192 // [. . . o o x o o o o . . . . . .]
1193 //
1194 // T H
1195 // [. . . . o o o o o o . . . . . .]
1196 // M M
1197
1198 self.copy(self.tail + 1, self.tail, i);
1199 self.tail += 1;
1200 },
1201 (true, false, _) => unsafe {
1202 // contiguous, remove closer to head:
1203 //
1204 // T R H
1205 // [. . . o o o o x o o . . . . . .]
1206 //
1207 // T H
1208 // [. . . o o o o o o . . . . . . .]
1209 // M M
1210
1211 self.copy(idx, idx + 1, self.head - idx - 1);
1212 self.head -= 1;
1213 },
1214 (false, true, true) => unsafe {
1215 // discontiguous, remove closer to tail, tail section:
1216 //
1217 // H T R
1218 // [o o o o o o . . . . . o o x o o]
1219 //
1220 // H T
1221 // [o o o o o o . . . . . . o o o o]
1222 // M M
1223
1224 self.copy(self.tail + 1, self.tail, i);
Felix S. Klock IIe7c98612015-02-19 07:33:321225 self.tail = self.wrap_add(self.tail, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551226 },
1227 (false, false, false) => unsafe {
1228 // discontiguous, remove closer to head, head section:
1229 //
1230 // R H T
1231 // [o o o o x o o . . . . . . o o o]
1232 //
1233 // H T
1234 // [o o o o o o . . . . . . . o o o]
1235 // M M
1236
1237 self.copy(idx, idx + 1, self.head - idx - 1);
1238 self.head -= 1;
1239 },
1240 (false, false, true) => unsafe {
1241 // discontiguous, remove closer to head, tail section:
1242 //
1243 // H T R
1244 // [o o o . . . . . . o o o o o x o]
1245 //
1246 // H T
1247 // [o o . . . . . . . o o o o o o o]
1248 // M M M M
1249 //
1250 // or quasi-discontiguous, remove next to head, tail section:
1251 //
1252 // H T R
1253 // [. . . . . . . . . o o o o o x o]
1254 //
1255 // T H
1256 // [. . . . . . . . . o o o o o o .]
1257 // M
1258
1259 // draw in elements in the tail section
1260 self.copy(idx, idx + 1, self.cap - idx - 1);
1261
1262 // Prevents underflow.
1263 if self.head != 0 {
1264 // copy first element into empty spot
1265 self.copy(self.cap - 1, 0, 1);
1266
1267 // move elements in the head section backwards
1268 self.copy(0, 1, self.head - 1);
1269 }
1270
Felix S. Klock IIe7c98612015-02-19 07:33:321271 self.head = self.wrap_sub(self.head, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551272 },
1273 (false, true, false) => unsafe {
1274 // discontiguous, remove closer to tail, head section:
1275 //
1276 // R H T
1277 // [o o x o o o o o o o . . . o o o]
1278 //
1279 // H T
1280 // [o o o o o o o o o o . . . . o o]
1281 // M M M M M
1282
1283 // draw in elements up to idx
1284 self.copy(1, 0, idx);
1285
1286 // copy last element into empty spot
1287 self.copy(0, self.cap - 1, 1);
1288
1289 // move elements from tail to end forward, excluding the last one
1290 self.copy(self.tail + 1, self.tail, self.cap - self.tail - 1);
1291
Felix S. Klock IIe7c98612015-02-19 07:33:321292 self.tail = self.wrap_add(self.tail, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551293 }
1294 }
1295
1296 return elem;
1297 }
Alexisdc930b12015-02-07 16:46:161298
1299 /// Splits the collection into two at the given index.
1300 ///
1301 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1302 /// and the returned `Self` contains elements `[at, len)`.
1303 ///
1304 /// Note that the capacity of `self` does not change.
1305 ///
1306 /// # Panics
1307 ///
1308 /// Panics if `at > len`
1309 ///
1310 /// # Examples
Alexis3c18bc42015-02-07 17:13:321311 ///
1312 /// ```
Alex Crichtonce1a9652015-06-10 20:33:521313 /// # #![feature(split_off)]
Aaron Turon5fa9de12015-02-18 07:44:551314 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321315 ///
Aaron Turon5fa9de12015-02-18 07:44:551316 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
Alexisdc930b12015-02-07 16:46:161317 /// let buf2 = buf.split_off(1);
1318 /// // buf = [1], buf2 = [2, 3]
1319 /// assert_eq!(buf.len(), 1);
1320 /// assert_eq!(buf2.len(), 2);
1321 /// ```
1322 #[inline]
Alex Crichtond444d0c2015-06-09 21:39:231323 #[unstable(feature = "split_off",
Alexisdc930b12015-02-07 16:46:161324 reason = "new API, waiting for dust to settle")]
1325 pub fn split_off(&mut self, at: usize) -> Self {
1326 let len = self.len();
1327 assert!(at <= len, "`at` out of bounds");
1328
1329 let other_len = len - at;
Aaron Turon5fa9de12015-02-18 07:44:551330 let mut other = VecDeque::with_capacity(other_len);
Alexisdc930b12015-02-07 16:46:161331
1332 unsafe {
1333 let (first_half, second_half) = self.as_slices();
1334
1335 let first_len = first_half.len();
1336 let second_len = second_half.len();
1337 if at < first_len {
1338 // `at` lies in the first half.
1339 let amount_in_first = first_len - at;
1340
Alex Crichtonacd48a22015-03-27 18:12:281341 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
1342 *other.ptr,
Alex Crichtonab456942015-02-23 19:39:161343 amount_in_first);
Alexisdc930b12015-02-07 16:46:161344
1345 // just take all of the second half.
Alex Crichtonacd48a22015-03-27 18:12:281346 ptr::copy_nonoverlapping(second_half.as_ptr(),
1347 other.ptr.offset(amount_in_first as isize),
Alex Crichtonab456942015-02-23 19:39:161348 second_len);
Alexisdc930b12015-02-07 16:46:161349 } else {
1350 // `at` lies in the second half, need to factor in the elements we skipped
1351 // in the first half.
1352 let offset = at - first_len;
1353 let amount_in_second = second_len - offset;
Alex Crichtonacd48a22015-03-27 18:12:281354 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
1355 *other.ptr,
Alex Crichtonab456942015-02-23 19:39:161356 amount_in_second);
Alexisdc930b12015-02-07 16:46:161357 }
1358 }
1359
1360 // Cleanup where the ends of the buffers are
Felix S. Klock IIe7c98612015-02-19 07:33:321361 self.head = self.wrap_sub(self.head, other_len);
Alexisdc930b12015-02-07 16:46:161362 other.head = other.wrap_index(other_len);
1363
1364 other
1365 }
Alexis3c18bc42015-02-07 17:13:321366
1367 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1368 ///
1369 /// # Panics
1370 ///
1371 /// Panics if the new number of elements in self overflows a `usize`.
1372 ///
1373 /// # Examples
1374 ///
1375 /// ```
Alex Crichtonce1a9652015-06-10 20:33:521376 /// # #![feature(append)]
Aaron Turon5fa9de12015-02-18 07:44:551377 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321378 ///
Aaron Turon5fa9de12015-02-18 07:44:551379 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1380 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
Alexis3c18bc42015-02-07 17:13:321381 /// buf.append(&mut buf2);
1382 /// assert_eq!(buf.len(), 6);
1383 /// assert_eq!(buf2.len(), 0);
1384 /// ```
1385 #[inline]
Alex Crichtond444d0c2015-06-09 21:39:231386 #[unstable(feature = "append",
Alexis3c18bc42015-02-07 17:13:321387 reason = "new API, waiting for dust to settle")]
1388 pub fn append(&mut self, other: &mut Self) {
1389 // naive impl
1390 self.extend(other.drain());
1391 }
Steven Allendecf3952015-04-27 17:47:191392
1393 /// Retains only the elements specified by the predicate.
1394 ///
1395 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1396 /// This method operates in place and preserves the order of the retained
1397 /// elements.
1398 ///
1399 /// # Examples
1400 ///
1401 /// ```
1402 /// # #![feature(vec_deque_retain)]
1403 /// use std::collections::VecDeque;
1404 ///
1405 /// let mut buf = VecDeque::new();
1406 /// buf.extend(1..5);
1407 /// buf.retain(|&x| x%2 == 0);
1408 ///
1409 /// let v: Vec<_> = buf.into_iter().collect();
1410 /// assert_eq!(&v[..], &[2, 4]);
1411 /// ```
1412 #[unstable(feature = "vec_deque_retain",
1413 reason = "new API, waiting for dust to settle")]
1414 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
1415 let len = self.len();
1416 let mut del = 0;
1417 for i in 0..len {
1418 if !f(&self[i]) {
1419 del += 1;
1420 } else if del > 0 {
1421 self.swap(i-del, i);
1422 }
1423 }
1424 if del > 0 {
1425 self.truncate(len - del);
1426 }
1427 }
Jed Estep4f7a7422013-06-25 19:08:471428}
1429
Aaron Turon5fa9de12015-02-18 07:44:551430impl<T: Clone> VecDeque<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:581431 /// Modifies the ringbuf in-place so that `len()` is equal to new_len,
1432 /// either by removing excess elements or by appending copies of a value to the back.
1433 ///
1434 /// # Examples
1435 ///
1436 /// ```
Alex Crichtonce1a9652015-06-10 20:33:521437 /// # #![feature(deque_extras)]
Aaron Turon5fa9de12015-02-18 07:44:551438 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:581439 ///
Aaron Turon5fa9de12015-02-18 07:44:551440 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031441 /// buf.push_back(5);
1442 /// buf.push_back(10);
Piotr Czarnecki156a1c32015-01-05 14:48:581443 /// buf.push_back(15);
1444 /// buf.resize(2, 0);
1445 /// buf.resize(6, 20);
Joshua Landauca7418b2015-06-10 16:22:201446 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
Piotr Czarnecki156a1c32015-01-05 14:48:581447 /// assert_eq!(a, b);
1448 /// }
1449 /// ```
Alex Crichtond444d0c2015-06-09 21:39:231450 #[unstable(feature = "deque_extras",
Brian Anderson94ca8a32015-01-13 02:40:191451 reason = "matches collection reform specification; waiting on panic semantics")]
Alexise250fe32015-02-05 02:17:191452 pub fn resize(&mut self, new_len: usize, value: T) {
Piotr Czarnecki156a1c32015-01-05 14:48:581453 let len = self.len();
1454
1455 if new_len > len {
1456 self.extend(repeat(value).take(new_len - len))
1457 } else {
1458 self.truncate(new_len);
1459 }
1460 }
1461}
1462
Colin Sherratt7a666df2014-10-19 20:19:071463/// Returns the index in the underlying buffer for a given logical element index.
1464#[inline]
Alexise250fe32015-02-05 02:17:191465fn wrap_index(index: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071466 // size is always a power of 2
Colin Sherratt40191182014-11-12 01:22:071467 index & (size - 1)
Colin Sherratt7a666df2014-10-19 20:19:071468}
1469
1470/// Calculate the number of elements left to be read in the buffer
1471#[inline]
Alexise250fe32015-02-05 02:17:191472fn count(tail: usize, head: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071473 // size is always a power of 2
Felix S. Klock IIe7c98612015-02-19 07:33:321474 (head.wrapping_sub(tail)) & (size - 1)
Colin Sherratt7a666df2014-10-19 20:19:071475}
1476
Aaron Turon5fa9de12015-02-18 07:44:551477/// `VecDeque` iterator.
Brian Andersonb44ee372015-01-24 05:48:201478#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101479pub struct Iter<'a, T:'a> {
Colin Sherratt7a666df2014-10-19 20:19:071480 ring: &'a [T],
Alexise250fe32015-02-05 02:17:191481 tail: usize,
1482 head: usize
Niko Matsakis1b487a82014-08-28 01:46:521483}
1484
Jorge Aparicio351409a2015-01-04 03:54:181485// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
Huon Wilsonb7832ed2014-12-30 10:01:361486impl<'a, T> Clone for Iter<'a, T> {
1487 fn clone(&self) -> Iter<'a, T> {
1488 Iter {
1489 ring: self.ring,
1490 tail: self.tail,
1491 head: self.head
1492 }
1493 }
1494}
1495
Brian Andersonb44ee372015-01-24 05:48:201496#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351497impl<'a, T> Iterator for Iter<'a, T> {
1498 type Item = &'a T;
1499
Niko Matsakisbc4164d2013-11-16 22:29:391500 #[inline]
Erik Price5731ca32013-12-10 07:16:181501 fn next(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071502 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391503 return None;
1504 }
Colin Sherratt7a666df2014-10-19 20:19:071505 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:321506 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181507 unsafe { Some(self.ring.get_unchecked(tail)) }
Niko Matsakisbc4164d2013-11-16 22:29:391508 }
1509
1510 #[inline]
Alexise250fe32015-02-05 02:17:191511 fn size_hint(&self) -> (usize, Option<usize>) {
Colin Sherratt7a666df2014-10-19 20:19:071512 let len = count(self.tail, self.head, self.ring.len());
Niko Matsakisbc4164d2013-11-16 22:29:391513 (len, Some(len))
1514 }
1515}
1516
Brian Andersonb44ee372015-01-24 05:48:201517#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351518impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391519 #[inline]
Erik Price5731ca32013-12-10 07:16:181520 fn next_back(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071521 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391522 return None;
1523 }
Felix S. Klock IIe7c98612015-02-19 07:33:321524 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181525 unsafe { Some(self.ring.get_unchecked(self.head)) }
Niko Matsakisbc4164d2013-11-16 22:29:391526 }
1527}
Jed Estep35314c92013-06-26 15:38:291528
Brian Andersonb44ee372015-01-24 05:48:201529#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351530impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241531
Brian Andersonb44ee372015-01-24 05:48:201532#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351533impl<'a, T> RandomAccessIterator for Iter<'a, T> {
blake2-ppcf6862132013-07-29 18:16:261534 #[inline]
Alexise250fe32015-02-05 02:17:191535 fn indexable(&self) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071536 let (len, _) = self.size_hint();
1537 len
1538 }
blake2-ppcf6862132013-07-29 18:16:261539
1540 #[inline]
Alexise250fe32015-02-05 02:17:191541 fn idx(&mut self, j: usize) -> Option<&'a T> {
blake2-ppcf6862132013-07-29 18:16:261542 if j >= self.indexable() {
1543 None
1544 } else {
Felix S. Klock IIe7c98612015-02-19 07:33:321545 let idx = wrap_index(self.tail.wrapping_add(j), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181546 unsafe { Some(self.ring.get_unchecked(idx)) }
blake2-ppcf6862132013-07-29 18:16:261547 }
1548 }
1549}
1550
Aaron Turon5fa9de12015-02-18 07:44:551551/// `VecDeque` mutable iterator.
Brian Andersonb44ee372015-01-24 05:48:201552#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101553pub struct IterMut<'a, T:'a> {
Edward Wang101498c2015-02-25 10:11:231554 ring: &'a mut [T],
Alexise250fe32015-02-05 02:17:191555 tail: usize,
1556 head: usize,
Niko Matsakis1b487a82014-08-28 01:46:521557}
1558
Brian Andersonb44ee372015-01-24 05:48:201559#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351560impl<'a, T> Iterator for IterMut<'a, T> {
1561 type Item = &'a mut T;
1562
Niko Matsakisbc4164d2013-11-16 22:29:391563 #[inline]
Erik Price5731ca32013-12-10 07:16:181564 fn next(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:071565 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391566 return None;
1567 }
Colin Sherratt7a666df2014-10-19 20:19:071568 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:321569 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111570
1571 unsafe {
Edward Wang101498c2015-02-25 10:11:231572 let elem = self.ring.get_unchecked_mut(tail);
1573 Some(&mut *(elem as *mut _))
Alex Crichton9d5d97b2014-10-15 06:05:011574 }
Niko Matsakisbc4164d2013-11-16 22:29:391575 }
1576
1577 #[inline]
Alexise250fe32015-02-05 02:17:191578 fn size_hint(&self) -> (usize, Option<usize>) {
Edward Wang101498c2015-02-25 10:11:231579 let len = count(self.tail, self.head, self.ring.len());
Colin Sherratt7a666df2014-10-19 20:19:071580 (len, Some(len))
Niko Matsakisbc4164d2013-11-16 22:29:391581 }
1582}
1583
Brian Andersonb44ee372015-01-24 05:48:201584#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351585impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391586 #[inline]
Erik Price5731ca32013-12-10 07:16:181587 fn next_back(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:071588 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391589 return None;
1590 }
Felix S. Klock IIe7c98612015-02-19 07:33:321591 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111592
1593 unsafe {
Edward Wang101498c2015-02-25 10:11:231594 let elem = self.ring.get_unchecked_mut(self.head);
1595 Some(&mut *(elem as *mut _))
Alexis Beingessner865c2db2014-11-23 02:34:111596 }
Niko Matsakisbc4164d2013-11-16 22:29:391597 }
1598}
Daniel Micayb47e1e92013-02-16 22:55:551599
Brian Andersonb44ee372015-01-24 05:48:201600#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351601impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241602
Aaron Turon5fa9de12015-02-18 07:44:551603/// A by-value VecDeque iterator
Andrew Paseltiner64532f72015-03-23 12:50:471604#[derive(Clone)]
Brian Andersonb44ee372015-01-24 05:48:201605#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101606pub struct IntoIter<T> {
Aaron Turon5fa9de12015-02-18 07:44:551607 inner: VecDeque<T>,
Alexis Beingessner865c2db2014-11-23 02:34:111608}
1609
Brian Andersonb44ee372015-01-24 05:48:201610#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351611impl<T> Iterator for IntoIter<T> {
1612 type Item = T;
1613
Alexis Beingessner865c2db2014-11-23 02:34:111614 #[inline]
1615 fn next(&mut self) -> Option<T> {
1616 self.inner.pop_front()
1617 }
1618
1619 #[inline]
Alexise250fe32015-02-05 02:17:191620 fn size_hint(&self) -> (usize, Option<usize>) {
Alexis Beingessner865c2db2014-11-23 02:34:111621 let len = self.inner.len();
1622 (len, Some(len))
1623 }
1624}
1625
Brian Andersonb44ee372015-01-24 05:48:201626#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351627impl<T> DoubleEndedIterator for IntoIter<T> {
Alexis Beingessner865c2db2014-11-23 02:34:111628 #[inline]
1629 fn next_back(&mut self) -> Option<T> {
1630 self.inner.pop_back()
1631 }
1632}
1633
Brian Andersonb44ee372015-01-24 05:48:201634#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351635impl<T> ExactSizeIterator for IntoIter<T> {}
Alexis Beingessner865c2db2014-11-23 02:34:111636
Aaron Turon5fa9de12015-02-18 07:44:551637/// A draining VecDeque iterator
Alex Crichtond444d0c2015-06-09 21:39:231638#[unstable(feature = "drain",
Brian Anderson94ca8a32015-01-13 02:40:191639 reason = "matches collection reform specification, waiting for dust to settle")]
Clark Gaebeld57f2592014-12-16 22:45:031640pub struct Drain<'a, T: 'a> {
Aaron Turon5fa9de12015-02-18 07:44:551641 inner: &'a mut VecDeque<T>,
Clark Gaebeld57f2592014-12-16 22:45:031642}
1643
Brian Andersonb44ee372015-01-24 05:48:201644#[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:031645impl<'a, T: 'a> Drop for Drain<'a, T> {
1646 fn drop(&mut self) {
Jorge Apariciof9865ea2015-01-11 02:50:071647 for _ in self.by_ref() {}
Clark Gaebeld57f2592014-12-16 22:45:031648 self.inner.head = 0;
1649 self.inner.tail = 0;
1650 }
1651}
1652
Brian Andersonb44ee372015-01-24 05:48:201653#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351654impl<'a, T: 'a> Iterator for Drain<'a, T> {
1655 type Item = T;
1656
Clark Gaebeld57f2592014-12-16 22:45:031657 #[inline]
1658 fn next(&mut self) -> Option<T> {
1659 self.inner.pop_front()
1660 }
1661
1662 #[inline]
Alexise250fe32015-02-05 02:17:191663 fn size_hint(&self) -> (usize, Option<usize>) {
Clark Gaebeld57f2592014-12-16 22:45:031664 let len = self.inner.len();
1665 (len, Some(len))
1666 }
1667}
1668
Brian Andersonb44ee372015-01-24 05:48:201669#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351670impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
Clark Gaebeld57f2592014-12-16 22:45:031671 #[inline]
1672 fn next_back(&mut self) -> Option<T> {
1673 self.inner.pop_back()
1674 }
1675}
1676
Brian Andersonb44ee372015-01-24 05:48:201677#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351678impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
Clark Gaebeld57f2592014-12-16 22:45:031679
Brian Andersonb44ee372015-01-24 05:48:201680#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551681impl<A: PartialEq> PartialEq for VecDeque<A> {
1682 fn eq(&self, other: &VecDeque<A>) -> bool {
Colin Sherratt7a666df2014-10-19 20:19:071683 self.len() == other.len() &&
Joshua Landauca7418b2015-06-10 16:22:201684 self.iter().zip(other).all(|(a, b)| a.eq(b))
blake2-ppc10c76982013-07-06 13:27:321685 }
blake2-ppc10c76982013-07-06 13:27:321686}
1687
Brian Andersonb44ee372015-01-24 05:48:201688#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551689impl<A: Eq> Eq for VecDeque<A> {}
nham25acfde2014-08-01 20:05:031690
Brian Andersonb44ee372015-01-24 05:48:201691#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551692impl<A: PartialOrd> PartialOrd for VecDeque<A> {
1693 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
nham63615772014-07-27 03:18:561694 iter::order::partial_cmp(self.iter(), other.iter())
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: Ord> Ord for VecDeque<A> {
nham3737c532014-08-01 20:22:481700 #[inline]
Aaron Turon5fa9de12015-02-18 07:44:551701 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
nham3737c532014-08-01 20:22:481702 iter::order::cmp(self.iter(), other.iter())
1703 }
1704}
1705
Brian Andersonb44ee372015-01-24 05:48:201706#[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton5a32b4a2015-02-18 22:34:081707impl<A: Hash> Hash for VecDeque<A> {
Alex Crichtonf83e23a2015-02-18 04:48:071708 fn hash<H: Hasher>(&self, state: &mut H) {
1709 self.len().hash(state);
1710 for elt in self {
1711 elt.hash(state);
1712 }
1713 }
1714}
nham1cfa6562014-07-27 02:33:471715
Brian Andersonb44ee372015-01-24 05:48:201716#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551717impl<A> Index<usize> for VecDeque<A> {
Jorge Aparicio32dd5922015-01-03 15:40:101718 type Output = A;
1719
Niko Matsakisb4d4daf2015-03-21 23:33:271720 #[inline]
1721 fn index(&self, i: usize) -> &A {
1722 self.get(i).expect("Out of bounds access")
1723 }
Jorge Aparicio32dd5922015-01-03 15:40:101724}
1725
Brian Andersonb44ee372015-01-24 05:48:201726#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551727impl<A> IndexMut<usize> for VecDeque<A> {
Niko Matsakisb4d4daf2015-03-21 23:33:271728 #[inline]
1729 fn index_mut(&mut self, i: usize) -> &mut A {
1730 self.get_mut(i).expect("Out of bounds access")
1731 }
Jorge Aparicio32dd5922015-01-03 15:40:101732}
1733
Brian Andersonb44ee372015-01-24 05:48:201734#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551735impl<A> FromIterator<A> for VecDeque<A> {
Alexis66613e22015-02-18 18:06:211736 fn from_iter<T: IntoIterator<Item=A>>(iterable: T) -> VecDeque<A> {
1737 let iterator = iterable.into_iter();
blake2-ppcf8ae5262013-07-30 00:06:491738 let (lower, _) = iterator.size_hint();
Aaron Turon5fa9de12015-02-18 07:44:551739 let mut deq = VecDeque::with_capacity(lower);
blake2-ppcf8ae5262013-07-30 00:06:491740 deq.extend(iterator);
blake2-ppc08dc72f2013-07-06 03:42:451741 deq
1742 }
1743}
1744
Alex Crichtoncc687862015-02-17 18:06:241745#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551746impl<T> IntoIterator for VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101747 type Item = T;
1748 type IntoIter = IntoIter<T>;
1749
Alex Crichton8f5b5f92015-04-17 21:31:301750 /// Consumes the list into a front-to-back iterator yielding elements by
1751 /// value.
Jorge Aparicioe7273782015-02-13 22:55:101752 fn into_iter(self) -> IntoIter<T> {
Alex Crichton8f5b5f92015-04-17 21:31:301753 IntoIter {
1754 inner: self,
1755 }
Jorge Aparicioe7273782015-02-13 22:55:101756 }
1757}
1758
Alex Crichtoncc687862015-02-17 18:06:241759#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551760impl<'a, T> IntoIterator for &'a VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101761 type Item = &'a T;
1762 type IntoIter = Iter<'a, T>;
1763
1764 fn into_iter(self) -> Iter<'a, T> {
1765 self.iter()
1766 }
1767}
1768
Alex Crichtoncc687862015-02-17 18:06:241769#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551770impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101771 type Item = &'a mut T;
1772 type IntoIter = IterMut<'a, T>;
1773
1774 fn into_iter(mut self) -> IterMut<'a, T> {
1775 self.iter_mut()
1776 }
1777}
1778
Brian Andersonb44ee372015-01-24 05:48:201779#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551780impl<A> Extend<A> for VecDeque<A> {
Alexis4a9d1902015-02-18 15:04:301781 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
1782 for elt in iter {
Alexis Beingessnercf3b2e42014-11-06 17:24:471783 self.push_back(elt);
blake2-ppcf8ae5262013-07-30 00:06:491784 }
1785 }
1786}
1787
Johannes Oertelb36ed7d2015-06-03 10:38:421788#[stable(feature = "extend_ref", since = "1.2.0")]
1789impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
1790 fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
1791 self.extend(iter.into_iter().cloned());
1792 }
1793}
1794
Brian Andersonb44ee372015-01-24 05:48:201795#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551796impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041797 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Tobias Bucher408f7b52015-02-10 21:12:131798 try!(write!(f, "["));
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041799
1800 for (i, e) in self.iter().enumerate() {
1801 if i != 0 { try!(write!(f, ", ")); }
Sean McArthur44440e52014-12-20 08:09:351802 try!(write!(f, "{:?}", *e));
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041803 }
1804
1805 write!(f, "]")
1806 }
1807}
Jorge Apariciocb5e4292015-03-12 00:44:021808
1809#[cfg(test)]
Johannes Oertel07cc7d92015-04-24 15:30:411810mod tests {
Wesley Wiser99df3832015-05-30 23:49:561811 use core::iter::Iterator;
Jorge Apariciocb5e4292015-03-12 00:44:021812 use core::option::Option::Some;
1813
1814 use test;
1815
1816 use super::VecDeque;
1817
1818 #[bench]
1819 fn bench_push_back_100(b: &mut test::Bencher) {
1820 let mut deq = VecDeque::with_capacity(101);
1821 b.iter(|| {
1822 for i in 0..100 {
1823 deq.push_back(i);
1824 }
1825 deq.head = 0;
1826 deq.tail = 0;
1827 })
1828 }
1829
1830 #[bench]
1831 fn bench_push_front_100(b: &mut test::Bencher) {
1832 let mut deq = VecDeque::with_capacity(101);
1833 b.iter(|| {
1834 for i in 0..100 {
1835 deq.push_front(i);
1836 }
1837 deq.head = 0;
1838 deq.tail = 0;
1839 })
1840 }
1841
1842 #[bench]
1843 fn bench_pop_back_100(b: &mut test::Bencher) {
1844 let mut deq= VecDeque::<i32>::with_capacity(101);
1845
1846 b.iter(|| {
1847 deq.head = 100;
1848 deq.tail = 0;
1849 while !deq.is_empty() {
1850 test::black_box(deq.pop_back());
1851 }
1852 })
1853 }
1854
1855 #[bench]
1856 fn bench_pop_front_100(b: &mut test::Bencher) {
1857 let mut deq = VecDeque::<i32>::with_capacity(101);
1858
1859 b.iter(|| {
1860 deq.head = 100;
1861 deq.tail = 0;
1862 while !deq.is_empty() {
1863 test::black_box(deq.pop_front());
1864 }
1865 })
1866 }
1867
1868 #[test]
1869 fn test_swap_front_back_remove() {
1870 fn test(back: bool) {
1871 // This test checks that every single combination of tail position and length is tested.
1872 // Capacity 15 should be large enough to cover every case.
1873 let mut tester = VecDeque::with_capacity(15);
1874 let usable_cap = tester.capacity();
1875 let final_len = usable_cap / 2;
1876
1877 for len in 0..final_len {
1878 let expected = if back {
1879 (0..len).collect()
1880 } else {
1881 (0..len).rev().collect()
1882 };
1883 for tail_pos in 0..usable_cap {
1884 tester.tail = tail_pos;
1885 tester.head = tail_pos;
1886 if back {
1887 for i in 0..len * 2 {
1888 tester.push_front(i);
1889 }
1890 for i in 0..len {
1891 assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
1892 }
1893 } else {
1894 for i in 0..len * 2 {
1895 tester.push_back(i);
1896 }
1897 for i in 0..len {
1898 let idx = tester.len() - 1 - i;
1899 assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
1900 }
1901 }
1902 assert!(tester.tail < tester.cap);
1903 assert!(tester.head < tester.cap);
1904 assert_eq!(tester, expected);
1905 }
1906 }
1907 }
1908 test(true);
1909 test(false);
1910 }
1911
1912 #[test]
1913 fn test_insert() {
1914 // This test checks that every single combination of tail position, length, and
1915 // insertion position is tested. Capacity 15 should be large enough to cover every case.
1916
1917 let mut tester = VecDeque::with_capacity(15);
1918 // can't guarantee we got 15, so have to get what we got.
1919 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
1920 // this test isn't covering what it wants to
1921 let cap = tester.capacity();
1922
1923
1924 // len is the length *after* insertion
1925 for len in 1..cap {
1926 // 0, 1, 2, .., len - 1
Alex Crichtond4a2c942015-03-30 18:00:051927 let expected = (0..).take(len).collect();
Jorge Apariciocb5e4292015-03-12 00:44:021928 for tail_pos in 0..cap {
1929 for to_insert in 0..len {
1930 tester.tail = tail_pos;
1931 tester.head = tail_pos;
1932 for i in 0..len {
1933 if i != to_insert {
1934 tester.push_back(i);
1935 }
1936 }
1937 tester.insert(to_insert, to_insert);
1938 assert!(tester.tail < tester.cap);
1939 assert!(tester.head < tester.cap);
1940 assert_eq!(tester, expected);
1941 }
1942 }
1943 }
1944 }
1945
1946 #[test]
1947 fn test_remove() {
1948 // This test checks that every single combination of tail position, length, and
1949 // removal position is tested. Capacity 15 should be large enough to cover every case.
1950
1951 let mut tester = VecDeque::with_capacity(15);
1952 // can't guarantee we got 15, so have to get what we got.
1953 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
1954 // this test isn't covering what it wants to
1955 let cap = tester.capacity();
1956
1957 // len is the length *after* removal
1958 for len in 0..cap - 1 {
1959 // 0, 1, 2, .., len - 1
Alex Crichtond4a2c942015-03-30 18:00:051960 let expected = (0..).take(len).collect();
Jorge Apariciocb5e4292015-03-12 00:44:021961 for tail_pos in 0..cap {
1962 for to_remove in 0..len + 1 {
1963 tester.tail = tail_pos;
1964 tester.head = tail_pos;
1965 for i in 0..len {
1966 if i == to_remove {
1967 tester.push_back(1234);
1968 }
1969 tester.push_back(i);
1970 }
1971 if to_remove == len {
1972 tester.push_back(1234);
1973 }
1974 tester.remove(to_remove);
1975 assert!(tester.tail < tester.cap);
1976 assert!(tester.head < tester.cap);
1977 assert_eq!(tester, expected);
1978 }
1979 }
1980 }
1981 }
1982
1983 #[test]
1984 fn test_shrink_to_fit() {
1985 // This test checks that every single combination of head and tail position,
1986 // is tested. Capacity 15 should be large enough to cover every case.
1987
1988 let mut tester = VecDeque::with_capacity(15);
1989 // can't guarantee we got 15, so have to get what we got.
1990 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
1991 // this test isn't covering what it wants to
1992 let cap = tester.capacity();
1993 tester.reserve(63);
1994 let max_cap = tester.capacity();
1995
1996 for len in 0..cap + 1 {
1997 // 0, 1, 2, .., len - 1
Alex Crichtond4a2c942015-03-30 18:00:051998 let expected = (0..).take(len).collect();
Jorge Apariciocb5e4292015-03-12 00:44:021999 for tail_pos in 0..max_cap + 1 {
2000 tester.tail = tail_pos;
2001 tester.head = tail_pos;
2002 tester.reserve(63);
2003 for i in 0..len {
2004 tester.push_back(i);
2005 }
2006 tester.shrink_to_fit();
2007 assert!(tester.capacity() <= cap);
2008 assert!(tester.tail < tester.cap);
2009 assert!(tester.head < tester.cap);
2010 assert_eq!(tester, expected);
2011 }
2012 }
2013 }
2014
2015 #[test]
2016 fn test_split_off() {
2017 // This test checks that every single combination of tail position, length, and
2018 // split position is tested. Capacity 15 should be large enough to cover every case.
2019
2020 let mut tester = VecDeque::with_capacity(15);
2021 // can't guarantee we got 15, so have to get what we got.
2022 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2023 // this test isn't covering what it wants to
2024 let cap = tester.capacity();
2025
2026 // len is the length *before* splitting
2027 for len in 0..cap {
2028 // index to split at
2029 for at in 0..len + 1 {
2030 // 0, 1, 2, .., at - 1 (may be empty)
Alex Crichtond4a2c942015-03-30 18:00:052031 let expected_self = (0..).take(at).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022032 // at, at + 1, .., len - 1 (may be empty)
Alex Crichtond4a2c942015-03-30 18:00:052033 let expected_other = (at..).take(len - at).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022034
2035 for tail_pos in 0..cap {
2036 tester.tail = tail_pos;
2037 tester.head = tail_pos;
2038 for i in 0..len {
2039 tester.push_back(i);
2040 }
2041 let result = tester.split_off(at);
2042 assert!(tester.tail < tester.cap);
2043 assert!(tester.head < tester.cap);
2044 assert!(result.tail < result.cap);
2045 assert!(result.head < result.cap);
2046 assert_eq!(tester, expected_self);
2047 assert_eq!(result, expected_other);
2048 }
2049 }
2050 }
2051 }
2052}