blob: 1064fcdd9178bf805eeb0566e022901487b34dd7 [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 Crichton56290a02014-12-22 17:04:2321use core::cmp::Ordering;
Alex Crichton6a585372014-05-30 01:50:1222use core::fmt;
Steven Fackler651c42f2015-08-24 04:59:0723use core::iter::{repeat, FromIterator};
Ulrik Sverdrup66f5dc12015-09-18 14:32:5224use core::mem;
Alex Crichton56290a02014-12-22 17:04:2325use core::ops::{Index, IndexMut};
Alexis Beingessnerbfa0e1f2015-07-10 04:57:2126use core::ptr;
Oliver Schneider6584ae52015-03-13 08:56:1827use core::slice;
Ulrik Sverdrup66f5dc12015-09-18 14:32:5228use core::usize;
Alex Crichton998fece2013-05-06 04:42:5429
Alex Crichtonf83e23a2015-02-18 04:48:0730use core::hash::{Hash, Hasher};
Keegan McAllister67350bc2014-09-07 21:57:2631use core::cmp;
Colin Sherratt7a666df2014-10-19 20:19:0732
Alexis Beingessnerbfa0e1f2015-07-10 04:57:2133use alloc::raw_vec::RawVec;
blake2-ppc70523712013-07-10 13:27:1434
Michael Layzell45be6fc2015-08-07 02:03:1435use super::range::RangeArgument;
36
Florian Zeitzf35f9732015-02-27 14:36:5337const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
38const MINIMUM_CAPACITY: usize = 1; // 2 - 1
Ulrik Sverdrup66f5dc12015-09-18 14:32:5239const MAXIMUM_ZST_CAPACITY: usize = 1 << (usize::BITS - 1); // Largest possible power of two
Alexis Beingessnercf3b2e42014-11-06 17:24:4740
Alex Crichtonff497332015-10-22 23:28:4541/// `VecDeque` is a growable ring buffer, which can be used as a double-ended
42/// queue efficiently.
Corey Richardsonf5ea6202015-07-05 16:18:5743///
Alex Crichtonff497332015-10-22 23:28:4544/// The "default" usage of this type as a queue is to use `push_back` to add to
45/// the queue, and `pop_front` to remove from the queue. `extend` and `append`
46/// push onto the back in this manner, and iterating over `VecDeque` goes front
47/// to back.
Brian Andersonb44ee372015-01-24 05:48:2048#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5549pub struct VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:0750 // tail and head are pointers into the buffer. Tail always points
51 // to the first element that could be read, Head always points
52 // to where data should be written.
Corey Richardson8e2ce462015-07-05 07:49:3653 // If tail == head the buffer is empty. The length of the ringbuffer
Colin Sherratt7a666df2014-10-19 20:19:0754 // is defined as the distance between the two.
55
Alexise250fe32015-02-05 02:17:1956 tail: usize,
57 head: usize,
Alexis Beingessnerbfa0e1f2015-07-10 04:57:2158 buf: RawVec<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
Brian Andersonb44ee372015-01-24 05:48:2068#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5569impl<T> Drop for VecDeque<T> {
Felix S. Klock IId778e572015-07-17 14:12:3570 #[unsafe_destructor_blind_to_params]
Colin Sherratt7a666df2014-10-19 20:19:0771 fn drop(&mut self) {
72 self.clear();
Alexis Beingessnerbfa0e1f2015-07-10 04:57:2173 // RawVec handles deallocation
Colin Sherratt7a666df2014-10-19 20:19:0774 }
Marijn Haverbeke26610db2012-01-11 11:49:3375}
Roy Frostig9c818892010-07-21 01:03:0976
Brian Andersonb44ee372015-01-24 05:48:2077#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:5578impl<T> Default for VecDeque<T> {
Tom Jakubowskid6a39412014-06-09 07:30:0479 #[inline]
Aaron Turon5fa9de12015-02-18 07:44:5580 fn default() -> VecDeque<T> { VecDeque::new() }
Tom Jakubowskid6a39412014-06-09 07:30:0481}
82
Aaron Turon5fa9de12015-02-18 07:44:5583impl<T> VecDeque<T> {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:2184 /// Marginally more convenient
85 #[inline]
86 fn ptr(&self) -> *mut T {
87 self.buf.ptr()
88 }
89
90 /// Marginally more convenient
91 #[inline]
92 fn cap(&self) -> usize {
Ulrik Sverdrup66f5dc12015-09-18 14:32:5293 if mem::size_of::<T>() == 0 {
94 // For zero sized types, we are always at maximum capacity
95 MAXIMUM_ZST_CAPACITY
96 } else {
97 self.buf.cap()
98 }
Alexis Beingessnerbfa0e1f2015-07-10 04:57:2199 }
100
Colin Sherratt7a666df2014-10-19 20:19:07101 /// Turn ptr into a slice
102 #[inline]
Alexis Beingessner8dbaa712014-12-31 00:07:53103 unsafe fn buffer_as_slice(&self) -> &[T] {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21104 slice::from_raw_parts(self.ptr(), self.cap())
Clark Gaebel525f65e2014-12-16 04:01:58105 }
106
107 /// Turn ptr into a mut slice
108 #[inline]
Alexis Beingessner8dbaa712014-12-31 00:07:53109 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21110 slice::from_raw_parts_mut(self.ptr(), self.cap())
Colin Sherratt7a666df2014-10-19 20:19:07111 }
112
113 /// Moves an element out of the buffer
114 #[inline]
Alexise250fe32015-02-05 02:17:19115 unsafe fn buffer_read(&mut self, off: usize) -> T {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21116 ptr::read(self.ptr().offset(off as isize))
Colin Sherratt7a666df2014-10-19 20:19:07117 }
118
119 /// Writes an element into the buffer, moving it.
120 #[inline]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25121 unsafe fn buffer_write(&mut self, off: usize, value: T) {
122 ptr::write(self.ptr().offset(off as isize), value);
Colin Sherratt7a666df2014-10-19 20:19:07123 }
124
Esptiondad8cd12015-07-09 02:17:13125 /// Returns true if and only if the buffer is at capacity
Colin Sherratt7a666df2014-10-19 20:19:07126 #[inline]
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21127 fn is_full(&self) -> bool { self.cap() - self.len() == 1 }
Colin Sherratt40191182014-11-12 01:22:07128
Alex Crichton665ea962015-02-18 03:00:20129 /// Returns the index in the underlying buffer for a given logical element
130 /// index.
Colin Sherratt40191182014-11-12 01:22:07131 #[inline]
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21132 fn wrap_index(&self, idx: usize) -> usize { wrap_index(idx, self.cap()) }
Matt Murphy40f28c72014-12-03 17:12:30133
Felix S. Klock IIe7c98612015-02-19 07:33:32134 /// Returns the index in the underlying buffer for a given logical element
135 /// index + addend.
136 #[inline]
137 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21138 wrap_index(idx.wrapping_add(addend), self.cap())
Felix S. Klock IIe7c98612015-02-19 07:33:32139 }
140
141 /// Returns the index in the underlying buffer for a given logical element
142 /// index - subtrahend.
143 #[inline]
144 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21145 wrap_index(idx.wrapping_sub(subtrahend), self.cap())
Felix S. Klock IIe7c98612015-02-19 07:33:32146 }
147
Matt Murphy40f28c72014-12-03 17:12:30148 /// Copies a contiguous block of memory len long from src to dst
149 #[inline]
Alexise250fe32015-02-05 02:17:19150 unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
Michael Layzell26db7172015-11-03 18:03:36151 debug_assert!(dst + len <= self.cap(), "cpy dst={} src={} len={} cap={}", dst, src, len,
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21152 self.cap());
Michael Layzell26db7172015-11-03 18:03:36153 debug_assert!(src + len <= self.cap(), "cpy dst={} src={} len={} cap={}", dst, src, len,
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21154 self.cap());
Alex Crichtonab456942015-02-23 19:39:16155 ptr::copy(
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21156 self.ptr().offset(src as isize),
157 self.ptr().offset(dst as isize),
Piotr Czarnecki156a1c32015-01-05 14:48:58158 len);
159 }
160
161 /// Copies a contiguous block of memory len long from src to dst
162 #[inline]
Alexise250fe32015-02-05 02:17:19163 unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
Michael Layzell26db7172015-11-03 18:03:36164 debug_assert!(dst + len <= self.cap(), "cno dst={} src={} len={} cap={}", dst, src, len,
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21165 self.cap());
Michael Layzell26db7172015-11-03 18:03:36166 debug_assert!(src + len <= self.cap(), "cno dst={} src={} len={} cap={}", dst, src, len,
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21167 self.cap());
Alex Crichtonab456942015-02-23 19:39:16168 ptr::copy_nonoverlapping(
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21169 self.ptr().offset(src as isize),
170 self.ptr().offset(dst as isize),
Piotr Czarnecki59d41532014-12-16 23:37:55171 len);
Matt Murphy40f28c72014-12-03 17:12:30172 }
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21173
Michael Layzell45be6fc2015-08-07 02:03:14174 /// Copies a potentially wrapping block of memory len long from src to dest.
175 /// (abs(dst - src) + len) must be no larger than cap() (There must be at
176 /// most one continuous overlapping region between src and dest).
177 unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
Michael Layzell26db7172015-11-03 18:03:36178 #[allow(dead_code)]
179 fn diff(a: usize, b: usize) -> usize {if a <= b {b - a} else {a - b}}
180 debug_assert!(cmp::min(diff(dst, src),
181 self.cap() - diff(dst, src)) + len <= self.cap(),
182 "wrc dst={} src={} len={} cap={}", dst, src, len, self.cap());
Michael Layzell45be6fc2015-08-07 02:03:14183
184 if src == dst || len == 0 { return }
185
186 let dst_after_src = self.wrap_sub(dst, src) < len;
187
188 let src_pre_wrap_len = self.cap() - src;
189 let dst_pre_wrap_len = self.cap() - dst;
190 let src_wraps = src_pre_wrap_len < len;
191 let dst_wraps = dst_pre_wrap_len < len;
192
193 match (dst_after_src, src_wraps, dst_wraps) {
194 (_, false, false) => {
195 // src doesn't wrap, dst doesn't wrap
196 //
197 // S . . .
198 // 1 [_ _ A A B B C C _]
199 // 2 [_ _ A A A A B B _]
200 // D . . .
201 //
202 self.copy(dst, src, len);
203 }
204 (false, false, true) => {
205 // dst before src, src doesn't wrap, dst wraps
206 //
207 // S . . .
208 // 1 [A A B B _ _ _ C C]
209 // 2 [A A B B _ _ _ A A]
210 // 3 [B B B B _ _ _ A A]
211 // . . D .
212 //
213 self.copy(dst, src, dst_pre_wrap_len);
214 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
215 }
216 (true, false, true) => {
217 // src before dst, src doesn't wrap, dst wraps
218 //
219 // S . . .
220 // 1 [C C _ _ _ A A B B]
221 // 2 [B B _ _ _ A A B B]
222 // 3 [B B _ _ _ A A A A]
223 // . . D .
224 //
225 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
226 self.copy(dst, src, dst_pre_wrap_len);
227 }
228 (false, true, false) => {
229 // dst before src, src wraps, dst doesn't wrap
230 //
231 // . . S .
232 // 1 [C C _ _ _ A A B B]
233 // 2 [C C _ _ _ B B B B]
234 // 3 [C C _ _ _ B B C C]
235 // D . . .
236 //
237 self.copy(dst, src, src_pre_wrap_len);
238 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
239 }
240 (true, true, false) => {
241 // src before dst, src wraps, dst doesn't wrap
242 //
243 // . . S .
244 // 1 [A A B B _ _ _ C C]
245 // 2 [A A A A _ _ _ C C]
246 // 3 [C C A A _ _ _ C C]
247 // D . . .
248 //
249 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
250 self.copy(dst, src, src_pre_wrap_len);
251 }
252 (false, true, true) => {
253 // dst before src, src wraps, dst wraps
254 //
255 // . . . S .
256 // 1 [A B C D _ E F G H]
257 // 2 [A B C D _ E G H H]
258 // 3 [A B C D _ E G H A]
259 // 4 [B C C D _ E G H A]
260 // . . D . .
261 //
262 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
263 let delta = dst_pre_wrap_len - src_pre_wrap_len;
264 self.copy(dst, src, src_pre_wrap_len);
265 self.copy(dst + src_pre_wrap_len, 0, delta);
266 self.copy(0, delta, len - dst_pre_wrap_len);
267 }
268 (true, true, true) => {
269 // src before dst, src wraps, dst wraps
270 //
271 // . . S . .
272 // 1 [A B C D _ E F G H]
273 // 2 [A A B D _ E F G H]
274 // 3 [H A B D _ E F G H]
275 // 4 [H A B D _ E F F G]
276 // . . . D .
277 //
278 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
279 let delta = src_pre_wrap_len - dst_pre_wrap_len;
280 self.copy(delta, 0, len - src_pre_wrap_len);
281 self.copy(0, self.cap() - delta, delta);
282 self.copy(dst, src, dst_pre_wrap_len);
283 }
284 }
285 }
286
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21287 /// Frobs the head and tail sections around to handle the fact that we
288 /// just reallocated. Unsafe because it trusts old_cap.
289 #[inline]
290 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
291 let new_cap = self.cap();
292
293 // Move the shortest contiguous section of the ring buffer
294 // T H
295 // [o o o o o o o . ]
296 // T H
297 // A [o o o o o o o . . . . . . . . . ]
298 // H T
299 // [o o . o o o o o ]
300 // T H
301 // B [. . . o o o o o o o . . . . . . ]
302 // H T
303 // [o o o o o . o o ]
304 // H T
305 // C [o o o o o . . . . . . . . . o o ]
306
307 if self.tail <= self.head { // A
308 // Nop
309 } else if self.head < old_cap - self.tail { // B
310 self.copy_nonoverlapping(old_cap, 0, self.head);
311 self.head += old_cap;
312 debug_assert!(self.head > self.tail);
313 } else { // C
314 let new_tail = new_cap - (old_cap - self.tail);
315 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
316 self.tail = new_tail;
317 debug_assert!(self.head < self.tail);
318 }
319 debug_assert!(self.head < self.cap());
320 debug_assert!(self.tail < self.cap());
321 debug_assert!(self.cap().count_ones() == 1);
322 }
Colin Sherratt7a666df2014-10-19 20:19:07323}
324
Aaron Turon5fa9de12015-02-18 07:44:55325impl<T> VecDeque<T> {
326 /// Creates an empty `VecDeque`.
Brian Andersonb44ee372015-01-24 05:48:20327 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55328 pub fn new() -> VecDeque<T> {
329 VecDeque::with_capacity(INITIAL_CAPACITY)
blake2-ppc70523712013-07-10 13:27:14330 }
331
Aaron Turon5fa9de12015-02-18 07:44:55332 /// Creates an empty `VecDeque` with space for at least `n` elements.
Brian Andersonb44ee372015-01-24 05:48:20333 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55334 pub fn with_capacity(n: usize) -> VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:07335 // +1 since the ringbuffer always leaves one space empty
Piotr Czarnecki156a1c32015-01-05 14:48:58336 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
337 assert!(cap > n, "capacity overflow");
Colin Sherrattba24e332014-11-10 03:34:53338
Aaron Turon5fa9de12015-02-18 07:44:55339 VecDeque {
Colin Sherratt7a666df2014-10-19 20:19:07340 tail: 0,
341 head: 0,
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21342 buf: RawVec::with_capacity(cap),
Colin Sherratt7a666df2014-10-19 20:19:07343 }
blake2-ppc70523712013-07-10 13:27:14344 }
345
Aaron Turon5fa9de12015-02-18 07:44:55346 /// Retrieves an element in the `VecDeque` by index.
blake2-ppc70523712013-07-10 13:27:14347 ///
jbranchaudc09defa2014-12-09 05:28:07348 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47349 ///
Joseph Crailfcf3f322015-03-13 02:42:38350 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55351 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47352 ///
Aaron Turon5fa9de12015-02-18 07:44:55353 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03354 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47355 /// buf.push_back(4);
356 /// buf.push_back(5);
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:13357 /// assert_eq!(buf.get(1), Some(&4));
Alexis Beingessnercf3b2e42014-11-06 17:24:47358 /// ```
Brian Andersonb44ee372015-01-24 05:48:20359 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25360 pub fn get(&self, index: usize) -> Option<&T> {
361 if index < self.len() {
362 let idx = self.wrap_add(self.tail, index);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21363 unsafe { Some(&*self.ptr().offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07364 } else {
365 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47366 }
367 }
368
Aaron Turon5fa9de12015-02-18 07:44:55369 /// Retrieves an element in the `VecDeque` mutably by index.
nhamebe80972014-07-17 23:19:51370 ///
jbranchaudc09defa2014-12-09 05:28:07371 /// # Examples
nhamebe80972014-07-17 23:19:51372 ///
Joseph Crailfcf3f322015-03-13 02:42:38373 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55374 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51375 ///
Aaron Turon5fa9de12015-02-18 07:44:55376 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03377 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47378 /// buf.push_back(4);
379 /// buf.push_back(5);
Corey Farwell68d003c2015-04-18 16:45:05380 /// if let Some(elem) = buf.get_mut(1) {
381 /// *elem = 7;
Alexis Beingessnercf3b2e42014-11-06 17:24:47382 /// }
383 ///
P1startfd10d202014-08-02 06:39:39384 /// assert_eq!(buf[1], 7);
nhamebe80972014-07-17 23:19:51385 /// ```
Brian Andersonb44ee372015-01-24 05:48:20386 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25387 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
388 if index < self.len() {
389 let idx = self.wrap_add(self.tail, index);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21390 unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07391 } else {
392 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47393 }
blake2-ppc70523712013-07-10 13:27:14394 }
395
P1startf2aa88c2014-08-04 10:48:39396 /// Swaps elements at indices `i` and `j`.
blake2-ppc57757a82013-09-26 07:19:26397 ///
398 /// `i` and `j` may be equal.
399 ///
P1startf2aa88c2014-08-04 10:48:39400 /// Fails if there is no element with either index.
nhamebe80972014-07-17 23:19:51401 ///
jbranchaudc09defa2014-12-09 05:28:07402 /// # Examples
nhamebe80972014-07-17 23:19:51403 ///
Joseph Crailfcf3f322015-03-13 02:42:38404 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55405 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51406 ///
Aaron Turon5fa9de12015-02-18 07:44:55407 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03408 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47409 /// buf.push_back(4);
410 /// buf.push_back(5);
nhamebe80972014-07-17 23:19:51411 /// buf.swap(0, 2);
P1startfd10d202014-08-02 06:39:39412 /// assert_eq!(buf[0], 5);
413 /// assert_eq!(buf[2], 3);
nhamebe80972014-07-17 23:19:51414 /// ```
Brian Andersonb44ee372015-01-24 05:48:20415 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19416 pub fn swap(&mut self, i: usize, j: usize) {
blake2-ppc57757a82013-09-26 07:19:26417 assert!(i < self.len());
418 assert!(j < self.len());
Felix S. Klock IIe7c98612015-02-19 07:33:32419 let ri = self.wrap_add(self.tail, i);
420 let rj = self.wrap_add(self.tail, j);
Colin Sherratt7a666df2014-10-19 20:19:07421 unsafe {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21422 ptr::swap(self.ptr().offset(ri as isize), self.ptr().offset(rj as isize))
Colin Sherratt7a666df2014-10-19 20:19:07423 }
blake2-ppc70523712013-07-10 13:27:14424 }
425
Aaron Turon5fa9de12015-02-18 07:44:55426 /// Returns the number of elements the `VecDeque` can hold without
Alexis Beingessnercf3b2e42014-11-06 17:24:47427 /// reallocating.
428 ///
jbranchaudc09defa2014-12-09 05:28:07429 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47430 ///
431 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55432 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47433 ///
Aaron Turon5fa9de12015-02-18 07:44:55434 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
Colin Sherratt7a666df2014-10-19 20:19:07435 /// assert!(buf.capacity() >= 10);
Alexis Beingessnercf3b2e42014-11-06 17:24:47436 /// ```
437 #[inline]
Brian Andersonb44ee372015-01-24 05:48:20438 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21439 pub fn capacity(&self) -> usize { self.cap() - 1 }
Tim Chevalier77de84b2013-05-27 18:47:38440
Alexis Beingessnercf3b2e42014-11-06 17:24:47441 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
Aaron Turon5fa9de12015-02-18 07:44:55442 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
Tim Chevalier77de84b2013-05-27 18:47:38443 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47444 /// Note that the allocator may give the collection more space than it requests. Therefore
445 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
446 /// insertions are expected.
447 ///
448 /// # Panics
449 ///
Alexise250fe32015-02-05 02:17:19450 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47451 ///
jbranchaudc09defa2014-12-09 05:28:07452 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47453 ///
454 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55455 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47456 ///
Aaron Turon5fa9de12015-02-18 07:44:55457 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47458 /// buf.reserve_exact(10);
459 /// assert!(buf.capacity() >= 11);
460 /// ```
Brian Andersonb44ee372015-01-24 05:48:20461 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19462 pub fn reserve_exact(&mut self, additional: usize) {
Colin Sherratt7a666df2014-10-19 20:19:07463 self.reserve(additional);
Alexis Beingessnercf3b2e42014-11-06 17:24:47464 }
465
466 /// Reserves capacity for at least `additional` more elements to be inserted in the given
Corey Richardson8e2ce462015-07-05 07:49:36467 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
Alexis Beingessnercf3b2e42014-11-06 17:24:47468 ///
469 /// # Panics
470 ///
Alexise250fe32015-02-05 02:17:19471 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47472 ///
jbranchaudc09defa2014-12-09 05:28:07473 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47474 ///
475 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55476 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47477 ///
Aaron Turon5fa9de12015-02-18 07:44:55478 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47479 /// buf.reserve(10);
480 /// assert!(buf.capacity() >= 11);
481 /// ```
Brian Andersonb44ee372015-01-24 05:48:20482 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19483 pub fn reserve(&mut self, additional: usize) {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21484 let old_cap = self.cap();
485 let used_cap = self.len() + 1;
486 let new_cap = used_cap
487 .checked_add(additional)
488 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
489 .expect("capacity overflow");
Colin Sherratt7a666df2014-10-19 20:19:07490
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21491 if new_cap > self.capacity() {
492 self.buf.reserve_exact(used_cap, new_cap - used_cap);
493 unsafe { self.handle_cap_increase(old_cap); }
Colin Sherratt7a666df2014-10-19 20:19:07494 }
Tim Chevalier77de84b2013-05-27 18:47:38495 }
Jed Estep4f7a7422013-06-25 19:08:47496
Corey Richardson8e2ce462015-07-05 07:49:36497 /// Shrinks the capacity of the `VecDeque` as much as possible.
Piotr Czarnecki156a1c32015-01-05 14:48:58498 ///
499 /// It will drop down as close as possible to the length but the allocator may still inform the
Corey Richardson8e2ce462015-07-05 07:49:36500 /// `VecDeque` that there is space for a few more elements.
Piotr Czarnecki156a1c32015-01-05 14:48:58501 ///
502 /// # Examples
503 ///
504 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55505 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58506 ///
Aaron Turon5fa9de12015-02-18 07:44:55507 /// let mut buf = VecDeque::with_capacity(15);
Alexise15538d2015-02-06 18:57:13508 /// buf.extend(0..4);
Piotr Czarnecki156a1c32015-01-05 14:48:58509 /// assert_eq!(buf.capacity(), 15);
510 /// buf.shrink_to_fit();
511 /// assert!(buf.capacity() >= 4);
512 /// ```
Alex Crichtonff497332015-10-22 23:28:45513 #[stable(feature = "deque_extras_15", since = "1.5.0")]
Piotr Czarnecki156a1c32015-01-05 14:48:58514 pub fn shrink_to_fit(&mut self) {
515 // +1 since the ringbuffer always leaves one space empty
Corey Richardson8e2ce462015-07-05 07:49:36516 // len + 1 can't overflow for an existing, well-formed ringbuffer.
Piotr Czarnecki156a1c32015-01-05 14:48:58517 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21518 if target_cap < self.cap() {
Piotr Czarnecki156a1c32015-01-05 14:48:58519 // There are three cases of interest:
520 // All elements are out of desired bounds
521 // Elements are contiguous, and head is out of desired bounds
522 // Elements are discontiguous, and tail is out of desired bounds
523 //
524 // At all other times, element positions are unaffected.
525 //
526 // Indicates that elements at the head should be moved.
527 let head_outside = self.head == 0 || self.head >= target_cap;
528 // Move elements from out of desired bounds (positions after target_cap)
529 if self.tail >= target_cap && head_outside {
530 // T H
531 // [. . . . . . . . o o o o o o o . ]
532 // T H
533 // [o o o o o o o . ]
534 unsafe {
535 self.copy_nonoverlapping(0, self.tail, self.len());
536 }
537 self.head = self.len();
538 self.tail = 0;
539 } else if self.tail != 0 && self.tail < target_cap && head_outside {
540 // T H
541 // [. . . o o o o o o o . . . . . . ]
542 // H T
543 // [o o . o o o o o ]
Felix S. Klock IIe7c98612015-02-19 07:33:32544 let len = self.wrap_sub(self.head, target_cap);
Piotr Czarnecki156a1c32015-01-05 14:48:58545 unsafe {
546 self.copy_nonoverlapping(0, target_cap, len);
547 }
548 self.head = len;
549 debug_assert!(self.head < self.tail);
550 } else if self.tail >= target_cap {
551 // H T
552 // [o o o o o . . . . . . . . . o o ]
553 // H T
554 // [o o o o o . o o ]
Felix S. Klock IIe7c98612015-02-19 07:33:32555 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21556 let len = self.cap() - self.tail;
Piotr Czarnecki156a1c32015-01-05 14:48:58557 let new_tail = target_cap - len;
558 unsafe {
559 self.copy_nonoverlapping(new_tail, self.tail, len);
560 }
561 self.tail = new_tail;
562 debug_assert!(self.head < self.tail);
563 }
564
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21565 self.buf.shrink_to_fit(target_cap);
566
567 debug_assert!(self.head < self.cap());
568 debug_assert!(self.tail < self.cap());
569 debug_assert!(self.cap().count_ones() == 1);
Piotr Czarnecki156a1c32015-01-05 14:48:58570 }
571 }
572
Corey Richardson8e2ce462015-07-05 07:49:36573 /// Shortens a `VecDeque`, dropping excess elements from the back.
Piotr Czarnecki156a1c32015-01-05 14:48:58574 ///
Corey Richardson8e2ce462015-07-05 07:49:36575 /// If `len` is greater than the `VecDeque`'s current length, this has no
Piotr Czarnecki156a1c32015-01-05 14:48:58576 /// effect.
577 ///
578 /// # Examples
579 ///
580 /// ```
Steve Klabnikba5fcb72015-07-27 14:50:19581 /// #![feature(deque_extras)]
582 ///
Aaron Turon5fa9de12015-02-18 07:44:55583 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58584 ///
Aaron Turon5fa9de12015-02-18 07:44:55585 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03586 /// buf.push_back(5);
587 /// buf.push_back(10);
Piotr Czarnecki156a1c32015-01-05 14:48:58588 /// buf.push_back(15);
589 /// buf.truncate(1);
590 /// assert_eq!(buf.len(), 1);
591 /// assert_eq!(Some(&5), buf.get(0));
592 /// ```
Alex Crichtond444d0c2015-06-09 21:39:23593 #[unstable(feature = "deque_extras",
Alex Crichton377c11a2015-08-13 05:19:51594 reason = "matches collection reform specification; waiting on panic semantics",
595 issue = "27788")]
Alexise250fe32015-02-05 02:17:19596 pub fn truncate(&mut self, len: usize) {
Jorge Aparicioefc97a52015-01-26 21:05:07597 for _ in len..self.len() {
Piotr Czarnecki156a1c32015-01-05 14:48:58598 self.pop_back();
599 }
600 }
601
P1startf2aa88c2014-08-04 10:48:39602 /// Returns a front-to-back iterator.
nhamebe80972014-07-17 23:19:51603 ///
jbranchaudc09defa2014-12-09 05:28:07604 /// # Examples
nhamebe80972014-07-17 23:19:51605 ///
Joseph Crailfcf3f322015-03-13 02:42:38606 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55607 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51608 ///
Aaron Turon5fa9de12015-02-18 07:44:55609 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03610 /// buf.push_back(5);
Alexis Beingessnercf3b2e42014-11-06 17:24:47611 /// buf.push_back(3);
612 /// buf.push_back(4);
Nick Cameron52ef4622014-08-06 09:59:40613 /// let b: &[_] = &[&5, &3, &4];
Emeliov Dmitriidf65f592015-03-30 16:22:46614 /// let c: Vec<&i32> = buf.iter().collect();
615 /// assert_eq!(&c[..], b);
nhamebe80972014-07-17 23:19:51616 /// ```
Brian Andersonb44ee372015-01-24 05:48:20617 #[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:10618 pub fn iter(&self) -> Iter<T> {
619 Iter {
Colin Sherratt7a666df2014-10-19 20:19:07620 tail: self.tail,
621 head: self.head,
622 ring: unsafe { self.buffer_as_slice() }
623 }
blake2-ppc3385e792013-07-15 23:13:26624 }
625
Andrew Wagner8fcc8322014-12-15 09:22:49626 /// Returns a front-to-back iterator that returns mutable references.
nhamebe80972014-07-17 23:19:51627 ///
jbranchaudc09defa2014-12-09 05:28:07628 /// # Examples
nhamebe80972014-07-17 23:19:51629 ///
Joseph Crailfcf3f322015-03-13 02:42:38630 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55631 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51632 ///
Aaron Turon5fa9de12015-02-18 07:44:55633 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03634 /// buf.push_back(5);
Alexis Beingessnercf3b2e42014-11-06 17:24:47635 /// buf.push_back(3);
636 /// buf.push_back(4);
Aaron Turonfc525ee2014-09-15 03:27:36637 /// for num in buf.iter_mut() {
nhamebe80972014-07-17 23:19:51638 /// *num = *num - 2;
639 /// }
Nick Cameron52ef4622014-08-06 09:59:40640 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
Alex Crichton77de3ee2015-03-26 16:57:58641 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
nhamebe80972014-07-17 23:19:51642 /// ```
Brian Andersonb44ee372015-01-24 05:48:20643 #[stable(feature = "rust1", since = "1.0.0")]
Alexis1420ceb2015-02-05 18:48:20644 pub fn iter_mut(&mut self) -> IterMut<T> {
Florian Wilkensf8cfd242014-12-19 20:52:10645 IterMut {
Colin Sherratt7a666df2014-10-19 20:19:07646 tail: self.tail,
647 head: self.head,
Edward Wang101498c2015-02-25 10:11:23648 ring: unsafe { self.buffer_as_mut_slice() },
Niko Matsakisbc4164d2013-11-16 22:29:39649 }
Jed Estep4f7a7422013-06-25 19:08:47650 }
Alex Crichton21ac9852014-10-30 20:43:24651
Clark Gaebel525f65e2014-12-16 04:01:58652 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55653 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58654 #[inline]
Alex Crichtonff497332015-10-22 23:28:45655 #[stable(feature = "deque_extras_15", since = "1.5.0")]
Alexis1420ceb2015-02-05 18:48:20656 pub fn as_slices(&self) -> (&[T], &[T]) {
Clark Gaebel525f65e2014-12-16 04:01:58657 unsafe {
658 let contiguous = self.is_contiguous();
659 let buf = self.buffer_as_slice();
660 if contiguous {
661 let (empty, buf) = buf.split_at(0);
Jorge Aparicio517f1cc2015-01-07 16:58:31662 (&buf[self.tail..self.head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58663 } else {
664 let (mid, right) = buf.split_at(self.tail);
665 let (left, _) = mid.split_at(self.head);
666 (right, left)
667 }
668 }
669 }
670
671 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55672 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58673 #[inline]
Alex Crichtonff497332015-10-22 23:28:45674 #[stable(feature = "deque_extras_15", since = "1.5.0")]
Alexis1420ceb2015-02-05 18:48:20675 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
Clark Gaebel525f65e2014-12-16 04:01:58676 unsafe {
677 let contiguous = self.is_contiguous();
678 let head = self.head;
679 let tail = self.tail;
680 let buf = self.buffer_as_mut_slice();
681
682 if contiguous {
683 let (empty, buf) = buf.split_at_mut(0);
Aaron Turona506d4c2015-01-18 00:15:52684 (&mut buf[tail .. head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58685 } else {
686 let (mid, right) = buf.split_at_mut(tail);
687 let (left, _) = mid.split_at_mut(head);
688
689 (right, left)
690 }
691 }
692 }
693
Aaron Turon5fa9de12015-02-18 07:44:55694 /// Returns the number of elements in the `VecDeque`.
Alex Crichton21ac9852014-10-30 20:43:24695 ///
jbranchaudc09defa2014-12-09 05:28:07696 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24697 ///
698 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55699 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24700 ///
Aaron Turon5fa9de12015-02-18 07:44:55701 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24702 /// assert_eq!(v.len(), 0);
Tobias Bucher7f64fe42015-01-25 21:05:03703 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24704 /// assert_eq!(v.len(), 1);
705 /// ```
Brian Andersonb44ee372015-01-24 05:48:20706 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21707 pub fn len(&self) -> usize { count(self.tail, self.head, self.cap()) }
Alex Crichton21ac9852014-10-30 20:43:24708
709 /// Returns true if the buffer contains no elements
710 ///
jbranchaudc09defa2014-12-09 05:28:07711 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24712 ///
713 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55714 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24715 ///
Aaron Turon5fa9de12015-02-18 07:44:55716 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24717 /// assert!(v.is_empty());
Tobias Bucher7f64fe42015-01-25 21:05:03718 /// v.push_front(1);
Alex Crichton21ac9852014-10-30 20:43:24719 /// assert!(!v.is_empty());
720 /// ```
Brian Andersonb44ee372015-01-24 05:48:20721 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24722 pub fn is_empty(&self) -> bool { self.len() == 0 }
723
Michael Layzell45be6fc2015-08-07 02:03:14724 /// Create a draining iterator that removes the specified range in the
725 /// `VecDeque` and yields the removed items from start to end. The element
726 /// range is removed even if the iterator is not consumed until the end.
727 ///
728 /// Note: It is unspecified how many elements are removed from the deque,
729 /// if the `Drain` value is not dropped, but the borrow it holds expires
730 /// (eg. due to mem::forget).
731 ///
732 /// # Panics
733 ///
734 /// Panics if the starting point is greater than the end point or if
735 /// the end point is greater than the length of the vector.
Clark Gaebeld57f2592014-12-16 22:45:03736 ///
737 /// # Examples
738 ///
739 /// ```
Steve Klabnikba5fcb72015-07-27 14:50:19740 /// #![feature(drain)]
741 ///
Aaron Turon5fa9de12015-02-18 07:44:55742 /// use std::collections::VecDeque;
Clark Gaebeld57f2592014-12-16 22:45:03743 ///
Michael Layzell45be6fc2015-08-07 02:03:14744 /// // draining using `..` clears the whole deque.
Aaron Turon5fa9de12015-02-18 07:44:55745 /// let mut v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03746 /// v.push_back(1);
Michael Layzell45be6fc2015-08-07 02:03:14747 /// assert_eq!(v.drain(..).next(), Some(1));
Clark Gaebeld57f2592014-12-16 22:45:03748 /// assert!(v.is_empty());
749 /// ```
750 #[inline]
Alex Crichtond444d0c2015-06-09 21:39:23751 #[unstable(feature = "drain",
Alex Crichton377c11a2015-08-13 05:19:51752 reason = "matches collection reform specification, waiting for dust to settle",
753 issue = "27711")]
Michael Layzell45be6fc2015-08-07 02:03:14754 pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> {
755 // Memory safety
756 //
757 // When the Drain is first created, the source deque is shortened to
758 // make sure no uninitialized or moved-from elements are accessible at
759 // all if the Drain's destructor never gets to run.
760 //
761 // Drain will ptr::read out the values to remove.
762 // When finished, the remaining data will be copied back to cover the hole,
763 // and the head/tail values will be restored correctly.
764 //
765 let len = self.len();
766 let start = *range.start().unwrap_or(&0);
767 let end = *range.end().unwrap_or(&len);
768 assert!(start <= end, "drain lower bound was too large");
769 assert!(end <= len, "drain upper bound was too large");
770
771 // The deque's elements are parted into three segments:
772 // * self.tail -> drain_tail
773 // * drain_tail -> drain_head
774 // * drain_head -> self.head
775 //
776 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
777 //
778 // We store drain_tail as self.head, and drain_head and self.head as
779 // after_tail and after_head respectively on the Drain. This also
780 // truncates the effective array such that if the Drain is leaked, we
781 // have forgotten about the potentially moved values after the start of
782 // the drain.
783 //
784 // T t h H
785 // [. . . o o x x o o . . .]
786 //
787 let drain_tail = self.wrap_add(self.tail, start);
788 let drain_head = self.wrap_add(self.tail, end);
789 let head = self.head;
790
791 // "forget" about the values after the start of the drain until after
792 // the drain is complete and the Drain destructor is run.
793 self.head = drain_tail;
794
Clark Gaebeld57f2592014-12-16 22:45:03795 Drain {
Michael Layzell45be6fc2015-08-07 02:03:14796 deque: self as *mut _,
797 after_tail: drain_head,
798 after_head: head,
799 iter: Iter {
800 tail: drain_tail,
801 head: drain_head,
802 ring: unsafe { self.buffer_as_mut_slice() },
803 },
Clark Gaebeld57f2592014-12-16 22:45:03804 }
805 }
806
Alex Crichton21ac9852014-10-30 20:43:24807 /// Clears the buffer, removing all values.
808 ///
jbranchaudc09defa2014-12-09 05:28:07809 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24810 ///
811 /// ```
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 v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03815 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24816 /// v.clear();
817 /// assert!(v.is_empty());
818 /// ```
Brian Andersonb44ee372015-01-24 05:48:20819 #[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:03820 #[inline]
Alex Crichton21ac9852014-10-30 20:43:24821 pub fn clear(&mut self) {
Michael Layzell45be6fc2015-08-07 02:03:14822 self.drain(..);
Alex Crichton21ac9852014-10-30 20:43:24823 }
824
825 /// Provides a reference to the front element, or `None` if the sequence is
826 /// empty.
827 ///
jbranchaudc09defa2014-12-09 05:28:07828 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24829 ///
830 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55831 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24832 ///
Aaron Turon5fa9de12015-02-18 07:44:55833 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24834 /// assert_eq!(d.front(), None);
835 ///
Tobias Bucher7f64fe42015-01-25 21:05:03836 /// d.push_back(1);
837 /// d.push_back(2);
838 /// assert_eq!(d.front(), Some(&1));
Alex Crichton21ac9852014-10-30 20:43:24839 /// ```
Brian Andersonb44ee372015-01-24 05:48:20840 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24841 pub fn front(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07842 if !self.is_empty() { Some(&self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24843 }
844
845 /// Provides a mutable reference to the front element, or `None` if the
846 /// sequence is empty.
847 ///
jbranchaudc09defa2014-12-09 05:28:07848 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24849 ///
850 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55851 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24852 ///
Aaron Turon5fa9de12015-02-18 07:44:55853 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24854 /// assert_eq!(d.front_mut(), None);
855 ///
Tobias Bucher7f64fe42015-01-25 21:05:03856 /// d.push_back(1);
857 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24858 /// match d.front_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03859 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24860 /// None => (),
861 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03862 /// assert_eq!(d.front(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24863 /// ```
Brian Andersonb44ee372015-01-24 05:48:20864 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24865 pub fn front_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07866 if !self.is_empty() { Some(&mut self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24867 }
868
869 /// Provides a reference to the back element, or `None` if the sequence is
870 /// empty.
871 ///
jbranchaudc09defa2014-12-09 05:28:07872 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24873 ///
874 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55875 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24876 ///
Aaron Turon5fa9de12015-02-18 07:44:55877 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24878 /// assert_eq!(d.back(), None);
879 ///
Tobias Bucher7f64fe42015-01-25 21:05:03880 /// d.push_back(1);
881 /// d.push_back(2);
882 /// assert_eq!(d.back(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24883 /// ```
Brian Andersonb44ee372015-01-24 05:48:20884 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24885 pub fn back(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07886 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24887 }
888
889 /// Provides a mutable reference to the back element, or `None` if the
890 /// sequence is empty.
891 ///
jbranchaudc09defa2014-12-09 05:28:07892 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24893 ///
894 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55895 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24896 ///
Aaron Turon5fa9de12015-02-18 07:44:55897 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24898 /// assert_eq!(d.back(), None);
899 ///
Tobias Bucher7f64fe42015-01-25 21:05:03900 /// d.push_back(1);
901 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24902 /// match d.back_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03903 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24904 /// None => (),
905 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03906 /// assert_eq!(d.back(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24907 /// ```
Brian Andersonb44ee372015-01-24 05:48:20908 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24909 pub fn back_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07910 let len = self.len();
911 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24912 }
913
914 /// Removes the first element and returns it, or `None` if the sequence is
915 /// empty.
916 ///
jbranchaudc09defa2014-12-09 05:28:07917 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24918 ///
919 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55920 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24921 ///
Aaron Turon5fa9de12015-02-18 07:44:55922 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03923 /// d.push_back(1);
924 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24925 ///
Tobias Bucher7f64fe42015-01-25 21:05:03926 /// assert_eq!(d.pop_front(), Some(1));
927 /// assert_eq!(d.pop_front(), Some(2));
Alex Crichton21ac9852014-10-30 20:43:24928 /// assert_eq!(d.pop_front(), None);
929 /// ```
Brian Andersonb44ee372015-01-24 05:48:20930 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24931 pub fn pop_front(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07932 if self.is_empty() {
933 None
934 } else {
935 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:32936 self.tail = self.wrap_add(self.tail, 1);
Colin Sherratt7a666df2014-10-19 20:19:07937 unsafe { Some(self.buffer_read(tail)) }
Alex Crichton21ac9852014-10-30 20:43:24938 }
Alex Crichton21ac9852014-10-30 20:43:24939 }
940
941 /// Inserts an element first in the sequence.
942 ///
jbranchaudc09defa2014-12-09 05:28:07943 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24944 ///
945 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55946 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24947 ///
Aaron Turon5fa9de12015-02-18 07:44:55948 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03949 /// d.push_front(1);
950 /// d.push_front(2);
951 /// assert_eq!(d.front(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24952 /// ```
Brian Andersonb44ee372015-01-24 05:48:20953 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25954 pub fn push_front(&mut self, value: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29955 if self.is_full() {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21956 let old_cap = self.cap();
957 self.buf.double();
958 unsafe { self.handle_cap_increase(old_cap); }
Colin Sherratt4cae9ad2014-11-11 02:16:29959 debug_assert!(!self.is_full());
960 }
Colin Sherratt7a666df2014-10-19 20:19:07961
Felix S. Klock IIe7c98612015-02-19 07:33:32962 self.tail = self.wrap_sub(self.tail, 1);
Colin Sherratt7a666df2014-10-19 20:19:07963 let tail = self.tail;
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25964 unsafe { self.buffer_write(tail, value); }
Alex Crichton21ac9852014-10-30 20:43:24965 }
966
967 /// Appends an element to the back of a buffer
968 ///
jbranchaudc09defa2014-12-09 05:28:07969 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24970 ///
Joseph Crailfcf3f322015-03-13 02:42:38971 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55972 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24973 ///
Aaron Turon5fa9de12015-02-18 07:44:55974 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03975 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:47976 /// buf.push_back(3);
Alex Crichton21ac9852014-10-30 20:43:24977 /// assert_eq!(3, *buf.back().unwrap());
978 /// ```
Brian Andersonb44ee372015-01-24 05:48:20979 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25980 pub fn push_back(&mut self, value: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29981 if self.is_full() {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21982 let old_cap = self.cap();
983 self.buf.double();
984 unsafe { self.handle_cap_increase(old_cap); }
Colin Sherratt4cae9ad2014-11-11 02:16:29985 debug_assert!(!self.is_full());
986 }
Colin Sherratt7a666df2014-10-19 20:19:07987
988 let head = self.head;
Felix S. Klock IIe7c98612015-02-19 07:33:32989 self.head = self.wrap_add(self.head, 1);
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25990 unsafe { self.buffer_write(head, value) }
Alex Crichton21ac9852014-10-30 20:43:24991 }
992
993 /// Removes the last element from a buffer and returns it, or `None` if
994 /// it is empty.
995 ///
jbranchaudc09defa2014-12-09 05:28:07996 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24997 ///
Joseph Crailfcf3f322015-03-13 02:42:38998 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55999 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:241000 ///
Aaron Turon5fa9de12015-02-18 07:44:551001 /// let mut buf = VecDeque::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:471002 /// assert_eq!(buf.pop_back(), None);
Tobias Bucher7f64fe42015-01-25 21:05:031003 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:471004 /// buf.push_back(3);
1005 /// assert_eq!(buf.pop_back(), Some(3));
Alex Crichton21ac9852014-10-30 20:43:241006 /// ```
Brian Andersonb44ee372015-01-24 05:48:201007 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnercf3b2e42014-11-06 17:24:471008 pub fn pop_back(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:071009 if self.is_empty() {
Alex Crichton21ac9852014-10-30 20:43:241010 None
Colin Sherratt7a666df2014-10-19 20:19:071011 } else {
Felix S. Klock IIe7c98612015-02-19 07:33:321012 self.head = self.wrap_sub(self.head, 1);
Colin Sherratt7a666df2014-10-19 20:19:071013 let head = self.head;
1014 unsafe { Some(self.buffer_read(head)) }
Alex Crichton21ac9852014-10-30 20:43:241015 }
1016 }
Matt Murphy40f28c72014-12-03 17:12:301017
Clark Gaebel525f65e2014-12-16 04:01:581018 #[inline]
1019 fn is_contiguous(&self) -> bool {
1020 self.tail <= self.head
1021 }
1022
Corey Richardson8e2ce462015-07-05 07:49:361023 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1024 /// last element.
Piotr Czarnecki156a1c32015-01-05 14:48:581025 ///
1026 /// This does not preserve ordering, but is O(1).
1027 ///
1028 /// Returns `None` if `index` is out of bounds.
1029 ///
1030 /// # Examples
1031 ///
1032 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551033 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:581034 ///
Aaron Turon5fa9de12015-02-18 07:44:551035 /// let mut buf = VecDeque::new();
Alex Crichtonff497332015-10-22 23:28:451036 /// assert_eq!(buf.swap_remove_back(0), None);
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131037 /// buf.push_back(1);
1038 /// buf.push_back(2);
1039 /// buf.push_back(3);
1040 ///
Alex Crichtonff497332015-10-22 23:28:451041 /// assert_eq!(buf.swap_remove_back(0), Some(1));
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131042 /// assert_eq!(buf.len(), 2);
1043 /// assert_eq!(buf[0], 3);
1044 /// assert_eq!(buf[1], 2);
Piotr Czarnecki156a1c32015-01-05 14:48:581045 /// ```
Alex Crichtonff497332015-10-22 23:28:451046 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1047 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:581048 let length = self.len();
1049 if length > 0 && index < length - 1 {
1050 self.swap(index, length - 1);
1051 } else if index >= length {
1052 return None;
1053 }
1054 self.pop_back()
1055 }
1056
Alex Crichtonff497332015-10-22 23:28:451057 /// deprecated
1058 #[unstable(feature = "deque_extras",
1059 reason = "the naming of this function may be altered",
1060 issue = "27788")]
1061 #[deprecated(since = "1.5.0", reason = "renamed to swap_remove_back")]
1062 pub fn swap_back_remove(&mut self, index: usize) -> Option<T> {
1063 self.swap_remove_back(index)
1064 }
1065
Corey Richardson8e2ce462015-07-05 07:49:361066 /// Removes an element from anywhere in the `VecDeque` and returns it,
Alex Crichtonce1a9652015-06-10 20:33:521067 /// replacing it with the first element.
Piotr Czarnecki156a1c32015-01-05 14:48:581068 ///
1069 /// This does not preserve ordering, but is O(1).
1070 ///
1071 /// Returns `None` if `index` is out of bounds.
1072 ///
1073 /// # Examples
1074 ///
1075 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551076 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:581077 ///
Aaron Turon5fa9de12015-02-18 07:44:551078 /// let mut buf = VecDeque::new();
Alex Crichtonff497332015-10-22 23:28:451079 /// assert_eq!(buf.swap_remove_front(0), None);
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131080 /// buf.push_back(1);
1081 /// buf.push_back(2);
1082 /// buf.push_back(3);
1083 ///
Alex Crichtonff497332015-10-22 23:28:451084 /// assert_eq!(buf.swap_remove_front(2), Some(3));
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131085 /// assert_eq!(buf.len(), 2);
1086 /// assert_eq!(buf[0], 2);
1087 /// assert_eq!(buf[1], 1);
Piotr Czarnecki156a1c32015-01-05 14:48:581088 /// ```
Alex Crichtonff497332015-10-22 23:28:451089 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1090 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:581091 let length = self.len();
1092 if length > 0 && index < length && index != 0 {
1093 self.swap(index, 0);
1094 } else if index >= length {
1095 return None;
1096 }
1097 self.pop_front()
1098 }
1099
Alex Crichtonff497332015-10-22 23:28:451100 /// deprecated
1101 #[unstable(feature = "deque_extras",
1102 reason = "the naming of this function may be altered",
1103 issue = "27788")]
1104 #[deprecated(since = "1.5.0", reason = "renamed to swap_remove_front")]
1105 pub fn swap_front_remove(&mut self, index: usize) -> Option<T> {
1106 self.swap_remove_front(index)
1107 }
1108
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251109 /// Inserts an element at `index` within the `VecDeque`. Whichever
Matt Murphy40f28c72014-12-03 17:12:301110 /// end is closer to the insertion point will be moved to make room,
1111 /// and all the affected elements will be moved to new positions.
1112 ///
1113 /// # Panics
1114 ///
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251115 /// Panics if `index` is greater than `VecDeque`'s length
Matt Murphy40f28c72014-12-03 17:12:301116 ///
Piotr Czarnecki156a1c32015-01-05 14:48:581117 /// # Examples
Joseph Crailfcf3f322015-03-13 02:42:381118 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551119 /// use std::collections::VecDeque;
Matt Murphy40f28c72014-12-03 17:12:301120 ///
Aaron Turon5fa9de12015-02-18 07:44:551121 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031122 /// buf.push_back(10);
Matt Murphy40f28c72014-12-03 17:12:301123 /// buf.push_back(12);
Tshepang Lekhonkhobe02ae6612015-07-17 18:55:111124 /// buf.insert(1, 11);
Matt Murphy40f28c72014-12-03 17:12:301125 /// assert_eq!(Some(&11), buf.get(1));
1126 /// ```
Alex Crichtonff497332015-10-22 23:28:451127 #[stable(feature = "deque_extras_15", since = "1.5.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251128 pub fn insert(&mut self, index: usize, value: T) {
1129 assert!(index <= self.len(), "index out of bounds");
Matt Murphy40f28c72014-12-03 17:12:301130 if self.is_full() {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211131 let old_cap = self.cap();
1132 self.buf.double();
1133 unsafe { self.handle_cap_increase(old_cap); }
Matt Murphy40f28c72014-12-03 17:12:301134 debug_assert!(!self.is_full());
1135 }
1136
1137 // Move the least number of elements in the ring buffer and insert
1138 // the given object
1139 //
1140 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1141 //
1142 // There are three main cases:
1143 // Elements are contiguous
1144 // - special case when tail is 0
1145 // Elements are discontiguous and the insert is in the tail section
1146 // Elements are discontiguous and the insert is in the head section
1147 //
1148 // For each of those there are two more cases:
1149 // Insert is closer to tail
1150 // Insert is closer to head
1151 //
1152 // Key: H - self.head
1153 // T - self.tail
1154 // o - Valid element
1155 // I - Insertion element
1156 // A - The element that should be after the insertion point
1157 // M - Indicates element was moved
1158
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251159 let idx = self.wrap_add(self.tail, index);
Matt Murphy40f28c72014-12-03 17:12:301160
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251161 let distance_to_tail = index;
1162 let distance_to_head = self.len() - index;
Matt Murphy40f28c72014-12-03 17:12:301163
Clark Gaebel525f65e2014-12-16 04:01:581164 let contiguous = self.is_contiguous();
Matt Murphy40f28c72014-12-03 17:12:301165
1166 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251167 (true, true, _) if index == 0 => {
Matt Murphy40f28c72014-12-03 17:12:301168 // push_front
1169 //
1170 // T
1171 // I H
1172 // [A o o o o o o . . . . . . . . .]
1173 //
1174 // H T
1175 // [A o o o o o o o . . . . . I]
1176 //
1177
Felix S. Klock IIe7c98612015-02-19 07:33:321178 self.tail = self.wrap_sub(self.tail, 1);
Matt Murphy40f28c72014-12-03 17:12:301179 },
Piotr Czarnecki59d41532014-12-16 23:37:551180 (true, true, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:301181 // contiguous, insert closer to tail:
1182 //
1183 // T I H
1184 // [. . . o o A o o o o . . . . . .]
1185 //
1186 // T H
1187 // [. . o o I A o o o o . . . . . .]
1188 // M M
1189 //
1190 // contiguous, insert closer to tail and tail is 0:
1191 //
1192 //
1193 // T I H
1194 // [o o A o o o o . . . . . . . . .]
1195 //
1196 // H T
1197 // [o I A o o o o o . . . . . . . o]
1198 // M M
1199
Felix S. Klock IIe7c98612015-02-19 07:33:321200 let new_tail = self.wrap_sub(self.tail, 1);
Matt Murphy40f28c72014-12-03 17:12:301201
Piotr Czarnecki59d41532014-12-16 23:37:551202 self.copy(new_tail, self.tail, 1);
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251203 // Already moved the tail, so we only copy `index - 1` elements.
1204 self.copy(self.tail, self.tail + 1, index - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551205
1206 self.tail = new_tail;
Matt Murphy40f28c72014-12-03 17:12:301207 },
Piotr Czarnecki59d41532014-12-16 23:37:551208 (true, false, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:301209 // contiguous, insert closer to head:
1210 //
1211 // T I H
1212 // [. . . o o o o A o o . . . . . .]
1213 //
1214 // T H
1215 // [. . . o o o o I A o o . . . . .]
1216 // M M M
1217
Piotr Czarnecki59d41532014-12-16 23:37:551218 self.copy(idx + 1, idx, self.head - idx);
Felix S. Klock IIe7c98612015-02-19 07:33:321219 self.head = self.wrap_add(self.head, 1);
Matt Murphy40f28c72014-12-03 17:12:301220 },
Piotr Czarnecki59d41532014-12-16 23:37:551221 (false, true, true) => unsafe {
1222 // discontiguous, insert closer to tail, tail section:
Matt Murphy40f28c72014-12-03 17:12:301223 //
1224 // H T I
1225 // [o o o o o o . . . . . o o A o o]
1226 //
1227 // H T
1228 // [o o o o o o . . . . o o I A o o]
1229 // M M
1230
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251231 self.copy(self.tail - 1, self.tail, index);
Piotr Czarnecki59d41532014-12-16 23:37:551232 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301233 },
Piotr Czarnecki59d41532014-12-16 23:37:551234 (false, false, true) => unsafe {
1235 // discontiguous, insert closer to head, tail section:
Matt Murphy40f28c72014-12-03 17:12:301236 //
1237 // H T I
1238 // [o o . . . . . . . o o o o o A o]
1239 //
1240 // H T
1241 // [o o o . . . . . . o o o o o I A]
1242 // M M M M
1243
Matt Murphy40f28c72014-12-03 17:12:301244 // copy elements up to new head
Piotr Czarnecki59d41532014-12-16 23:37:551245 self.copy(1, 0, self.head);
Matt Murphy40f28c72014-12-03 17:12:301246
1247 // copy last element into empty spot at bottom of buffer
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211248 self.copy(0, self.cap() - 1, 1);
Matt Murphy40f28c72014-12-03 17:12:301249
1250 // move elements from idx to end forward not including ^ element
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211251 self.copy(idx + 1, idx, self.cap() - 1 - idx);
Piotr Czarnecki59d41532014-12-16 23:37:551252
1253 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301254 },
Piotr Czarnecki59d41532014-12-16 23:37:551255 (false, true, false) if idx == 0 => unsafe {
1256 // discontiguous, insert is closer to tail, head section,
Matt Murphy40f28c72014-12-03 17:12:301257 // and is at index zero in the internal buffer:
1258 //
1259 // I H T
1260 // [A o o o o o o o o o . . . o o o]
1261 //
1262 // H T
1263 // [A o o o o o o o o o . . o o o I]
1264 // M M M
1265
Matt Murphy40f28c72014-12-03 17:12:301266 // copy elements up to new tail
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211267 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301268
1269 // copy last element into empty spot at bottom of buffer
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211270 self.copy(self.cap() - 1, 0, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551271
1272 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301273 },
Piotr Czarnecki59d41532014-12-16 23:37:551274 (false, true, false) => unsafe {
1275 // discontiguous, insert closer to tail, head section:
Matt Murphy40f28c72014-12-03 17:12:301276 //
1277 // I H T
1278 // [o o o A o o o o o o . . . o o o]
1279 //
1280 // H T
1281 // [o o I A o o o o o o . . o o o o]
1282 // M M M M M M
1283
Matt Murphy40f28c72014-12-03 17:12:301284 // copy elements up to new tail
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211285 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301286
1287 // copy last element into empty spot at bottom of buffer
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211288 self.copy(self.cap() - 1, 0, 1);
Matt Murphy40f28c72014-12-03 17:12:301289
1290 // move elements from idx-1 to end forward not including ^ element
1291 self.copy(0, 1, idx - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551292
1293 self.tail -= 1;
1294 },
1295 (false, false, false) => unsafe {
1296 // discontiguous, insert closer to head, head section:
Matt Murphy40f28c72014-12-03 17:12:301297 //
1298 // I H T
1299 // [o o o o A o o . . . . . . o o o]
1300 //
1301 // H T
1302 // [o o o o I A o o . . . . . o o o]
1303 // M M M
1304
Piotr Czarnecki59d41532014-12-16 23:37:551305 self.copy(idx + 1, idx, self.head - idx);
1306 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301307 }
1308 }
1309
1310 // tail might've been changed so we need to recalculate
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251311 let new_idx = self.wrap_add(self.tail, index);
Matt Murphy40f28c72014-12-03 17:12:301312 unsafe {
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251313 self.buffer_write(new_idx, value);
Matt Murphy40f28c72014-12-03 17:12:301314 }
1315 }
Piotr Czarnecki59d41532014-12-16 23:37:551316
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251317 /// Removes and returns the element at `index` from the `VecDeque`.
Piotr Czarnecki59d41532014-12-16 23:37:551318 /// Whichever end is closer to the removal point will be moved to make
1319 /// room, and all the affected elements will be moved to new positions.
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251320 /// Returns `None` if `index` is out of bounds.
Piotr Czarnecki59d41532014-12-16 23:37:551321 ///
Piotr Czarnecki156a1c32015-01-05 14:48:581322 /// # Examples
Joseph Crailfcf3f322015-03-13 02:42:381323 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551324 /// use std::collections::VecDeque;
Piotr Czarnecki59d41532014-12-16 23:37:551325 ///
Aaron Turon5fa9de12015-02-18 07:44:551326 /// let mut buf = VecDeque::new();
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131327 /// buf.push_back(1);
1328 /// buf.push_back(2);
1329 /// buf.push_back(3);
1330 ///
1331 /// assert_eq!(buf.remove(1), Some(2));
1332 /// assert_eq!(buf.get(1), Some(&3));
Piotr Czarnecki59d41532014-12-16 23:37:551333 /// ```
Brian Andersonb44ee372015-01-24 05:48:201334 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251335 pub fn remove(&mut self, index: usize) -> Option<T> {
1336 if self.is_empty() || self.len() <= index {
Piotr Czarnecki59d41532014-12-16 23:37:551337 return None;
1338 }
1339
1340 // There are three main cases:
1341 // Elements are contiguous
1342 // Elements are discontiguous and the removal is in the tail section
1343 // Elements are discontiguous and the removal is in the head section
1344 // - special case when elements are technically contiguous,
1345 // but self.head = 0
1346 //
1347 // For each of those there are two more cases:
1348 // Insert is closer to tail
1349 // Insert is closer to head
1350 //
1351 // Key: H - self.head
1352 // T - self.tail
1353 // o - Valid element
1354 // x - Element marked for removal
1355 // R - Indicates element that is being removed
1356 // M - Indicates element was moved
1357
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251358 let idx = self.wrap_add(self.tail, index);
Piotr Czarnecki59d41532014-12-16 23:37:551359
1360 let elem = unsafe {
1361 Some(self.buffer_read(idx))
1362 };
1363
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251364 let distance_to_tail = index;
1365 let distance_to_head = self.len() - index;
Piotr Czarnecki59d41532014-12-16 23:37:551366
Piotr Czarnecki156a1c32015-01-05 14:48:581367 let contiguous = self.is_contiguous();
Piotr Czarnecki59d41532014-12-16 23:37:551368
1369 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1370 (true, true, _) => unsafe {
1371 // contiguous, remove closer to tail:
1372 //
1373 // T R H
1374 // [. . . o o x o o o o . . . . . .]
1375 //
1376 // T H
1377 // [. . . . o o o o o o . . . . . .]
1378 // M M
1379
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251380 self.copy(self.tail + 1, self.tail, index);
Piotr Czarnecki59d41532014-12-16 23:37:551381 self.tail += 1;
1382 },
1383 (true, false, _) => unsafe {
1384 // contiguous, remove closer to head:
1385 //
1386 // T R H
1387 // [. . . o o o o x o o . . . . . .]
1388 //
1389 // T H
1390 // [. . . o o o o o o . . . . . . .]
1391 // M M
1392
1393 self.copy(idx, idx + 1, self.head - idx - 1);
1394 self.head -= 1;
1395 },
1396 (false, true, true) => unsafe {
1397 // discontiguous, remove closer to tail, tail section:
1398 //
1399 // H T R
1400 // [o o o o o o . . . . . o o x o o]
1401 //
1402 // H T
1403 // [o o o o o o . . . . . . o o o o]
1404 // M M
1405
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251406 self.copy(self.tail + 1, self.tail, index);
Felix S. Klock IIe7c98612015-02-19 07:33:321407 self.tail = self.wrap_add(self.tail, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551408 },
1409 (false, false, false) => unsafe {
1410 // discontiguous, remove closer to head, head section:
1411 //
1412 // R H T
1413 // [o o o o x o o . . . . . . o o o]
1414 //
1415 // H T
1416 // [o o o o o o . . . . . . . o o o]
1417 // M M
1418
1419 self.copy(idx, idx + 1, self.head - idx - 1);
1420 self.head -= 1;
1421 },
1422 (false, false, true) => unsafe {
1423 // discontiguous, remove closer to head, tail section:
1424 //
1425 // H T R
1426 // [o o o . . . . . . o o o o o x o]
1427 //
1428 // H T
1429 // [o o . . . . . . . o o o o o o o]
1430 // M M M M
1431 //
1432 // or quasi-discontiguous, remove next to head, tail section:
1433 //
1434 // H T R
1435 // [. . . . . . . . . o o o o o x o]
1436 //
1437 // T H
1438 // [. . . . . . . . . o o o o o o .]
1439 // M
1440
1441 // draw in elements in the tail section
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211442 self.copy(idx, idx + 1, self.cap() - idx - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551443
1444 // Prevents underflow.
1445 if self.head != 0 {
1446 // copy first element into empty spot
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211447 self.copy(self.cap() - 1, 0, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551448
1449 // move elements in the head section backwards
1450 self.copy(0, 1, self.head - 1);
1451 }
1452
Felix S. Klock IIe7c98612015-02-19 07:33:321453 self.head = self.wrap_sub(self.head, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551454 },
1455 (false, true, false) => unsafe {
1456 // discontiguous, remove closer to tail, head section:
1457 //
1458 // R H T
1459 // [o o x o o o o o o o . . . o o o]
1460 //
1461 // H T
1462 // [o o o o o o o o o o . . . . o o]
1463 // M M M M M
1464
1465 // draw in elements up to idx
1466 self.copy(1, 0, idx);
1467
1468 // copy last element into empty spot
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211469 self.copy(0, self.cap() - 1, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551470
1471 // move elements from tail to end forward, excluding the last one
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211472 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551473
Felix S. Klock IIe7c98612015-02-19 07:33:321474 self.tail = self.wrap_add(self.tail, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551475 }
1476 }
1477
1478 return elem;
1479 }
Alexisdc930b12015-02-07 16:46:161480
1481 /// Splits the collection into two at the given index.
1482 ///
1483 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1484 /// and the returned `Self` contains elements `[at, len)`.
1485 ///
1486 /// Note that the capacity of `self` does not change.
1487 ///
1488 /// # Panics
1489 ///
1490 /// Panics if `at > len`
1491 ///
1492 /// # Examples
Alexis3c18bc42015-02-07 17:13:321493 ///
1494 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551495 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321496 ///
Aaron Turon5fa9de12015-02-18 07:44:551497 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
Alexisdc930b12015-02-07 16:46:161498 /// let buf2 = buf.split_off(1);
1499 /// // buf = [1], buf2 = [2, 3]
1500 /// assert_eq!(buf.len(), 1);
1501 /// assert_eq!(buf2.len(), 2);
1502 /// ```
1503 #[inline]
Alex Crichtonf0b13262015-09-10 20:26:441504 #[stable(feature = "split_off", since = "1.4.0")]
Alexisdc930b12015-02-07 16:46:161505 pub fn split_off(&mut self, at: usize) -> Self {
1506 let len = self.len();
1507 assert!(at <= len, "`at` out of bounds");
1508
1509 let other_len = len - at;
Aaron Turon5fa9de12015-02-18 07:44:551510 let mut other = VecDeque::with_capacity(other_len);
Alexisdc930b12015-02-07 16:46:161511
1512 unsafe {
1513 let (first_half, second_half) = self.as_slices();
1514
1515 let first_len = first_half.len();
1516 let second_len = second_half.len();
1517 if at < first_len {
1518 // `at` lies in the first half.
1519 let amount_in_first = first_len - at;
1520
Alex Crichtonacd48a22015-03-27 18:12:281521 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211522 other.ptr(),
Alex Crichtonab456942015-02-23 19:39:161523 amount_in_first);
Alexisdc930b12015-02-07 16:46:161524
1525 // just take all of the second half.
Alex Crichtonacd48a22015-03-27 18:12:281526 ptr::copy_nonoverlapping(second_half.as_ptr(),
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211527 other.ptr().offset(amount_in_first as isize),
Alex Crichtonab456942015-02-23 19:39:161528 second_len);
Alexisdc930b12015-02-07 16:46:161529 } else {
1530 // `at` lies in the second half, need to factor in the elements we skipped
1531 // in the first half.
1532 let offset = at - first_len;
1533 let amount_in_second = second_len - offset;
Alex Crichtonacd48a22015-03-27 18:12:281534 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211535 other.ptr(),
Alex Crichtonab456942015-02-23 19:39:161536 amount_in_second);
Alexisdc930b12015-02-07 16:46:161537 }
1538 }
1539
1540 // Cleanup where the ends of the buffers are
Felix S. Klock IIe7c98612015-02-19 07:33:321541 self.head = self.wrap_sub(self.head, other_len);
Alexisdc930b12015-02-07 16:46:161542 other.head = other.wrap_index(other_len);
1543
1544 other
1545 }
Alexis3c18bc42015-02-07 17:13:321546
1547 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1548 ///
1549 /// # Panics
1550 ///
1551 /// Panics if the new number of elements in self overflows a `usize`.
1552 ///
1553 /// # Examples
1554 ///
1555 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551556 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321557 ///
Aaron Turon5fa9de12015-02-18 07:44:551558 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1559 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
Alexis3c18bc42015-02-07 17:13:321560 /// buf.append(&mut buf2);
1561 /// assert_eq!(buf.len(), 6);
1562 /// assert_eq!(buf2.len(), 0);
1563 /// ```
1564 #[inline]
Alex Crichtonf0b13262015-09-10 20:26:441565 #[stable(feature = "append", since = "1.4.0")]
Alexis3c18bc42015-02-07 17:13:321566 pub fn append(&mut self, other: &mut Self) {
1567 // naive impl
Michael Layzell45be6fc2015-08-07 02:03:141568 self.extend(other.drain(..));
Alexis3c18bc42015-02-07 17:13:321569 }
Steven Allendecf3952015-04-27 17:47:191570
1571 /// Retains only the elements specified by the predicate.
1572 ///
1573 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1574 /// This method operates in place and preserves the order of the retained
1575 /// elements.
1576 ///
1577 /// # Examples
1578 ///
1579 /// ```
Steven Allendecf3952015-04-27 17:47:191580 /// use std::collections::VecDeque;
1581 ///
1582 /// let mut buf = VecDeque::new();
1583 /// buf.extend(1..5);
1584 /// buf.retain(|&x| x%2 == 0);
1585 ///
1586 /// let v: Vec<_> = buf.into_iter().collect();
1587 /// assert_eq!(&v[..], &[2, 4]);
1588 /// ```
Alex Crichtonf0b13262015-09-10 20:26:441589 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
Steven Allendecf3952015-04-27 17:47:191590 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
1591 let len = self.len();
1592 let mut del = 0;
1593 for i in 0..len {
1594 if !f(&self[i]) {
1595 del += 1;
1596 } else if del > 0 {
1597 self.swap(i-del, i);
1598 }
1599 }
1600 if del > 0 {
1601 self.truncate(len - del);
1602 }
1603 }
Jed Estep4f7a7422013-06-25 19:08:471604}
1605
Aaron Turon5fa9de12015-02-18 07:44:551606impl<T: Clone> VecDeque<T> {
Corey Richardson8e2ce462015-07-05 07:49:361607 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
Piotr Czarnecki156a1c32015-01-05 14:48:581608 /// either by removing excess elements or by appending copies of a value to the back.
1609 ///
1610 /// # Examples
1611 ///
1612 /// ```
Steve Klabnikba5fcb72015-07-27 14:50:191613 /// #![feature(deque_extras)]
1614 ///
Aaron Turon5fa9de12015-02-18 07:44:551615 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:581616 ///
Aaron Turon5fa9de12015-02-18 07:44:551617 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031618 /// buf.push_back(5);
1619 /// buf.push_back(10);
Piotr Czarnecki156a1c32015-01-05 14:48:581620 /// buf.push_back(15);
1621 /// buf.resize(2, 0);
1622 /// buf.resize(6, 20);
Joshua Landauca7418b2015-06-10 16:22:201623 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
Piotr Czarnecki156a1c32015-01-05 14:48:581624 /// assert_eq!(a, b);
1625 /// }
1626 /// ```
Alex Crichtond444d0c2015-06-09 21:39:231627 #[unstable(feature = "deque_extras",
Alex Crichton377c11a2015-08-13 05:19:511628 reason = "matches collection reform specification; waiting on panic semantics",
1629 issue = "27788")]
Alexise250fe32015-02-05 02:17:191630 pub fn resize(&mut self, new_len: usize, value: T) {
Piotr Czarnecki156a1c32015-01-05 14:48:581631 let len = self.len();
1632
1633 if new_len > len {
1634 self.extend(repeat(value).take(new_len - len))
1635 } else {
1636 self.truncate(new_len);
1637 }
1638 }
1639}
1640
Colin Sherratt7a666df2014-10-19 20:19:071641/// Returns the index in the underlying buffer for a given logical element index.
1642#[inline]
Alexise250fe32015-02-05 02:17:191643fn wrap_index(index: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071644 // size is always a power of 2
Ulrik Sverdrup66f5dc12015-09-18 14:32:521645 debug_assert!(size.is_power_of_two());
Colin Sherratt40191182014-11-12 01:22:071646 index & (size - 1)
Colin Sherratt7a666df2014-10-19 20:19:071647}
1648
1649/// Calculate the number of elements left to be read in the buffer
1650#[inline]
Alexise250fe32015-02-05 02:17:191651fn count(tail: usize, head: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071652 // size is always a power of 2
Felix S. Klock IIe7c98612015-02-19 07:33:321653 (head.wrapping_sub(tail)) & (size - 1)
Colin Sherratt7a666df2014-10-19 20:19:071654}
1655
Aaron Turon5fa9de12015-02-18 07:44:551656/// `VecDeque` iterator.
Brian Andersonb44ee372015-01-24 05:48:201657#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101658pub struct Iter<'a, T:'a> {
Colin Sherratt7a666df2014-10-19 20:19:071659 ring: &'a [T],
Alexise250fe32015-02-05 02:17:191660 tail: usize,
1661 head: usize
Niko Matsakis1b487a82014-08-28 01:46:521662}
1663
Jorge Aparicio351409a2015-01-04 03:54:181664// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
Vadim Petrochenkov7e2ffc72015-11-16 16:54:281665#[stable(feature = "rust1", since = "1.0.0")]
Huon Wilsonb7832ed2014-12-30 10:01:361666impl<'a, T> Clone for Iter<'a, T> {
1667 fn clone(&self) -> Iter<'a, T> {
1668 Iter {
1669 ring: self.ring,
1670 tail: self.tail,
1671 head: self.head
1672 }
1673 }
1674}
1675
Brian Andersonb44ee372015-01-24 05:48:201676#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351677impl<'a, T> Iterator for Iter<'a, T> {
1678 type Item = &'a T;
1679
Niko Matsakisbc4164d2013-11-16 22:29:391680 #[inline]
Erik Price5731ca32013-12-10 07:16:181681 fn next(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071682 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391683 return None;
1684 }
Colin Sherratt7a666df2014-10-19 20:19:071685 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:321686 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181687 unsafe { Some(self.ring.get_unchecked(tail)) }
Niko Matsakisbc4164d2013-11-16 22:29:391688 }
1689
1690 #[inline]
Alexise250fe32015-02-05 02:17:191691 fn size_hint(&self) -> (usize, Option<usize>) {
Colin Sherratt7a666df2014-10-19 20:19:071692 let len = count(self.tail, self.head, self.ring.len());
Niko Matsakisbc4164d2013-11-16 22:29:391693 (len, Some(len))
1694 }
1695}
1696
Brian Andersonb44ee372015-01-24 05:48:201697#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351698impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391699 #[inline]
Erik Price5731ca32013-12-10 07:16:181700 fn next_back(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071701 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391702 return None;
1703 }
Felix S. Klock IIe7c98612015-02-19 07:33:321704 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181705 unsafe { Some(self.ring.get_unchecked(self.head)) }
Niko Matsakisbc4164d2013-11-16 22:29:391706 }
1707}
Jed Estep35314c92013-06-26 15:38:291708
Brian Andersonb44ee372015-01-24 05:48:201709#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351710impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241711
Aaron Turon5fa9de12015-02-18 07:44:551712/// `VecDeque` mutable iterator.
Brian Andersonb44ee372015-01-24 05:48:201713#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101714pub struct IterMut<'a, T:'a> {
Edward Wang101498c2015-02-25 10:11:231715 ring: &'a mut [T],
Alexise250fe32015-02-05 02:17:191716 tail: usize,
1717 head: usize,
Niko Matsakis1b487a82014-08-28 01:46:521718}
1719
Brian Andersonb44ee372015-01-24 05:48:201720#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351721impl<'a, T> Iterator for IterMut<'a, T> {
1722 type Item = &'a mut T;
1723
Niko Matsakisbc4164d2013-11-16 22:29:391724 #[inline]
Erik Price5731ca32013-12-10 07:16:181725 fn next(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:071726 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391727 return None;
1728 }
Colin Sherratt7a666df2014-10-19 20:19:071729 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:321730 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111731
1732 unsafe {
Edward Wang101498c2015-02-25 10:11:231733 let elem = self.ring.get_unchecked_mut(tail);
1734 Some(&mut *(elem as *mut _))
Alex Crichton9d5d97b2014-10-15 06:05:011735 }
Niko Matsakisbc4164d2013-11-16 22:29:391736 }
1737
1738 #[inline]
Alexise250fe32015-02-05 02:17:191739 fn size_hint(&self) -> (usize, Option<usize>) {
Edward Wang101498c2015-02-25 10:11:231740 let len = count(self.tail, self.head, self.ring.len());
Colin Sherratt7a666df2014-10-19 20:19:071741 (len, Some(len))
Niko Matsakisbc4164d2013-11-16 22:29:391742 }
1743}
1744
Brian Andersonb44ee372015-01-24 05:48:201745#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351746impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391747 #[inline]
Erik Price5731ca32013-12-10 07:16:181748 fn next_back(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:071749 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391750 return None;
1751 }
Felix S. Klock IIe7c98612015-02-19 07:33:321752 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111753
1754 unsafe {
Edward Wang101498c2015-02-25 10:11:231755 let elem = self.ring.get_unchecked_mut(self.head);
1756 Some(&mut *(elem as *mut _))
Alexis Beingessner865c2db2014-11-23 02:34:111757 }
Niko Matsakisbc4164d2013-11-16 22:29:391758 }
1759}
Daniel Micayb47e1e92013-02-16 22:55:551760
Brian Andersonb44ee372015-01-24 05:48:201761#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351762impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241763
Aaron Turon5fa9de12015-02-18 07:44:551764/// A by-value VecDeque iterator
Andrew Paseltiner64532f72015-03-23 12:50:471765#[derive(Clone)]
Brian Andersonb44ee372015-01-24 05:48:201766#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101767pub struct IntoIter<T> {
Aaron Turon5fa9de12015-02-18 07:44:551768 inner: VecDeque<T>,
Alexis Beingessner865c2db2014-11-23 02:34:111769}
1770
Brian Andersonb44ee372015-01-24 05:48:201771#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351772impl<T> Iterator for IntoIter<T> {
1773 type Item = T;
1774
Alexis Beingessner865c2db2014-11-23 02:34:111775 #[inline]
1776 fn next(&mut self) -> Option<T> {
1777 self.inner.pop_front()
1778 }
1779
1780 #[inline]
Alexise250fe32015-02-05 02:17:191781 fn size_hint(&self) -> (usize, Option<usize>) {
Alexis Beingessner865c2db2014-11-23 02:34:111782 let len = self.inner.len();
1783 (len, Some(len))
1784 }
1785}
1786
Brian Andersonb44ee372015-01-24 05:48:201787#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351788impl<T> DoubleEndedIterator for IntoIter<T> {
Alexis Beingessner865c2db2014-11-23 02:34:111789 #[inline]
1790 fn next_back(&mut self) -> Option<T> {
1791 self.inner.pop_back()
1792 }
1793}
1794
Brian Andersonb44ee372015-01-24 05:48:201795#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351796impl<T> ExactSizeIterator for IntoIter<T> {}
Alexis Beingessner865c2db2014-11-23 02:34:111797
Aaron Turon5fa9de12015-02-18 07:44:551798/// A draining VecDeque iterator
Alex Crichtond444d0c2015-06-09 21:39:231799#[unstable(feature = "drain",
Alex Crichton377c11a2015-08-13 05:19:511800 reason = "matches collection reform specification, waiting for dust to settle",
1801 issue = "27711")]
Clark Gaebeld57f2592014-12-16 22:45:031802pub struct Drain<'a, T: 'a> {
Michael Layzell45be6fc2015-08-07 02:03:141803 after_tail: usize,
1804 after_head: usize,
1805 iter: Iter<'a, T>,
1806 deque: *mut VecDeque<T>,
Clark Gaebeld57f2592014-12-16 22:45:031807}
1808
Vadim Petrochenkov7e2ffc72015-11-16 16:54:281809#[unstable(feature = "drain", issue = "27711")]
Michael Layzell493355d2015-09-24 22:19:231810unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
Vadim Petrochenkov7e2ffc72015-11-16 16:54:281811#[unstable(feature = "drain", issue = "27711")]
Michael Layzell493355d2015-09-24 22:19:231812unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1813
Brian Andersonb44ee372015-01-24 05:48:201814#[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:031815impl<'a, T: 'a> Drop for Drain<'a, T> {
1816 fn drop(&mut self) {
Jorge Apariciof9865ea2015-01-11 02:50:071817 for _ in self.by_ref() {}
Michael Layzell45be6fc2015-08-07 02:03:141818
1819 let source_deque = unsafe { &mut *self.deque };
1820
1821 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
1822 //
1823 // T t h H
1824 // [. . . o o x x o o . . .]
1825 //
1826 let orig_tail = source_deque.tail;
1827 let drain_tail = source_deque.head;
1828 let drain_head = self.after_tail;
1829 let orig_head = self.after_head;
1830
1831 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
1832 let head_len = count(drain_head, orig_head, source_deque.cap());
1833
1834 // Restore the original head value
1835 source_deque.head = orig_head;
1836
1837 match (tail_len, head_len) {
1838 (0, 0) => {
1839 source_deque.head = 0;
1840 source_deque.tail = 0;
1841 }
1842 (0, _) => {
1843 source_deque.tail = drain_head;
1844 }
1845 (_, 0) => {
1846 source_deque.head = drain_tail;
1847 }
1848 _ => unsafe {
1849 if tail_len <= head_len {
1850 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
1851 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
1852 } else {
1853 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
1854 source_deque.wrap_copy(drain_tail, drain_head, head_len);
1855 }
1856 }
1857 }
Clark Gaebeld57f2592014-12-16 22:45:031858 }
1859}
1860
Brian Andersonb44ee372015-01-24 05:48:201861#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351862impl<'a, T: 'a> Iterator for Drain<'a, T> {
1863 type Item = T;
1864
Clark Gaebeld57f2592014-12-16 22:45:031865 #[inline]
1866 fn next(&mut self) -> Option<T> {
Michael Layzell45be6fc2015-08-07 02:03:141867 self.iter.next().map(|elt|
1868 unsafe {
1869 ptr::read(elt)
1870 }
1871 )
Clark Gaebeld57f2592014-12-16 22:45:031872 }
1873
1874 #[inline]
Alexise250fe32015-02-05 02:17:191875 fn size_hint(&self) -> (usize, Option<usize>) {
Michael Layzell45be6fc2015-08-07 02:03:141876 self.iter.size_hint()
Clark Gaebeld57f2592014-12-16 22:45:031877 }
1878}
1879
Brian Andersonb44ee372015-01-24 05:48:201880#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351881impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
Clark Gaebeld57f2592014-12-16 22:45:031882 #[inline]
1883 fn next_back(&mut self) -> Option<T> {
Michael Layzell45be6fc2015-08-07 02:03:141884 self.iter.next_back().map(|elt|
1885 unsafe {
1886 ptr::read(elt)
1887 }
1888 )
Clark Gaebeld57f2592014-12-16 22:45:031889 }
1890}
1891
Brian Andersonb44ee372015-01-24 05:48:201892#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351893impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
Clark Gaebeld57f2592014-12-16 22:45:031894
Brian Andersonb44ee372015-01-24 05:48:201895#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551896impl<A: PartialEq> PartialEq for VecDeque<A> {
1897 fn eq(&self, other: &VecDeque<A>) -> bool {
Colin Sherratt7a666df2014-10-19 20:19:071898 self.len() == other.len() &&
Joshua Landauca7418b2015-06-10 16:22:201899 self.iter().zip(other).all(|(a, b)| a.eq(b))
blake2-ppc10c76982013-07-06 13:27:321900 }
blake2-ppc10c76982013-07-06 13:27:321901}
1902
Brian Andersonb44ee372015-01-24 05:48:201903#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551904impl<A: Eq> Eq for VecDeque<A> {}
nham25acfde2014-08-01 20:05:031905
Brian Andersonb44ee372015-01-24 05:48:201906#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551907impl<A: PartialOrd> PartialOrd for VecDeque<A> {
1908 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
Steven Fackler651c42f2015-08-24 04:59:071909 self.iter().partial_cmp(other.iter())
nham63615772014-07-27 03:18:561910 }
1911}
1912
Brian Andersonb44ee372015-01-24 05:48:201913#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551914impl<A: Ord> Ord for VecDeque<A> {
nham3737c532014-08-01 20:22:481915 #[inline]
Aaron Turon5fa9de12015-02-18 07:44:551916 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
Steven Fackler651c42f2015-08-24 04:59:071917 self.iter().cmp(other.iter())
nham3737c532014-08-01 20:22:481918 }
1919}
1920
Brian Andersonb44ee372015-01-24 05:48:201921#[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton5a32b4a2015-02-18 22:34:081922impl<A: Hash> Hash for VecDeque<A> {
Alex Crichtonf83e23a2015-02-18 04:48:071923 fn hash<H: Hasher>(&self, state: &mut H) {
1924 self.len().hash(state);
1925 for elt in self {
1926 elt.hash(state);
1927 }
1928 }
1929}
nham1cfa6562014-07-27 02:33:471930
Brian Andersonb44ee372015-01-24 05:48:201931#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551932impl<A> Index<usize> for VecDeque<A> {
Jorge Aparicio32dd5922015-01-03 15:40:101933 type Output = A;
1934
Niko Matsakisb4d4daf2015-03-21 23:33:271935 #[inline]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251936 fn index(&self, index: usize) -> &A {
1937 self.get(index).expect("Out of bounds access")
Niko Matsakisb4d4daf2015-03-21 23:33:271938 }
Jorge Aparicio32dd5922015-01-03 15:40:101939}
1940
Brian Andersonb44ee372015-01-24 05:48:201941#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551942impl<A> IndexMut<usize> for VecDeque<A> {
Niko Matsakisb4d4daf2015-03-21 23:33:271943 #[inline]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251944 fn index_mut(&mut self, index: usize) -> &mut A {
1945 self.get_mut(index).expect("Out of bounds access")
Niko Matsakisb4d4daf2015-03-21 23:33:271946 }
Jorge Aparicio32dd5922015-01-03 15:40:101947}
1948
Brian Andersonb44ee372015-01-24 05:48:201949#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551950impl<A> FromIterator<A> for VecDeque<A> {
Alexis66613e22015-02-18 18:06:211951 fn from_iter<T: IntoIterator<Item=A>>(iterable: T) -> VecDeque<A> {
1952 let iterator = iterable.into_iter();
blake2-ppcf8ae5262013-07-30 00:06:491953 let (lower, _) = iterator.size_hint();
Aaron Turon5fa9de12015-02-18 07:44:551954 let mut deq = VecDeque::with_capacity(lower);
blake2-ppcf8ae5262013-07-30 00:06:491955 deq.extend(iterator);
blake2-ppc08dc72f2013-07-06 03:42:451956 deq
1957 }
1958}
1959
Alex Crichtoncc687862015-02-17 18:06:241960#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551961impl<T> IntoIterator for VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101962 type Item = T;
1963 type IntoIter = IntoIter<T>;
1964
Alex Crichton8f5b5f92015-04-17 21:31:301965 /// Consumes the list into a front-to-back iterator yielding elements by
1966 /// value.
Jorge Aparicioe7273782015-02-13 22:55:101967 fn into_iter(self) -> IntoIter<T> {
Alex Crichton8f5b5f92015-04-17 21:31:301968 IntoIter {
1969 inner: self,
1970 }
Jorge Aparicioe7273782015-02-13 22:55:101971 }
1972}
1973
Alex Crichtoncc687862015-02-17 18:06:241974#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551975impl<'a, T> IntoIterator for &'a VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101976 type Item = &'a T;
1977 type IntoIter = Iter<'a, T>;
1978
1979 fn into_iter(self) -> Iter<'a, T> {
1980 self.iter()
1981 }
1982}
1983
Alex Crichtoncc687862015-02-17 18:06:241984#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551985impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101986 type Item = &'a mut T;
1987 type IntoIter = IterMut<'a, T>;
1988
1989 fn into_iter(mut self) -> IterMut<'a, T> {
1990 self.iter_mut()
1991 }
1992}
1993
Brian Andersonb44ee372015-01-24 05:48:201994#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551995impl<A> Extend<A> for VecDeque<A> {
Alexis4a9d1902015-02-18 15:04:301996 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
1997 for elt in iter {
Alexis Beingessnercf3b2e42014-11-06 17:24:471998 self.push_back(elt);
blake2-ppcf8ae5262013-07-30 00:06:491999 }
2000 }
2001}
2002
Johannes Oertelb36ed7d2015-06-03 10:38:422003#[stable(feature = "extend_ref", since = "1.2.0")]
2004impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2005 fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
2006 self.extend(iter.into_iter().cloned());
2007 }
2008}
2009
Brian Andersonb44ee372015-01-24 05:48:202010#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:552011impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:042012 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Andrew Paseltinerdb187182015-09-25 16:03:032013 f.debug_list().entries(self).finish()
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:042014 }
2015}
Jorge Apariciocb5e4292015-03-12 00:44:022016
2017#[cfg(test)]
Johannes Oertel07cc7d92015-04-24 15:30:412018mod tests {
Wesley Wiser99df3832015-05-30 23:49:562019 use core::iter::Iterator;
Jorge Apariciocb5e4292015-03-12 00:44:022020 use core::option::Option::Some;
2021
2022 use test;
2023
2024 use super::VecDeque;
2025
2026 #[bench]
2027 fn bench_push_back_100(b: &mut test::Bencher) {
2028 let mut deq = VecDeque::with_capacity(101);
2029 b.iter(|| {
2030 for i in 0..100 {
2031 deq.push_back(i);
2032 }
2033 deq.head = 0;
2034 deq.tail = 0;
2035 })
2036 }
2037
2038 #[bench]
2039 fn bench_push_front_100(b: &mut test::Bencher) {
2040 let mut deq = VecDeque::with_capacity(101);
2041 b.iter(|| {
2042 for i in 0..100 {
2043 deq.push_front(i);
2044 }
2045 deq.head = 0;
2046 deq.tail = 0;
2047 })
2048 }
2049
2050 #[bench]
2051 fn bench_pop_back_100(b: &mut test::Bencher) {
2052 let mut deq= VecDeque::<i32>::with_capacity(101);
2053
2054 b.iter(|| {
2055 deq.head = 100;
2056 deq.tail = 0;
2057 while !deq.is_empty() {
2058 test::black_box(deq.pop_back());
2059 }
2060 })
2061 }
2062
2063 #[bench]
2064 fn bench_pop_front_100(b: &mut test::Bencher) {
2065 let mut deq = VecDeque::<i32>::with_capacity(101);
2066
2067 b.iter(|| {
2068 deq.head = 100;
2069 deq.tail = 0;
2070 while !deq.is_empty() {
2071 test::black_box(deq.pop_front());
2072 }
2073 })
2074 }
2075
2076 #[test]
2077 fn test_swap_front_back_remove() {
2078 fn test(back: bool) {
2079 // This test checks that every single combination of tail position and length is tested.
2080 // Capacity 15 should be large enough to cover every case.
2081 let mut tester = VecDeque::with_capacity(15);
2082 let usable_cap = tester.capacity();
2083 let final_len = usable_cap / 2;
2084
2085 for len in 0..final_len {
2086 let expected = if back {
2087 (0..len).collect()
2088 } else {
2089 (0..len).rev().collect()
2090 };
2091 for tail_pos in 0..usable_cap {
2092 tester.tail = tail_pos;
2093 tester.head = tail_pos;
2094 if back {
2095 for i in 0..len * 2 {
2096 tester.push_front(i);
2097 }
2098 for i in 0..len {
2099 assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
2100 }
2101 } else {
2102 for i in 0..len * 2 {
2103 tester.push_back(i);
2104 }
2105 for i in 0..len {
2106 let idx = tester.len() - 1 - i;
2107 assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
2108 }
2109 }
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212110 assert!(tester.tail < tester.cap());
2111 assert!(tester.head < tester.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022112 assert_eq!(tester, expected);
2113 }
2114 }
2115 }
2116 test(true);
2117 test(false);
2118 }
2119
2120 #[test]
2121 fn test_insert() {
2122 // This test checks that every single combination of tail position, length, and
2123 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2124
2125 let mut tester = VecDeque::with_capacity(15);
2126 // can't guarantee we got 15, so have to get what we got.
2127 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2128 // this test isn't covering what it wants to
2129 let cap = tester.capacity();
2130
2131
2132 // len is the length *after* insertion
2133 for len in 1..cap {
2134 // 0, 1, 2, .., len - 1
Alex Crichtond4a2c942015-03-30 18:00:052135 let expected = (0..).take(len).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022136 for tail_pos in 0..cap {
2137 for to_insert in 0..len {
2138 tester.tail = tail_pos;
2139 tester.head = tail_pos;
2140 for i in 0..len {
2141 if i != to_insert {
2142 tester.push_back(i);
2143 }
2144 }
2145 tester.insert(to_insert, to_insert);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212146 assert!(tester.tail < tester.cap());
2147 assert!(tester.head < tester.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022148 assert_eq!(tester, expected);
2149 }
2150 }
2151 }
2152 }
2153
2154 #[test]
2155 fn test_remove() {
2156 // This test checks that every single combination of tail position, length, and
2157 // removal position is tested. Capacity 15 should be large enough to cover every case.
2158
2159 let mut tester = VecDeque::with_capacity(15);
2160 // can't guarantee we got 15, so have to get what we got.
2161 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2162 // this test isn't covering what it wants to
2163 let cap = tester.capacity();
2164
2165 // len is the length *after* removal
2166 for len in 0..cap - 1 {
2167 // 0, 1, 2, .., len - 1
Alex Crichtond4a2c942015-03-30 18:00:052168 let expected = (0..).take(len).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022169 for tail_pos in 0..cap {
2170 for to_remove in 0..len + 1 {
2171 tester.tail = tail_pos;
2172 tester.head = tail_pos;
2173 for i in 0..len {
2174 if i == to_remove {
2175 tester.push_back(1234);
2176 }
2177 tester.push_back(i);
2178 }
2179 if to_remove == len {
2180 tester.push_back(1234);
2181 }
2182 tester.remove(to_remove);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212183 assert!(tester.tail < tester.cap());
2184 assert!(tester.head < tester.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022185 assert_eq!(tester, expected);
2186 }
2187 }
2188 }
2189 }
2190
2191 #[test]
Michael Layzell45be6fc2015-08-07 02:03:142192 fn test_drain() {
2193 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2194
2195 let cap = tester.capacity();
2196 for len in 0..cap + 1 {
2197 for tail in 0..cap + 1 {
2198 for drain_start in 0..len + 1 {
2199 for drain_end in drain_start..len + 1 {
2200 tester.tail = tail;
2201 tester.head = tail;
2202 for i in 0..len {
2203 tester.push_back(i);
2204 }
2205
2206 // Check that we drain the correct values
2207 let drained: VecDeque<_> =
2208 tester.drain(drain_start..drain_end).collect();
2209 let drained_expected: VecDeque<_> =
2210 (drain_start..drain_end).collect();
2211 assert_eq!(drained, drained_expected);
2212
2213 // We shouldn't have changed the capacity or made the
2214 // head or tail out of bounds
2215 assert_eq!(tester.capacity(), cap);
2216 assert!(tester.tail < tester.cap());
2217 assert!(tester.head < tester.cap());
2218
2219 // We should see the correct values in the VecDeque
2220 let expected: VecDeque<_> =
2221 (0..drain_start).chain(drain_end..len).collect();
2222 assert_eq!(expected, tester);
2223 }
2224 }
2225 }
2226 }
2227 }
2228
2229 #[test]
Jorge Apariciocb5e4292015-03-12 00:44:022230 fn test_shrink_to_fit() {
2231 // This test checks that every single combination of head and tail position,
2232 // is tested. Capacity 15 should be large enough to cover every case.
2233
2234 let mut tester = VecDeque::with_capacity(15);
2235 // can't guarantee we got 15, so have to get what we got.
2236 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2237 // this test isn't covering what it wants to
2238 let cap = tester.capacity();
2239 tester.reserve(63);
2240 let max_cap = tester.capacity();
2241
2242 for len in 0..cap + 1 {
2243 // 0, 1, 2, .., len - 1
Alex Crichtond4a2c942015-03-30 18:00:052244 let expected = (0..).take(len).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022245 for tail_pos in 0..max_cap + 1 {
2246 tester.tail = tail_pos;
2247 tester.head = tail_pos;
2248 tester.reserve(63);
2249 for i in 0..len {
2250 tester.push_back(i);
2251 }
2252 tester.shrink_to_fit();
2253 assert!(tester.capacity() <= cap);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212254 assert!(tester.tail < tester.cap());
2255 assert!(tester.head < tester.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022256 assert_eq!(tester, expected);
2257 }
2258 }
2259 }
2260
2261 #[test]
2262 fn test_split_off() {
2263 // This test checks that every single combination of tail position, length, and
2264 // split position is tested. Capacity 15 should be large enough to cover every case.
2265
2266 let mut tester = VecDeque::with_capacity(15);
2267 // can't guarantee we got 15, so have to get what we got.
2268 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2269 // this test isn't covering what it wants to
2270 let cap = tester.capacity();
2271
2272 // len is the length *before* splitting
2273 for len in 0..cap {
2274 // index to split at
2275 for at in 0..len + 1 {
2276 // 0, 1, 2, .., at - 1 (may be empty)
Alex Crichtond4a2c942015-03-30 18:00:052277 let expected_self = (0..).take(at).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022278 // at, at + 1, .., len - 1 (may be empty)
Alex Crichtond4a2c942015-03-30 18:00:052279 let expected_other = (at..).take(len - at).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022280
2281 for tail_pos in 0..cap {
2282 tester.tail = tail_pos;
2283 tester.head = tail_pos;
2284 for i in 0..len {
2285 tester.push_back(i);
2286 }
2287 let result = tester.split_off(at);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212288 assert!(tester.tail < tester.cap());
2289 assert!(tester.head < tester.cap());
2290 assert!(result.tail < result.cap());
2291 assert!(result.head < result.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022292 assert_eq!(tester, expected_self);
2293 assert_eq!(result, expected_other);
2294 }
2295 }
2296 }
2297 }
Ulrik Sverdrup66f5dc12015-09-18 14:32:522298
2299 #[test]
2300 fn test_zst_push() {
2301 const N: usize = 8;
2302
2303 // Zero sized type
2304 struct Zst;
2305
2306 // Test that for all possible sequences of push_front / push_back,
2307 // we end up with a deque of the correct size
2308
2309 for len in 0..N {
2310 let mut tester = VecDeque::with_capacity(len);
2311 assert_eq!(tester.len(), 0);
2312 assert!(tester.capacity() >= len);
2313 for case in 0..(1 << len) {
2314 assert_eq!(tester.len(), 0);
2315 for bit in 0..len {
2316 if case & (1 << bit) != 0 {
2317 tester.push_front(Zst);
2318 } else {
2319 tester.push_back(Zst);
2320 }
2321 }
2322 assert_eq!(tester.len(), len);
2323 assert_eq!(tester.iter().count(), len);
2324 tester.clear();
2325 }
2326 }
2327 }
Jorge Apariciocb5e4292015-03-12 00:44:022328}