blob: 937ace00fdcca819f11147a24f74803c65723009 [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) {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21151 debug_assert!(dst + len <= self.cap(), "dst={} src={} len={} cap={}", dst, src, len,
152 self.cap());
153 debug_assert!(src + len <= self.cap(), "dst={} src={} len={} cap={}", dst, src, len,
154 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) {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21164 debug_assert!(dst + len <= self.cap(), "dst={} src={} len={} cap={}", dst, src, len,
165 self.cap());
166 debug_assert!(src + len <= self.cap(), "dst={} src={} len={} cap={}", dst, src, len,
167 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) {
178 debug_assert!(
179 (if src <= dst { dst - src } else { src - dst }) + len <= self.cap(),
180 "dst={} src={} len={} cap={}", dst, src, len, self.cap());
181
182 if src == dst || len == 0 { return }
183
184 let dst_after_src = self.wrap_sub(dst, src) < len;
185
186 let src_pre_wrap_len = self.cap() - src;
187 let dst_pre_wrap_len = self.cap() - dst;
188 let src_wraps = src_pre_wrap_len < len;
189 let dst_wraps = dst_pre_wrap_len < len;
190
191 match (dst_after_src, src_wraps, dst_wraps) {
192 (_, false, false) => {
193 // src doesn't wrap, dst doesn't wrap
194 //
195 // S . . .
196 // 1 [_ _ A A B B C C _]
197 // 2 [_ _ A A A A B B _]
198 // D . . .
199 //
200 self.copy(dst, src, len);
201 }
202 (false, false, true) => {
203 // dst before src, src doesn't wrap, dst wraps
204 //
205 // S . . .
206 // 1 [A A B B _ _ _ C C]
207 // 2 [A A B B _ _ _ A A]
208 // 3 [B B B B _ _ _ A A]
209 // . . D .
210 //
211 self.copy(dst, src, dst_pre_wrap_len);
212 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
213 }
214 (true, false, true) => {
215 // src before dst, src doesn't wrap, dst wraps
216 //
217 // S . . .
218 // 1 [C C _ _ _ A A B B]
219 // 2 [B B _ _ _ A A B B]
220 // 3 [B B _ _ _ A A A A]
221 // . . D .
222 //
223 self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
224 self.copy(dst, src, dst_pre_wrap_len);
225 }
226 (false, true, false) => {
227 // dst before src, src wraps, dst doesn't wrap
228 //
229 // . . S .
230 // 1 [C C _ _ _ A A B B]
231 // 2 [C C _ _ _ B B B B]
232 // 3 [C C _ _ _ B B C C]
233 // D . . .
234 //
235 self.copy(dst, src, src_pre_wrap_len);
236 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
237 }
238 (true, true, false) => {
239 // src before dst, src wraps, dst doesn't wrap
240 //
241 // . . S .
242 // 1 [A A B B _ _ _ C C]
243 // 2 [A A A A _ _ _ C C]
244 // 3 [C C A A _ _ _ C C]
245 // D . . .
246 //
247 self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
248 self.copy(dst, src, src_pre_wrap_len);
249 }
250 (false, true, true) => {
251 // dst before src, src wraps, dst wraps
252 //
253 // . . . S .
254 // 1 [A B C D _ E F G H]
255 // 2 [A B C D _ E G H H]
256 // 3 [A B C D _ E G H A]
257 // 4 [B C C D _ E G H A]
258 // . . D . .
259 //
260 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
261 let delta = dst_pre_wrap_len - src_pre_wrap_len;
262 self.copy(dst, src, src_pre_wrap_len);
263 self.copy(dst + src_pre_wrap_len, 0, delta);
264 self.copy(0, delta, len - dst_pre_wrap_len);
265 }
266 (true, true, true) => {
267 // src before dst, src wraps, dst wraps
268 //
269 // . . S . .
270 // 1 [A B C D _ E F G H]
271 // 2 [A A B D _ E F G H]
272 // 3 [H A B D _ E F G H]
273 // 4 [H A B D _ E F F G]
274 // . . . D .
275 //
276 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
277 let delta = src_pre_wrap_len - dst_pre_wrap_len;
278 self.copy(delta, 0, len - src_pre_wrap_len);
279 self.copy(0, self.cap() - delta, delta);
280 self.copy(dst, src, dst_pre_wrap_len);
281 }
282 }
283 }
284
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21285 /// Frobs the head and tail sections around to handle the fact that we
286 /// just reallocated. Unsafe because it trusts old_cap.
287 #[inline]
288 unsafe fn handle_cap_increase(&mut self, old_cap: usize) {
289 let new_cap = self.cap();
290
291 // Move the shortest contiguous section of the ring buffer
292 // T H
293 // [o o o o o o o . ]
294 // T H
295 // A [o o o o o o o . . . . . . . . . ]
296 // H T
297 // [o o . o o o o o ]
298 // T H
299 // B [. . . o o o o o o o . . . . . . ]
300 // H T
301 // [o o o o o . o o ]
302 // H T
303 // C [o o o o o . . . . . . . . . o o ]
304
305 if self.tail <= self.head { // A
306 // Nop
307 } else if self.head < old_cap - self.tail { // B
308 self.copy_nonoverlapping(old_cap, 0, self.head);
309 self.head += old_cap;
310 debug_assert!(self.head > self.tail);
311 } else { // C
312 let new_tail = new_cap - (old_cap - self.tail);
313 self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail);
314 self.tail = new_tail;
315 debug_assert!(self.head < self.tail);
316 }
317 debug_assert!(self.head < self.cap());
318 debug_assert!(self.tail < self.cap());
319 debug_assert!(self.cap().count_ones() == 1);
320 }
Colin Sherratt7a666df2014-10-19 20:19:07321}
322
Aaron Turon5fa9de12015-02-18 07:44:55323impl<T> VecDeque<T> {
324 /// Creates an empty `VecDeque`.
Brian Andersonb44ee372015-01-24 05:48:20325 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55326 pub fn new() -> VecDeque<T> {
327 VecDeque::with_capacity(INITIAL_CAPACITY)
blake2-ppc70523712013-07-10 13:27:14328 }
329
Aaron Turon5fa9de12015-02-18 07:44:55330 /// Creates an empty `VecDeque` with space for at least `n` elements.
Brian Andersonb44ee372015-01-24 05:48:20331 #[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:55332 pub fn with_capacity(n: usize) -> VecDeque<T> {
Colin Sherratt7a666df2014-10-19 20:19:07333 // +1 since the ringbuffer always leaves one space empty
Piotr Czarnecki156a1c32015-01-05 14:48:58334 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
335 assert!(cap > n, "capacity overflow");
Colin Sherrattba24e332014-11-10 03:34:53336
Aaron Turon5fa9de12015-02-18 07:44:55337 VecDeque {
Colin Sherratt7a666df2014-10-19 20:19:07338 tail: 0,
339 head: 0,
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21340 buf: RawVec::with_capacity(cap),
Colin Sherratt7a666df2014-10-19 20:19:07341 }
blake2-ppc70523712013-07-10 13:27:14342 }
343
Aaron Turon5fa9de12015-02-18 07:44:55344 /// Retrieves an element in the `VecDeque` by index.
blake2-ppc70523712013-07-10 13:27:14345 ///
jbranchaudc09defa2014-12-09 05:28:07346 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47347 ///
Joseph Crailfcf3f322015-03-13 02:42:38348 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55349 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47350 ///
Aaron Turon5fa9de12015-02-18 07:44:55351 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03352 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47353 /// buf.push_back(4);
354 /// buf.push_back(5);
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:13355 /// assert_eq!(buf.get(1), Some(&4));
Alexis Beingessnercf3b2e42014-11-06 17:24:47356 /// ```
Brian Andersonb44ee372015-01-24 05:48:20357 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25358 pub fn get(&self, index: usize) -> Option<&T> {
359 if index < self.len() {
360 let idx = self.wrap_add(self.tail, index);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21361 unsafe { Some(&*self.ptr().offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07362 } else {
363 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47364 }
365 }
366
Aaron Turon5fa9de12015-02-18 07:44:55367 /// Retrieves an element in the `VecDeque` mutably by index.
nhamebe80972014-07-17 23:19:51368 ///
jbranchaudc09defa2014-12-09 05:28:07369 /// # Examples
nhamebe80972014-07-17 23:19:51370 ///
Joseph Crailfcf3f322015-03-13 02:42:38371 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55372 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51373 ///
Aaron Turon5fa9de12015-02-18 07:44:55374 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03375 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47376 /// buf.push_back(4);
377 /// buf.push_back(5);
Corey Farwell68d003c2015-04-18 16:45:05378 /// if let Some(elem) = buf.get_mut(1) {
379 /// *elem = 7;
Alexis Beingessnercf3b2e42014-11-06 17:24:47380 /// }
381 ///
P1startfd10d202014-08-02 06:39:39382 /// assert_eq!(buf[1], 7);
nhamebe80972014-07-17 23:19:51383 /// ```
Brian Andersonb44ee372015-01-24 05:48:20384 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25385 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
386 if index < self.len() {
387 let idx = self.wrap_add(self.tail, index);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21388 unsafe { Some(&mut *self.ptr().offset(idx as isize)) }
Colin Sherratt7a666df2014-10-19 20:19:07389 } else {
390 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47391 }
blake2-ppc70523712013-07-10 13:27:14392 }
393
P1startf2aa88c2014-08-04 10:48:39394 /// Swaps elements at indices `i` and `j`.
blake2-ppc57757a82013-09-26 07:19:26395 ///
396 /// `i` and `j` may be equal.
397 ///
P1startf2aa88c2014-08-04 10:48:39398 /// Fails if there is no element with either index.
nhamebe80972014-07-17 23:19:51399 ///
jbranchaudc09defa2014-12-09 05:28:07400 /// # Examples
nhamebe80972014-07-17 23:19:51401 ///
Joseph Crailfcf3f322015-03-13 02:42:38402 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55403 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51404 ///
Aaron Turon5fa9de12015-02-18 07:44:55405 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03406 /// buf.push_back(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47407 /// buf.push_back(4);
408 /// buf.push_back(5);
nhamebe80972014-07-17 23:19:51409 /// buf.swap(0, 2);
P1startfd10d202014-08-02 06:39:39410 /// assert_eq!(buf[0], 5);
411 /// assert_eq!(buf[2], 3);
nhamebe80972014-07-17 23:19:51412 /// ```
Brian Andersonb44ee372015-01-24 05:48:20413 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19414 pub fn swap(&mut self, i: usize, j: usize) {
blake2-ppc57757a82013-09-26 07:19:26415 assert!(i < self.len());
416 assert!(j < self.len());
Felix S. Klock IIe7c98612015-02-19 07:33:32417 let ri = self.wrap_add(self.tail, i);
418 let rj = self.wrap_add(self.tail, j);
Colin Sherratt7a666df2014-10-19 20:19:07419 unsafe {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21420 ptr::swap(self.ptr().offset(ri as isize), self.ptr().offset(rj as isize))
Colin Sherratt7a666df2014-10-19 20:19:07421 }
blake2-ppc70523712013-07-10 13:27:14422 }
423
Aaron Turon5fa9de12015-02-18 07:44:55424 /// Returns the number of elements the `VecDeque` can hold without
Alexis Beingessnercf3b2e42014-11-06 17:24:47425 /// reallocating.
426 ///
jbranchaudc09defa2014-12-09 05:28:07427 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47428 ///
429 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55430 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47431 ///
Aaron Turon5fa9de12015-02-18 07:44:55432 /// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
Colin Sherratt7a666df2014-10-19 20:19:07433 /// assert!(buf.capacity() >= 10);
Alexis Beingessnercf3b2e42014-11-06 17:24:47434 /// ```
435 #[inline]
Brian Andersonb44ee372015-01-24 05:48:20436 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21437 pub fn capacity(&self) -> usize { self.cap() - 1 }
Tim Chevalier77de84b2013-05-27 18:47:38438
Alexis Beingessnercf3b2e42014-11-06 17:24:47439 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
Aaron Turon5fa9de12015-02-18 07:44:55440 /// given `VecDeque`. Does nothing if the capacity is already sufficient.
Tim Chevalier77de84b2013-05-27 18:47:38441 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47442 /// Note that the allocator may give the collection more space than it requests. Therefore
443 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
444 /// insertions are expected.
445 ///
446 /// # Panics
447 ///
Alexise250fe32015-02-05 02:17:19448 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47449 ///
jbranchaudc09defa2014-12-09 05:28:07450 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47451 ///
452 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55453 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47454 ///
Aaron Turon5fa9de12015-02-18 07:44:55455 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47456 /// buf.reserve_exact(10);
457 /// assert!(buf.capacity() >= 11);
458 /// ```
Brian Andersonb44ee372015-01-24 05:48:20459 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19460 pub fn reserve_exact(&mut self, additional: usize) {
Colin Sherratt7a666df2014-10-19 20:19:07461 self.reserve(additional);
Alexis Beingessnercf3b2e42014-11-06 17:24:47462 }
463
464 /// Reserves capacity for at least `additional` more elements to be inserted in the given
Corey Richardson8e2ce462015-07-05 07:49:36465 /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations.
Alexis Beingessnercf3b2e42014-11-06 17:24:47466 ///
467 /// # Panics
468 ///
Alexise250fe32015-02-05 02:17:19469 /// Panics if the new capacity overflows `usize`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47470 ///
jbranchaudc09defa2014-12-09 05:28:07471 /// # Examples
Alexis Beingessnercf3b2e42014-11-06 17:24:47472 ///
473 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55474 /// use std::collections::VecDeque;
Alexis Beingessnercf3b2e42014-11-06 17:24:47475 ///
Aaron Turon5fa9de12015-02-18 07:44:55476 /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
Alexis Beingessnercf3b2e42014-11-06 17:24:47477 /// buf.reserve(10);
478 /// assert!(buf.capacity() >= 11);
479 /// ```
Brian Andersonb44ee372015-01-24 05:48:20480 #[stable(feature = "rust1", since = "1.0.0")]
Alexise250fe32015-02-05 02:17:19481 pub fn reserve(&mut self, additional: usize) {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21482 let old_cap = self.cap();
483 let used_cap = self.len() + 1;
484 let new_cap = used_cap
485 .checked_add(additional)
486 .and_then(|needed_cap| needed_cap.checked_next_power_of_two())
487 .expect("capacity overflow");
Colin Sherratt7a666df2014-10-19 20:19:07488
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21489 if new_cap > self.capacity() {
490 self.buf.reserve_exact(used_cap, new_cap - used_cap);
491 unsafe { self.handle_cap_increase(old_cap); }
Colin Sherratt7a666df2014-10-19 20:19:07492 }
Tim Chevalier77de84b2013-05-27 18:47:38493 }
Jed Estep4f7a7422013-06-25 19:08:47494
Corey Richardson8e2ce462015-07-05 07:49:36495 /// Shrinks the capacity of the `VecDeque` as much as possible.
Piotr Czarnecki156a1c32015-01-05 14:48:58496 ///
497 /// It will drop down as close as possible to the length but the allocator may still inform the
Corey Richardson8e2ce462015-07-05 07:49:36498 /// `VecDeque` that there is space for a few more elements.
Piotr Czarnecki156a1c32015-01-05 14:48:58499 ///
500 /// # Examples
501 ///
502 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55503 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58504 ///
Aaron Turon5fa9de12015-02-18 07:44:55505 /// let mut buf = VecDeque::with_capacity(15);
Alexise15538d2015-02-06 18:57:13506 /// buf.extend(0..4);
Piotr Czarnecki156a1c32015-01-05 14:48:58507 /// assert_eq!(buf.capacity(), 15);
508 /// buf.shrink_to_fit();
509 /// assert!(buf.capacity() >= 4);
510 /// ```
Alex Crichtonff497332015-10-22 23:28:45511 #[stable(feature = "deque_extras_15", since = "1.5.0")]
Piotr Czarnecki156a1c32015-01-05 14:48:58512 pub fn shrink_to_fit(&mut self) {
513 // +1 since the ringbuffer always leaves one space empty
Corey Richardson8e2ce462015-07-05 07:49:36514 // len + 1 can't overflow for an existing, well-formed ringbuffer.
Piotr Czarnecki156a1c32015-01-05 14:48:58515 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21516 if target_cap < self.cap() {
Piotr Czarnecki156a1c32015-01-05 14:48:58517 // There are three cases of interest:
518 // All elements are out of desired bounds
519 // Elements are contiguous, and head is out of desired bounds
520 // Elements are discontiguous, and tail is out of desired bounds
521 //
522 // At all other times, element positions are unaffected.
523 //
524 // Indicates that elements at the head should be moved.
525 let head_outside = self.head == 0 || self.head >= target_cap;
526 // Move elements from out of desired bounds (positions after target_cap)
527 if self.tail >= target_cap && head_outside {
528 // T H
529 // [. . . . . . . . o o o o o o o . ]
530 // T H
531 // [o o o o o o o . ]
532 unsafe {
533 self.copy_nonoverlapping(0, self.tail, self.len());
534 }
535 self.head = self.len();
536 self.tail = 0;
537 } else if self.tail != 0 && self.tail < target_cap && head_outside {
538 // T H
539 // [. . . o o o o o o o . . . . . . ]
540 // H T
541 // [o o . o o o o o ]
Felix S. Klock IIe7c98612015-02-19 07:33:32542 let len = self.wrap_sub(self.head, target_cap);
Piotr Czarnecki156a1c32015-01-05 14:48:58543 unsafe {
544 self.copy_nonoverlapping(0, target_cap, len);
545 }
546 self.head = len;
547 debug_assert!(self.head < self.tail);
548 } else if self.tail >= target_cap {
549 // H T
550 // [o o o o o . . . . . . . . . o o ]
551 // H T
552 // [o o o o o . o o ]
Felix S. Klock IIe7c98612015-02-19 07:33:32553 debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21554 let len = self.cap() - self.tail;
Piotr Czarnecki156a1c32015-01-05 14:48:58555 let new_tail = target_cap - len;
556 unsafe {
557 self.copy_nonoverlapping(new_tail, self.tail, len);
558 }
559 self.tail = new_tail;
560 debug_assert!(self.head < self.tail);
561 }
562
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21563 self.buf.shrink_to_fit(target_cap);
564
565 debug_assert!(self.head < self.cap());
566 debug_assert!(self.tail < self.cap());
567 debug_assert!(self.cap().count_ones() == 1);
Piotr Czarnecki156a1c32015-01-05 14:48:58568 }
569 }
570
Corey Richardson8e2ce462015-07-05 07:49:36571 /// Shortens a `VecDeque`, dropping excess elements from the back.
Piotr Czarnecki156a1c32015-01-05 14:48:58572 ///
Corey Richardson8e2ce462015-07-05 07:49:36573 /// If `len` is greater than the `VecDeque`'s current length, this has no
Piotr Czarnecki156a1c32015-01-05 14:48:58574 /// effect.
575 ///
576 /// # Examples
577 ///
578 /// ```
Steve Klabnikba5fcb72015-07-27 14:50:19579 /// #![feature(deque_extras)]
580 ///
Aaron Turon5fa9de12015-02-18 07:44:55581 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:58582 ///
Aaron Turon5fa9de12015-02-18 07:44:55583 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03584 /// buf.push_back(5);
585 /// buf.push_back(10);
Piotr Czarnecki156a1c32015-01-05 14:48:58586 /// buf.push_back(15);
587 /// buf.truncate(1);
588 /// assert_eq!(buf.len(), 1);
589 /// assert_eq!(Some(&5), buf.get(0));
590 /// ```
Alex Crichtond444d0c2015-06-09 21:39:23591 #[unstable(feature = "deque_extras",
Alex Crichton377c11a2015-08-13 05:19:51592 reason = "matches collection reform specification; waiting on panic semantics",
593 issue = "27788")]
Alexise250fe32015-02-05 02:17:19594 pub fn truncate(&mut self, len: usize) {
Jorge Aparicioefc97a52015-01-26 21:05:07595 for _ in len..self.len() {
Piotr Czarnecki156a1c32015-01-05 14:48:58596 self.pop_back();
597 }
598 }
599
P1startf2aa88c2014-08-04 10:48:39600 /// Returns a front-to-back iterator.
nhamebe80972014-07-17 23:19:51601 ///
jbranchaudc09defa2014-12-09 05:28:07602 /// # Examples
nhamebe80972014-07-17 23:19:51603 ///
Joseph Crailfcf3f322015-03-13 02:42:38604 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55605 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51606 ///
Aaron Turon5fa9de12015-02-18 07:44:55607 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03608 /// buf.push_back(5);
Alexis Beingessnercf3b2e42014-11-06 17:24:47609 /// buf.push_back(3);
610 /// buf.push_back(4);
Nick Cameron52ef4622014-08-06 09:59:40611 /// let b: &[_] = &[&5, &3, &4];
Emeliov Dmitriidf65f592015-03-30 16:22:46612 /// let c: Vec<&i32> = buf.iter().collect();
613 /// assert_eq!(&c[..], b);
nhamebe80972014-07-17 23:19:51614 /// ```
Brian Andersonb44ee372015-01-24 05:48:20615 #[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:10616 pub fn iter(&self) -> Iter<T> {
617 Iter {
Colin Sherratt7a666df2014-10-19 20:19:07618 tail: self.tail,
619 head: self.head,
620 ring: unsafe { self.buffer_as_slice() }
621 }
blake2-ppc3385e792013-07-15 23:13:26622 }
623
Andrew Wagner8fcc8322014-12-15 09:22:49624 /// Returns a front-to-back iterator that returns mutable references.
nhamebe80972014-07-17 23:19:51625 ///
jbranchaudc09defa2014-12-09 05:28:07626 /// # Examples
nhamebe80972014-07-17 23:19:51627 ///
Joseph Crailfcf3f322015-03-13 02:42:38628 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55629 /// use std::collections::VecDeque;
nhamebe80972014-07-17 23:19:51630 ///
Aaron Turon5fa9de12015-02-18 07:44:55631 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03632 /// buf.push_back(5);
Alexis Beingessnercf3b2e42014-11-06 17:24:47633 /// buf.push_back(3);
634 /// buf.push_back(4);
Aaron Turonfc525ee2014-09-15 03:27:36635 /// for num in buf.iter_mut() {
nhamebe80972014-07-17 23:19:51636 /// *num = *num - 2;
637 /// }
Nick Cameron52ef4622014-08-06 09:59:40638 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
Alex Crichton77de3ee2015-03-26 16:57:58639 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
nhamebe80972014-07-17 23:19:51640 /// ```
Brian Andersonb44ee372015-01-24 05:48:20641 #[stable(feature = "rust1", since = "1.0.0")]
Alexis1420ceb2015-02-05 18:48:20642 pub fn iter_mut(&mut self) -> IterMut<T> {
Florian Wilkensf8cfd242014-12-19 20:52:10643 IterMut {
Colin Sherratt7a666df2014-10-19 20:19:07644 tail: self.tail,
645 head: self.head,
Edward Wang101498c2015-02-25 10:11:23646 ring: unsafe { self.buffer_as_mut_slice() },
Niko Matsakisbc4164d2013-11-16 22:29:39647 }
Jed Estep4f7a7422013-06-25 19:08:47648 }
Alex Crichton21ac9852014-10-30 20:43:24649
Clark Gaebel525f65e2014-12-16 04:01:58650 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55651 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58652 #[inline]
Alex Crichtonff497332015-10-22 23:28:45653 #[stable(feature = "deque_extras_15", since = "1.5.0")]
Alexis1420ceb2015-02-05 18:48:20654 pub fn as_slices(&self) -> (&[T], &[T]) {
Clark Gaebel525f65e2014-12-16 04:01:58655 unsafe {
656 let contiguous = self.is_contiguous();
657 let buf = self.buffer_as_slice();
658 if contiguous {
659 let (empty, buf) = buf.split_at(0);
Jorge Aparicio517f1cc2015-01-07 16:58:31660 (&buf[self.tail..self.head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58661 } else {
662 let (mid, right) = buf.split_at(self.tail);
663 let (left, _) = mid.split_at(self.head);
664 (right, left)
665 }
666 }
667 }
668
669 /// Returns a pair of slices which contain, in order, the contents of the
Aaron Turon5fa9de12015-02-18 07:44:55670 /// `VecDeque`.
Clark Gaebel525f65e2014-12-16 04:01:58671 #[inline]
Alex Crichtonff497332015-10-22 23:28:45672 #[stable(feature = "deque_extras_15", since = "1.5.0")]
Alexis1420ceb2015-02-05 18:48:20673 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
Clark Gaebel525f65e2014-12-16 04:01:58674 unsafe {
675 let contiguous = self.is_contiguous();
676 let head = self.head;
677 let tail = self.tail;
678 let buf = self.buffer_as_mut_slice();
679
680 if contiguous {
681 let (empty, buf) = buf.split_at_mut(0);
Aaron Turona506d4c2015-01-18 00:15:52682 (&mut buf[tail .. head], empty)
Clark Gaebel525f65e2014-12-16 04:01:58683 } else {
684 let (mid, right) = buf.split_at_mut(tail);
685 let (left, _) = mid.split_at_mut(head);
686
687 (right, left)
688 }
689 }
690 }
691
Aaron Turon5fa9de12015-02-18 07:44:55692 /// Returns the number of elements in the `VecDeque`.
Alex Crichton21ac9852014-10-30 20:43:24693 ///
jbranchaudc09defa2014-12-09 05:28:07694 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24695 ///
696 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55697 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24698 ///
Aaron Turon5fa9de12015-02-18 07:44:55699 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24700 /// assert_eq!(v.len(), 0);
Tobias Bucher7f64fe42015-01-25 21:05:03701 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24702 /// assert_eq!(v.len(), 1);
703 /// ```
Brian Andersonb44ee372015-01-24 05:48:20704 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21705 pub fn len(&self) -> usize { count(self.tail, self.head, self.cap()) }
Alex Crichton21ac9852014-10-30 20:43:24706
707 /// Returns true if the buffer contains no elements
708 ///
jbranchaudc09defa2014-12-09 05:28:07709 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24710 ///
711 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55712 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24713 ///
Aaron Turon5fa9de12015-02-18 07:44:55714 /// let mut v = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24715 /// assert!(v.is_empty());
Tobias Bucher7f64fe42015-01-25 21:05:03716 /// v.push_front(1);
Alex Crichton21ac9852014-10-30 20:43:24717 /// assert!(!v.is_empty());
718 /// ```
Brian Andersonb44ee372015-01-24 05:48:20719 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24720 pub fn is_empty(&self) -> bool { self.len() == 0 }
721
Michael Layzell45be6fc2015-08-07 02:03:14722 /// Create a draining iterator that removes the specified range in the
723 /// `VecDeque` and yields the removed items from start to end. The element
724 /// range is removed even if the iterator is not consumed until the end.
725 ///
726 /// Note: It is unspecified how many elements are removed from the deque,
727 /// if the `Drain` value is not dropped, but the borrow it holds expires
728 /// (eg. due to mem::forget).
729 ///
730 /// # Panics
731 ///
732 /// Panics if the starting point is greater than the end point or if
733 /// the end point is greater than the length of the vector.
Clark Gaebeld57f2592014-12-16 22:45:03734 ///
735 /// # Examples
736 ///
737 /// ```
Steve Klabnikba5fcb72015-07-27 14:50:19738 /// #![feature(drain)]
739 ///
Aaron Turon5fa9de12015-02-18 07:44:55740 /// use std::collections::VecDeque;
Clark Gaebeld57f2592014-12-16 22:45:03741 ///
Michael Layzell45be6fc2015-08-07 02:03:14742 /// // draining using `..` clears the whole deque.
Aaron Turon5fa9de12015-02-18 07:44:55743 /// let mut v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03744 /// v.push_back(1);
Michael Layzell45be6fc2015-08-07 02:03:14745 /// assert_eq!(v.drain(..).next(), Some(1));
Clark Gaebeld57f2592014-12-16 22:45:03746 /// assert!(v.is_empty());
747 /// ```
748 #[inline]
Alex Crichtond444d0c2015-06-09 21:39:23749 #[unstable(feature = "drain",
Alex Crichton377c11a2015-08-13 05:19:51750 reason = "matches collection reform specification, waiting for dust to settle",
751 issue = "27711")]
Michael Layzell45be6fc2015-08-07 02:03:14752 pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> {
753 // Memory safety
754 //
755 // When the Drain is first created, the source deque is shortened to
756 // make sure no uninitialized or moved-from elements are accessible at
757 // all if the Drain's destructor never gets to run.
758 //
759 // Drain will ptr::read out the values to remove.
760 // When finished, the remaining data will be copied back to cover the hole,
761 // and the head/tail values will be restored correctly.
762 //
763 let len = self.len();
764 let start = *range.start().unwrap_or(&0);
765 let end = *range.end().unwrap_or(&len);
766 assert!(start <= end, "drain lower bound was too large");
767 assert!(end <= len, "drain upper bound was too large");
768
769 // The deque's elements are parted into three segments:
770 // * self.tail -> drain_tail
771 // * drain_tail -> drain_head
772 // * drain_head -> self.head
773 //
774 // T = self.tail; H = self.head; t = drain_tail; h = drain_head
775 //
776 // We store drain_tail as self.head, and drain_head and self.head as
777 // after_tail and after_head respectively on the Drain. This also
778 // truncates the effective array such that if the Drain is leaked, we
779 // have forgotten about the potentially moved values after the start of
780 // the drain.
781 //
782 // T t h H
783 // [. . . o o x x o o . . .]
784 //
785 let drain_tail = self.wrap_add(self.tail, start);
786 let drain_head = self.wrap_add(self.tail, end);
787 let head = self.head;
788
789 // "forget" about the values after the start of the drain until after
790 // the drain is complete and the Drain destructor is run.
791 self.head = drain_tail;
792
Clark Gaebeld57f2592014-12-16 22:45:03793 Drain {
Michael Layzell45be6fc2015-08-07 02:03:14794 deque: self as *mut _,
795 after_tail: drain_head,
796 after_head: head,
797 iter: Iter {
798 tail: drain_tail,
799 head: drain_head,
800 ring: unsafe { self.buffer_as_mut_slice() },
801 },
Clark Gaebeld57f2592014-12-16 22:45:03802 }
803 }
804
Alex Crichton21ac9852014-10-30 20:43:24805 /// Clears the buffer, removing all values.
806 ///
jbranchaudc09defa2014-12-09 05:28:07807 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24808 ///
809 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55810 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24811 ///
Aaron Turon5fa9de12015-02-18 07:44:55812 /// let mut v = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03813 /// v.push_back(1);
Alex Crichton21ac9852014-10-30 20:43:24814 /// v.clear();
815 /// assert!(v.is_empty());
816 /// ```
Brian Andersonb44ee372015-01-24 05:48:20817 #[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:03818 #[inline]
Alex Crichton21ac9852014-10-30 20:43:24819 pub fn clear(&mut self) {
Michael Layzell45be6fc2015-08-07 02:03:14820 self.drain(..);
Alex Crichton21ac9852014-10-30 20:43:24821 }
822
823 /// Provides a reference to the front element, or `None` if the sequence is
824 /// empty.
825 ///
jbranchaudc09defa2014-12-09 05:28:07826 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24827 ///
828 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55829 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24830 ///
Aaron Turon5fa9de12015-02-18 07:44:55831 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24832 /// assert_eq!(d.front(), None);
833 ///
Tobias Bucher7f64fe42015-01-25 21:05:03834 /// d.push_back(1);
835 /// d.push_back(2);
836 /// assert_eq!(d.front(), Some(&1));
Alex Crichton21ac9852014-10-30 20:43:24837 /// ```
Brian Andersonb44ee372015-01-24 05:48:20838 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24839 pub fn front(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07840 if !self.is_empty() { Some(&self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24841 }
842
843 /// Provides a mutable reference to the front element, or `None` if the
844 /// sequence is empty.
845 ///
jbranchaudc09defa2014-12-09 05:28:07846 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24847 ///
848 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55849 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24850 ///
Aaron Turon5fa9de12015-02-18 07:44:55851 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24852 /// assert_eq!(d.front_mut(), None);
853 ///
Tobias Bucher7f64fe42015-01-25 21:05:03854 /// d.push_back(1);
855 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24856 /// match d.front_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03857 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24858 /// None => (),
859 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03860 /// assert_eq!(d.front(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24861 /// ```
Brian Andersonb44ee372015-01-24 05:48:20862 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24863 pub fn front_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07864 if !self.is_empty() { Some(&mut self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24865 }
866
867 /// Provides a reference to the back element, or `None` if the sequence is
868 /// empty.
869 ///
jbranchaudc09defa2014-12-09 05:28:07870 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24871 ///
872 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55873 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24874 ///
Aaron Turon5fa9de12015-02-18 07:44:55875 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24876 /// assert_eq!(d.back(), None);
877 ///
Tobias Bucher7f64fe42015-01-25 21:05:03878 /// d.push_back(1);
879 /// d.push_back(2);
880 /// assert_eq!(d.back(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24881 /// ```
Brian Andersonb44ee372015-01-24 05:48:20882 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24883 pub fn back(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07884 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24885 }
886
887 /// Provides a mutable reference to the back element, or `None` if the
888 /// sequence is empty.
889 ///
jbranchaudc09defa2014-12-09 05:28:07890 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24891 ///
892 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55893 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24894 ///
Aaron Turon5fa9de12015-02-18 07:44:55895 /// let mut d = VecDeque::new();
Alex Crichton21ac9852014-10-30 20:43:24896 /// assert_eq!(d.back(), None);
897 ///
Tobias Bucher7f64fe42015-01-25 21:05:03898 /// d.push_back(1);
899 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24900 /// match d.back_mut() {
Tobias Bucher7f64fe42015-01-25 21:05:03901 /// Some(x) => *x = 9,
Alex Crichton21ac9852014-10-30 20:43:24902 /// None => (),
903 /// }
Tobias Bucher7f64fe42015-01-25 21:05:03904 /// assert_eq!(d.back(), Some(&9));
Alex Crichton21ac9852014-10-30 20:43:24905 /// ```
Brian Andersonb44ee372015-01-24 05:48:20906 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24907 pub fn back_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07908 let len = self.len();
909 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24910 }
911
912 /// Removes the first element and returns it, or `None` if the sequence is
913 /// empty.
914 ///
jbranchaudc09defa2014-12-09 05:28:07915 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24916 ///
917 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55918 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24919 ///
Aaron Turon5fa9de12015-02-18 07:44:55920 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03921 /// d.push_back(1);
922 /// d.push_back(2);
Alex Crichton21ac9852014-10-30 20:43:24923 ///
Tobias Bucher7f64fe42015-01-25 21:05:03924 /// assert_eq!(d.pop_front(), Some(1));
925 /// assert_eq!(d.pop_front(), Some(2));
Alex Crichton21ac9852014-10-30 20:43:24926 /// assert_eq!(d.pop_front(), None);
927 /// ```
Brian Andersonb44ee372015-01-24 05:48:20928 #[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton21ac9852014-10-30 20:43:24929 pub fn pop_front(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07930 if self.is_empty() {
931 None
932 } else {
933 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:32934 self.tail = self.wrap_add(self.tail, 1);
Colin Sherratt7a666df2014-10-19 20:19:07935 unsafe { Some(self.buffer_read(tail)) }
Alex Crichton21ac9852014-10-30 20:43:24936 }
Alex Crichton21ac9852014-10-30 20:43:24937 }
938
939 /// Inserts an element first in the sequence.
940 ///
jbranchaudc09defa2014-12-09 05:28:07941 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24942 ///
943 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55944 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24945 ///
Aaron Turon5fa9de12015-02-18 07:44:55946 /// let mut d = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03947 /// d.push_front(1);
948 /// d.push_front(2);
949 /// assert_eq!(d.front(), Some(&2));
Alex Crichton21ac9852014-10-30 20:43:24950 /// ```
Brian Andersonb44ee372015-01-24 05:48:20951 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25952 pub fn push_front(&mut self, value: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29953 if self.is_full() {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21954 let old_cap = self.cap();
955 self.buf.double();
956 unsafe { self.handle_cap_increase(old_cap); }
Colin Sherratt4cae9ad2014-11-11 02:16:29957 debug_assert!(!self.is_full());
958 }
Colin Sherratt7a666df2014-10-19 20:19:07959
Felix S. Klock IIe7c98612015-02-19 07:33:32960 self.tail = self.wrap_sub(self.tail, 1);
Colin Sherratt7a666df2014-10-19 20:19:07961 let tail = self.tail;
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25962 unsafe { self.buffer_write(tail, value); }
Alex Crichton21ac9852014-10-30 20:43:24963 }
964
965 /// Appends an element to the back of a buffer
966 ///
jbranchaudc09defa2014-12-09 05:28:07967 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24968 ///
Joseph Crailfcf3f322015-03-13 02:42:38969 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55970 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24971 ///
Aaron Turon5fa9de12015-02-18 07:44:55972 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:03973 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:47974 /// buf.push_back(3);
Alex Crichton21ac9852014-10-30 20:43:24975 /// assert_eq!(3, *buf.back().unwrap());
976 /// ```
Brian Andersonb44ee372015-01-24 05:48:20977 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25978 pub fn push_back(&mut self, value: T) {
Colin Sherratt4cae9ad2014-11-11 02:16:29979 if self.is_full() {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:21980 let old_cap = self.cap();
981 self.buf.double();
982 unsafe { self.handle_cap_increase(old_cap); }
Colin Sherratt4cae9ad2014-11-11 02:16:29983 debug_assert!(!self.is_full());
984 }
Colin Sherratt7a666df2014-10-19 20:19:07985
986 let head = self.head;
Felix S. Klock IIe7c98612015-02-19 07:33:32987 self.head = self.wrap_add(self.head, 1);
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:25988 unsafe { self.buffer_write(head, value) }
Alex Crichton21ac9852014-10-30 20:43:24989 }
990
991 /// Removes the last element from a buffer and returns it, or `None` if
992 /// it is empty.
993 ///
jbranchaudc09defa2014-12-09 05:28:07994 /// # Examples
Alex Crichton21ac9852014-10-30 20:43:24995 ///
Joseph Crailfcf3f322015-03-13 02:42:38996 /// ```
Aaron Turon5fa9de12015-02-18 07:44:55997 /// use std::collections::VecDeque;
Alex Crichton21ac9852014-10-30 20:43:24998 ///
Aaron Turon5fa9de12015-02-18 07:44:55999 /// let mut buf = VecDeque::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:471000 /// assert_eq!(buf.pop_back(), None);
Tobias Bucher7f64fe42015-01-25 21:05:031001 /// buf.push_back(1);
Alexis Beingessnercf3b2e42014-11-06 17:24:471002 /// buf.push_back(3);
1003 /// assert_eq!(buf.pop_back(), Some(3));
Alex Crichton21ac9852014-10-30 20:43:241004 /// ```
Brian Andersonb44ee372015-01-24 05:48:201005 #[stable(feature = "rust1", since = "1.0.0")]
Alexis Beingessnercf3b2e42014-11-06 17:24:471006 pub fn pop_back(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:071007 if self.is_empty() {
Alex Crichton21ac9852014-10-30 20:43:241008 None
Colin Sherratt7a666df2014-10-19 20:19:071009 } else {
Felix S. Klock IIe7c98612015-02-19 07:33:321010 self.head = self.wrap_sub(self.head, 1);
Colin Sherratt7a666df2014-10-19 20:19:071011 let head = self.head;
1012 unsafe { Some(self.buffer_read(head)) }
Alex Crichton21ac9852014-10-30 20:43:241013 }
1014 }
Matt Murphy40f28c72014-12-03 17:12:301015
Clark Gaebel525f65e2014-12-16 04:01:581016 #[inline]
1017 fn is_contiguous(&self) -> bool {
1018 self.tail <= self.head
1019 }
1020
Corey Richardson8e2ce462015-07-05 07:49:361021 /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the
1022 /// last element.
Piotr Czarnecki156a1c32015-01-05 14:48:581023 ///
1024 /// This does not preserve ordering, but is O(1).
1025 ///
1026 /// Returns `None` if `index` is out of bounds.
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551031 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:581032 ///
Aaron Turon5fa9de12015-02-18 07:44:551033 /// let mut buf = VecDeque::new();
Alex Crichtonff497332015-10-22 23:28:451034 /// assert_eq!(buf.swap_remove_back(0), None);
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131035 /// buf.push_back(1);
1036 /// buf.push_back(2);
1037 /// buf.push_back(3);
1038 ///
Alex Crichtonff497332015-10-22 23:28:451039 /// assert_eq!(buf.swap_remove_back(0), Some(1));
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131040 /// assert_eq!(buf.len(), 2);
1041 /// assert_eq!(buf[0], 3);
1042 /// assert_eq!(buf[1], 2);
Piotr Czarnecki156a1c32015-01-05 14:48:581043 /// ```
Alex Crichtonff497332015-10-22 23:28:451044 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1045 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:581046 let length = self.len();
1047 if length > 0 && index < length - 1 {
1048 self.swap(index, length - 1);
1049 } else if index >= length {
1050 return None;
1051 }
1052 self.pop_back()
1053 }
1054
Alex Crichtonff497332015-10-22 23:28:451055 /// deprecated
1056 #[unstable(feature = "deque_extras",
1057 reason = "the naming of this function may be altered",
1058 issue = "27788")]
1059 #[deprecated(since = "1.5.0", reason = "renamed to swap_remove_back")]
1060 pub fn swap_back_remove(&mut self, index: usize) -> Option<T> {
1061 self.swap_remove_back(index)
1062 }
1063
Corey Richardson8e2ce462015-07-05 07:49:361064 /// Removes an element from anywhere in the `VecDeque` and returns it,
Alex Crichtonce1a9652015-06-10 20:33:521065 /// replacing it with the first element.
Piotr Czarnecki156a1c32015-01-05 14:48:581066 ///
1067 /// This does not preserve ordering, but is O(1).
1068 ///
1069 /// Returns `None` if `index` is out of bounds.
1070 ///
1071 /// # Examples
1072 ///
1073 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551074 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:581075 ///
Aaron Turon5fa9de12015-02-18 07:44:551076 /// let mut buf = VecDeque::new();
Alex Crichtonff497332015-10-22 23:28:451077 /// assert_eq!(buf.swap_remove_front(0), None);
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131078 /// buf.push_back(1);
1079 /// buf.push_back(2);
1080 /// buf.push_back(3);
1081 ///
Alex Crichtonff497332015-10-22 23:28:451082 /// assert_eq!(buf.swap_remove_front(2), Some(3));
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131083 /// assert_eq!(buf.len(), 2);
1084 /// assert_eq!(buf[0], 2);
1085 /// assert_eq!(buf[1], 1);
Piotr Czarnecki156a1c32015-01-05 14:48:581086 /// ```
Alex Crichtonff497332015-10-22 23:28:451087 #[stable(feature = "deque_extras_15", since = "1.5.0")]
1088 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
Piotr Czarnecki156a1c32015-01-05 14:48:581089 let length = self.len();
1090 if length > 0 && index < length && index != 0 {
1091 self.swap(index, 0);
1092 } else if index >= length {
1093 return None;
1094 }
1095 self.pop_front()
1096 }
1097
Alex Crichtonff497332015-10-22 23:28:451098 /// deprecated
1099 #[unstable(feature = "deque_extras",
1100 reason = "the naming of this function may be altered",
1101 issue = "27788")]
1102 #[deprecated(since = "1.5.0", reason = "renamed to swap_remove_front")]
1103 pub fn swap_front_remove(&mut self, index: usize) -> Option<T> {
1104 self.swap_remove_front(index)
1105 }
1106
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251107 /// Inserts an element at `index` within the `VecDeque`. Whichever
Matt Murphy40f28c72014-12-03 17:12:301108 /// end is closer to the insertion point will be moved to make room,
1109 /// and all the affected elements will be moved to new positions.
1110 ///
1111 /// # Panics
1112 ///
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251113 /// Panics if `index` is greater than `VecDeque`'s length
Matt Murphy40f28c72014-12-03 17:12:301114 ///
Piotr Czarnecki156a1c32015-01-05 14:48:581115 /// # Examples
Joseph Crailfcf3f322015-03-13 02:42:381116 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551117 /// use std::collections::VecDeque;
Matt Murphy40f28c72014-12-03 17:12:301118 ///
Aaron Turon5fa9de12015-02-18 07:44:551119 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031120 /// buf.push_back(10);
Matt Murphy40f28c72014-12-03 17:12:301121 /// buf.push_back(12);
Tshepang Lekhonkhobe02ae6612015-07-17 18:55:111122 /// buf.insert(1, 11);
Matt Murphy40f28c72014-12-03 17:12:301123 /// assert_eq!(Some(&11), buf.get(1));
1124 /// ```
Alex Crichtonff497332015-10-22 23:28:451125 #[stable(feature = "deque_extras_15", since = "1.5.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251126 pub fn insert(&mut self, index: usize, value: T) {
1127 assert!(index <= self.len(), "index out of bounds");
Matt Murphy40f28c72014-12-03 17:12:301128 if self.is_full() {
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211129 let old_cap = self.cap();
1130 self.buf.double();
1131 unsafe { self.handle_cap_increase(old_cap); }
Matt Murphy40f28c72014-12-03 17:12:301132 debug_assert!(!self.is_full());
1133 }
1134
1135 // Move the least number of elements in the ring buffer and insert
1136 // the given object
1137 //
1138 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
1139 //
1140 // There are three main cases:
1141 // Elements are contiguous
1142 // - special case when tail is 0
1143 // Elements are discontiguous and the insert is in the tail section
1144 // Elements are discontiguous and the insert is in the head section
1145 //
1146 // For each of those there are two more cases:
1147 // Insert is closer to tail
1148 // Insert is closer to head
1149 //
1150 // Key: H - self.head
1151 // T - self.tail
1152 // o - Valid element
1153 // I - Insertion element
1154 // A - The element that should be after the insertion point
1155 // M - Indicates element was moved
1156
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251157 let idx = self.wrap_add(self.tail, index);
Matt Murphy40f28c72014-12-03 17:12:301158
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251159 let distance_to_tail = index;
1160 let distance_to_head = self.len() - index;
Matt Murphy40f28c72014-12-03 17:12:301161
Clark Gaebel525f65e2014-12-16 04:01:581162 let contiguous = self.is_contiguous();
Matt Murphy40f28c72014-12-03 17:12:301163
1164 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251165 (true, true, _) if index == 0 => {
Matt Murphy40f28c72014-12-03 17:12:301166 // push_front
1167 //
1168 // T
1169 // I H
1170 // [A o o o o o o . . . . . . . . .]
1171 //
1172 // H T
1173 // [A o o o o o o o . . . . . I]
1174 //
1175
Felix S. Klock IIe7c98612015-02-19 07:33:321176 self.tail = self.wrap_sub(self.tail, 1);
Matt Murphy40f28c72014-12-03 17:12:301177 },
Piotr Czarnecki59d41532014-12-16 23:37:551178 (true, true, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:301179 // contiguous, insert closer to tail:
1180 //
1181 // T I H
1182 // [. . . o o A o o o o . . . . . .]
1183 //
1184 // T H
1185 // [. . o o I A o o o o . . . . . .]
1186 // M M
1187 //
1188 // contiguous, insert closer to tail and tail is 0:
1189 //
1190 //
1191 // T I H
1192 // [o o A o o o o . . . . . . . . .]
1193 //
1194 // H T
1195 // [o I A o o o o o . . . . . . . o]
1196 // M M
1197
Felix S. Klock IIe7c98612015-02-19 07:33:321198 let new_tail = self.wrap_sub(self.tail, 1);
Matt Murphy40f28c72014-12-03 17:12:301199
Piotr Czarnecki59d41532014-12-16 23:37:551200 self.copy(new_tail, self.tail, 1);
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251201 // Already moved the tail, so we only copy `index - 1` elements.
1202 self.copy(self.tail, self.tail + 1, index - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551203
1204 self.tail = new_tail;
Matt Murphy40f28c72014-12-03 17:12:301205 },
Piotr Czarnecki59d41532014-12-16 23:37:551206 (true, false, _) => unsafe {
Matt Murphy40f28c72014-12-03 17:12:301207 // contiguous, insert closer to head:
1208 //
1209 // T I H
1210 // [. . . o o o o A o o . . . . . .]
1211 //
1212 // T H
1213 // [. . . o o o o I A o o . . . . .]
1214 // M M M
1215
Piotr Czarnecki59d41532014-12-16 23:37:551216 self.copy(idx + 1, idx, self.head - idx);
Felix S. Klock IIe7c98612015-02-19 07:33:321217 self.head = self.wrap_add(self.head, 1);
Matt Murphy40f28c72014-12-03 17:12:301218 },
Piotr Czarnecki59d41532014-12-16 23:37:551219 (false, true, true) => unsafe {
1220 // discontiguous, insert closer to tail, tail section:
Matt Murphy40f28c72014-12-03 17:12:301221 //
1222 // H T I
1223 // [o o o o o o . . . . . o o A o o]
1224 //
1225 // H T
1226 // [o o o o o o . . . . o o I A o o]
1227 // M M
1228
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251229 self.copy(self.tail - 1, self.tail, index);
Piotr Czarnecki59d41532014-12-16 23:37:551230 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301231 },
Piotr Czarnecki59d41532014-12-16 23:37:551232 (false, false, true) => unsafe {
1233 // discontiguous, insert closer to head, tail section:
Matt Murphy40f28c72014-12-03 17:12:301234 //
1235 // H T I
1236 // [o o . . . . . . . o o o o o A o]
1237 //
1238 // H T
1239 // [o o o . . . . . . o o o o o I A]
1240 // M M M M
1241
Matt Murphy40f28c72014-12-03 17:12:301242 // copy elements up to new head
Piotr Czarnecki59d41532014-12-16 23:37:551243 self.copy(1, 0, self.head);
Matt Murphy40f28c72014-12-03 17:12:301244
1245 // copy last element into empty spot at bottom of buffer
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211246 self.copy(0, self.cap() - 1, 1);
Matt Murphy40f28c72014-12-03 17:12:301247
1248 // move elements from idx to end forward not including ^ element
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211249 self.copy(idx + 1, idx, self.cap() - 1 - idx);
Piotr Czarnecki59d41532014-12-16 23:37:551250
1251 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301252 },
Piotr Czarnecki59d41532014-12-16 23:37:551253 (false, true, false) if idx == 0 => unsafe {
1254 // discontiguous, insert is closer to tail, head section,
Matt Murphy40f28c72014-12-03 17:12:301255 // and is at index zero in the internal buffer:
1256 //
1257 // I H T
1258 // [A o o o o o o o o o . . . o o o]
1259 //
1260 // H T
1261 // [A o o o o o o o o o . . o o o I]
1262 // M M M
1263
Matt Murphy40f28c72014-12-03 17:12:301264 // copy elements up to new tail
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211265 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301266
1267 // copy last element into empty spot at bottom of buffer
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211268 self.copy(self.cap() - 1, 0, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551269
1270 self.tail -= 1;
Matt Murphy40f28c72014-12-03 17:12:301271 },
Piotr Czarnecki59d41532014-12-16 23:37:551272 (false, true, false) => unsafe {
1273 // discontiguous, insert closer to tail, head section:
Matt Murphy40f28c72014-12-03 17:12:301274 //
1275 // I H T
1276 // [o o o A o o o o o o . . . o o o]
1277 //
1278 // H T
1279 // [o o I A o o o o o o . . o o o o]
1280 // M M M M M M
1281
Matt Murphy40f28c72014-12-03 17:12:301282 // copy elements up to new tail
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211283 self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
Matt Murphy40f28c72014-12-03 17:12:301284
1285 // copy last element into empty spot at bottom of buffer
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211286 self.copy(self.cap() - 1, 0, 1);
Matt Murphy40f28c72014-12-03 17:12:301287
1288 // move elements from idx-1 to end forward not including ^ element
1289 self.copy(0, 1, idx - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551290
1291 self.tail -= 1;
1292 },
1293 (false, false, false) => unsafe {
1294 // discontiguous, insert closer to head, head section:
Matt Murphy40f28c72014-12-03 17:12:301295 //
1296 // I H T
1297 // [o o o o A o o . . . . . . o o o]
1298 //
1299 // H T
1300 // [o o o o I A o o . . . . . o o o]
1301 // M M M
1302
Piotr Czarnecki59d41532014-12-16 23:37:551303 self.copy(idx + 1, idx, self.head - idx);
1304 self.head += 1;
Matt Murphy40f28c72014-12-03 17:12:301305 }
1306 }
1307
1308 // tail might've been changed so we need to recalculate
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251309 let new_idx = self.wrap_add(self.tail, index);
Matt Murphy40f28c72014-12-03 17:12:301310 unsafe {
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251311 self.buffer_write(new_idx, value);
Matt Murphy40f28c72014-12-03 17:12:301312 }
1313 }
Piotr Czarnecki59d41532014-12-16 23:37:551314
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251315 /// Removes and returns the element at `index` from the `VecDeque`.
Piotr Czarnecki59d41532014-12-16 23:37:551316 /// Whichever end is closer to the removal point will be moved to make
1317 /// room, and all the affected elements will be moved to new positions.
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251318 /// Returns `None` if `index` is out of bounds.
Piotr Czarnecki59d41532014-12-16 23:37:551319 ///
Piotr Czarnecki156a1c32015-01-05 14:48:581320 /// # Examples
Joseph Crailfcf3f322015-03-13 02:42:381321 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551322 /// use std::collections::VecDeque;
Piotr Czarnecki59d41532014-12-16 23:37:551323 ///
Aaron Turon5fa9de12015-02-18 07:44:551324 /// let mut buf = VecDeque::new();
Tshepang Lekhonkhobea7fe2882015-07-17 21:49:131325 /// buf.push_back(1);
1326 /// buf.push_back(2);
1327 /// buf.push_back(3);
1328 ///
1329 /// assert_eq!(buf.remove(1), Some(2));
1330 /// assert_eq!(buf.get(1), Some(&3));
Piotr Czarnecki59d41532014-12-16 23:37:551331 /// ```
Brian Andersonb44ee372015-01-24 05:48:201332 #[stable(feature = "rust1", since = "1.0.0")]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251333 pub fn remove(&mut self, index: usize) -> Option<T> {
1334 if self.is_empty() || self.len() <= index {
Piotr Czarnecki59d41532014-12-16 23:37:551335 return None;
1336 }
1337
1338 // There are three main cases:
1339 // Elements are contiguous
1340 // Elements are discontiguous and the removal is in the tail section
1341 // Elements are discontiguous and the removal is in the head section
1342 // - special case when elements are technically contiguous,
1343 // but self.head = 0
1344 //
1345 // For each of those there are two more cases:
1346 // Insert is closer to tail
1347 // Insert is closer to head
1348 //
1349 // Key: H - self.head
1350 // T - self.tail
1351 // o - Valid element
1352 // x - Element marked for removal
1353 // R - Indicates element that is being removed
1354 // M - Indicates element was moved
1355
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251356 let idx = self.wrap_add(self.tail, index);
Piotr Czarnecki59d41532014-12-16 23:37:551357
1358 let elem = unsafe {
1359 Some(self.buffer_read(idx))
1360 };
1361
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251362 let distance_to_tail = index;
1363 let distance_to_head = self.len() - index;
Piotr Czarnecki59d41532014-12-16 23:37:551364
Piotr Czarnecki156a1c32015-01-05 14:48:581365 let contiguous = self.is_contiguous();
Piotr Czarnecki59d41532014-12-16 23:37:551366
1367 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1368 (true, true, _) => unsafe {
1369 // contiguous, remove closer to tail:
1370 //
1371 // T R H
1372 // [. . . o o x o o o o . . . . . .]
1373 //
1374 // T H
1375 // [. . . . o o o o o o . . . . . .]
1376 // M M
1377
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251378 self.copy(self.tail + 1, self.tail, index);
Piotr Czarnecki59d41532014-12-16 23:37:551379 self.tail += 1;
1380 },
1381 (true, false, _) => unsafe {
1382 // contiguous, remove closer to head:
1383 //
1384 // T R H
1385 // [. . . o o o o x o o . . . . . .]
1386 //
1387 // T H
1388 // [. . . o o o o o o . . . . . . .]
1389 // M M
1390
1391 self.copy(idx, idx + 1, self.head - idx - 1);
1392 self.head -= 1;
1393 },
1394 (false, true, true) => unsafe {
1395 // discontiguous, remove closer to tail, tail section:
1396 //
1397 // H T R
1398 // [o o o o o o . . . . . o o x o o]
1399 //
1400 // H T
1401 // [o o o o o o . . . . . . o o o o]
1402 // M M
1403
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251404 self.copy(self.tail + 1, self.tail, index);
Felix S. Klock IIe7c98612015-02-19 07:33:321405 self.tail = self.wrap_add(self.tail, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551406 },
1407 (false, false, false) => unsafe {
1408 // discontiguous, remove closer to head, head section:
1409 //
1410 // R H T
1411 // [o o o o x o o . . . . . . o o o]
1412 //
1413 // H T
1414 // [o o o o o o . . . . . . . o o o]
1415 // M M
1416
1417 self.copy(idx, idx + 1, self.head - idx - 1);
1418 self.head -= 1;
1419 },
1420 (false, false, true) => unsafe {
1421 // discontiguous, remove closer to head, tail section:
1422 //
1423 // H T R
1424 // [o o o . . . . . . o o o o o x o]
1425 //
1426 // H T
1427 // [o o . . . . . . . o o o o o o o]
1428 // M M M M
1429 //
1430 // or quasi-discontiguous, remove next to head, tail section:
1431 //
1432 // H T R
1433 // [. . . . . . . . . o o o o o x o]
1434 //
1435 // T H
1436 // [. . . . . . . . . o o o o o o .]
1437 // M
1438
1439 // draw in elements in the tail section
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211440 self.copy(idx, idx + 1, self.cap() - idx - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551441
1442 // Prevents underflow.
1443 if self.head != 0 {
1444 // copy first element into empty spot
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211445 self.copy(self.cap() - 1, 0, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551446
1447 // move elements in the head section backwards
1448 self.copy(0, 1, self.head - 1);
1449 }
1450
Felix S. Klock IIe7c98612015-02-19 07:33:321451 self.head = self.wrap_sub(self.head, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551452 },
1453 (false, true, false) => unsafe {
1454 // discontiguous, remove closer to tail, head section:
1455 //
1456 // R H T
1457 // [o o x o o o o o o o . . . o o o]
1458 //
1459 // H T
1460 // [o o o o o o o o o o . . . . o o]
1461 // M M M M M
1462
1463 // draw in elements up to idx
1464 self.copy(1, 0, idx);
1465
1466 // copy last element into empty spot
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211467 self.copy(0, self.cap() - 1, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551468
1469 // move elements from tail to end forward, excluding the last one
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211470 self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
Piotr Czarnecki59d41532014-12-16 23:37:551471
Felix S. Klock IIe7c98612015-02-19 07:33:321472 self.tail = self.wrap_add(self.tail, 1);
Piotr Czarnecki59d41532014-12-16 23:37:551473 }
1474 }
1475
1476 return elem;
1477 }
Alexisdc930b12015-02-07 16:46:161478
1479 /// Splits the collection into two at the given index.
1480 ///
1481 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1482 /// and the returned `Self` contains elements `[at, len)`.
1483 ///
1484 /// Note that the capacity of `self` does not change.
1485 ///
1486 /// # Panics
1487 ///
1488 /// Panics if `at > len`
1489 ///
1490 /// # Examples
Alexis3c18bc42015-02-07 17:13:321491 ///
1492 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551493 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321494 ///
Aaron Turon5fa9de12015-02-18 07:44:551495 /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
Alexisdc930b12015-02-07 16:46:161496 /// let buf2 = buf.split_off(1);
1497 /// // buf = [1], buf2 = [2, 3]
1498 /// assert_eq!(buf.len(), 1);
1499 /// assert_eq!(buf2.len(), 2);
1500 /// ```
1501 #[inline]
Alex Crichtonf0b13262015-09-10 20:26:441502 #[stable(feature = "split_off", since = "1.4.0")]
Alexisdc930b12015-02-07 16:46:161503 pub fn split_off(&mut self, at: usize) -> Self {
1504 let len = self.len();
1505 assert!(at <= len, "`at` out of bounds");
1506
1507 let other_len = len - at;
Aaron Turon5fa9de12015-02-18 07:44:551508 let mut other = VecDeque::with_capacity(other_len);
Alexisdc930b12015-02-07 16:46:161509
1510 unsafe {
1511 let (first_half, second_half) = self.as_slices();
1512
1513 let first_len = first_half.len();
1514 let second_len = second_half.len();
1515 if at < first_len {
1516 // `at` lies in the first half.
1517 let amount_in_first = first_len - at;
1518
Alex Crichtonacd48a22015-03-27 18:12:281519 ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize),
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211520 other.ptr(),
Alex Crichtonab456942015-02-23 19:39:161521 amount_in_first);
Alexisdc930b12015-02-07 16:46:161522
1523 // just take all of the second half.
Alex Crichtonacd48a22015-03-27 18:12:281524 ptr::copy_nonoverlapping(second_half.as_ptr(),
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211525 other.ptr().offset(amount_in_first as isize),
Alex Crichtonab456942015-02-23 19:39:161526 second_len);
Alexisdc930b12015-02-07 16:46:161527 } else {
1528 // `at` lies in the second half, need to factor in the elements we skipped
1529 // in the first half.
1530 let offset = at - first_len;
1531 let amount_in_second = second_len - offset;
Alex Crichtonacd48a22015-03-27 18:12:281532 ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize),
Alexis Beingessnerbfa0e1f2015-07-10 04:57:211533 other.ptr(),
Alex Crichtonab456942015-02-23 19:39:161534 amount_in_second);
Alexisdc930b12015-02-07 16:46:161535 }
1536 }
1537
1538 // Cleanup where the ends of the buffers are
Felix S. Klock IIe7c98612015-02-19 07:33:321539 self.head = self.wrap_sub(self.head, other_len);
Alexisdc930b12015-02-07 16:46:161540 other.head = other.wrap_index(other_len);
1541
1542 other
1543 }
Alexis3c18bc42015-02-07 17:13:321544
1545 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1546 ///
1547 /// # Panics
1548 ///
1549 /// Panics if the new number of elements in self overflows a `usize`.
1550 ///
1551 /// # Examples
1552 ///
1553 /// ```
Aaron Turon5fa9de12015-02-18 07:44:551554 /// use std::collections::VecDeque;
Alexis3c18bc42015-02-07 17:13:321555 ///
Aaron Turon5fa9de12015-02-18 07:44:551556 /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
1557 /// let mut buf2: VecDeque<_> = vec![4, 5, 6].into_iter().collect();
Alexis3c18bc42015-02-07 17:13:321558 /// buf.append(&mut buf2);
1559 /// assert_eq!(buf.len(), 6);
1560 /// assert_eq!(buf2.len(), 0);
1561 /// ```
1562 #[inline]
Alex Crichtonf0b13262015-09-10 20:26:441563 #[stable(feature = "append", since = "1.4.0")]
Alexis3c18bc42015-02-07 17:13:321564 pub fn append(&mut self, other: &mut Self) {
1565 // naive impl
Michael Layzell45be6fc2015-08-07 02:03:141566 self.extend(other.drain(..));
Alexis3c18bc42015-02-07 17:13:321567 }
Steven Allendecf3952015-04-27 17:47:191568
1569 /// Retains only the elements specified by the predicate.
1570 ///
1571 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1572 /// This method operates in place and preserves the order of the retained
1573 /// elements.
1574 ///
1575 /// # Examples
1576 ///
1577 /// ```
Steven Allendecf3952015-04-27 17:47:191578 /// use std::collections::VecDeque;
1579 ///
1580 /// let mut buf = VecDeque::new();
1581 /// buf.extend(1..5);
1582 /// buf.retain(|&x| x%2 == 0);
1583 ///
1584 /// let v: Vec<_> = buf.into_iter().collect();
1585 /// assert_eq!(&v[..], &[2, 4]);
1586 /// ```
Alex Crichtonf0b13262015-09-10 20:26:441587 #[stable(feature = "vec_deque_retain", since = "1.4.0")]
Steven Allendecf3952015-04-27 17:47:191588 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
1589 let len = self.len();
1590 let mut del = 0;
1591 for i in 0..len {
1592 if !f(&self[i]) {
1593 del += 1;
1594 } else if del > 0 {
1595 self.swap(i-del, i);
1596 }
1597 }
1598 if del > 0 {
1599 self.truncate(len - del);
1600 }
1601 }
Jed Estep4f7a7422013-06-25 19:08:471602}
1603
Aaron Turon5fa9de12015-02-18 07:44:551604impl<T: Clone> VecDeque<T> {
Corey Richardson8e2ce462015-07-05 07:49:361605 /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len,
Piotr Czarnecki156a1c32015-01-05 14:48:581606 /// either by removing excess elements or by appending copies of a value to the back.
1607 ///
1608 /// # Examples
1609 ///
1610 /// ```
Steve Klabnikba5fcb72015-07-27 14:50:191611 /// #![feature(deque_extras)]
1612 ///
Aaron Turon5fa9de12015-02-18 07:44:551613 /// use std::collections::VecDeque;
Piotr Czarnecki156a1c32015-01-05 14:48:581614 ///
Aaron Turon5fa9de12015-02-18 07:44:551615 /// let mut buf = VecDeque::new();
Tobias Bucher7f64fe42015-01-25 21:05:031616 /// buf.push_back(5);
1617 /// buf.push_back(10);
Piotr Czarnecki156a1c32015-01-05 14:48:581618 /// buf.push_back(15);
1619 /// buf.resize(2, 0);
1620 /// buf.resize(6, 20);
Joshua Landauca7418b2015-06-10 16:22:201621 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(&buf) {
Piotr Czarnecki156a1c32015-01-05 14:48:581622 /// assert_eq!(a, b);
1623 /// }
1624 /// ```
Alex Crichtond444d0c2015-06-09 21:39:231625 #[unstable(feature = "deque_extras",
Alex Crichton377c11a2015-08-13 05:19:511626 reason = "matches collection reform specification; waiting on panic semantics",
1627 issue = "27788")]
Alexise250fe32015-02-05 02:17:191628 pub fn resize(&mut self, new_len: usize, value: T) {
Piotr Czarnecki156a1c32015-01-05 14:48:581629 let len = self.len();
1630
1631 if new_len > len {
1632 self.extend(repeat(value).take(new_len - len))
1633 } else {
1634 self.truncate(new_len);
1635 }
1636 }
1637}
1638
Colin Sherratt7a666df2014-10-19 20:19:071639/// Returns the index in the underlying buffer for a given logical element index.
1640#[inline]
Alexise250fe32015-02-05 02:17:191641fn wrap_index(index: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071642 // size is always a power of 2
Ulrik Sverdrup66f5dc12015-09-18 14:32:521643 debug_assert!(size.is_power_of_two());
Colin Sherratt40191182014-11-12 01:22:071644 index & (size - 1)
Colin Sherratt7a666df2014-10-19 20:19:071645}
1646
1647/// Calculate the number of elements left to be read in the buffer
1648#[inline]
Alexise250fe32015-02-05 02:17:191649fn count(tail: usize, head: usize, size: usize) -> usize {
Colin Sherratt7a666df2014-10-19 20:19:071650 // size is always a power of 2
Felix S. Klock IIe7c98612015-02-19 07:33:321651 (head.wrapping_sub(tail)) & (size - 1)
Colin Sherratt7a666df2014-10-19 20:19:071652}
1653
Aaron Turon5fa9de12015-02-18 07:44:551654/// `VecDeque` iterator.
Brian Andersonb44ee372015-01-24 05:48:201655#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101656pub struct Iter<'a, T:'a> {
Colin Sherratt7a666df2014-10-19 20:19:071657 ring: &'a [T],
Alexise250fe32015-02-05 02:17:191658 tail: usize,
1659 head: usize
Niko Matsakis1b487a82014-08-28 01:46:521660}
1661
Jorge Aparicio351409a2015-01-04 03:54:181662// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
Huon Wilsonb7832ed2014-12-30 10:01:361663impl<'a, T> Clone for Iter<'a, T> {
1664 fn clone(&self) -> Iter<'a, T> {
1665 Iter {
1666 ring: self.ring,
1667 tail: self.tail,
1668 head: self.head
1669 }
1670 }
1671}
1672
Brian Andersonb44ee372015-01-24 05:48:201673#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351674impl<'a, T> Iterator for Iter<'a, T> {
1675 type Item = &'a T;
1676
Niko Matsakisbc4164d2013-11-16 22:29:391677 #[inline]
Erik Price5731ca32013-12-10 07:16:181678 fn next(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071679 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391680 return None;
1681 }
Colin Sherratt7a666df2014-10-19 20:19:071682 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:321683 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181684 unsafe { Some(self.ring.get_unchecked(tail)) }
Niko Matsakisbc4164d2013-11-16 22:29:391685 }
1686
1687 #[inline]
Alexise250fe32015-02-05 02:17:191688 fn size_hint(&self) -> (usize, Option<usize>) {
Colin Sherratt7a666df2014-10-19 20:19:071689 let len = count(self.tail, self.head, self.ring.len());
Niko Matsakisbc4164d2013-11-16 22:29:391690 (len, Some(len))
1691 }
1692}
1693
Brian Andersonb44ee372015-01-24 05:48:201694#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351695impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391696 #[inline]
Erik Price5731ca32013-12-10 07:16:181697 fn next_back(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:071698 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391699 return None;
1700 }
Felix S. Klock IIe7c98612015-02-19 07:33:321701 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
Aaron Turon6abfac02014-12-30 18:51:181702 unsafe { Some(self.ring.get_unchecked(self.head)) }
Niko Matsakisbc4164d2013-11-16 22:29:391703 }
1704}
Jed Estep35314c92013-06-26 15:38:291705
Brian Andersonb44ee372015-01-24 05:48:201706#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351707impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241708
Aaron Turon5fa9de12015-02-18 07:44:551709/// `VecDeque` mutable iterator.
Brian Andersonb44ee372015-01-24 05:48:201710#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101711pub struct IterMut<'a, T:'a> {
Edward Wang101498c2015-02-25 10:11:231712 ring: &'a mut [T],
Alexise250fe32015-02-05 02:17:191713 tail: usize,
1714 head: usize,
Niko Matsakis1b487a82014-08-28 01:46:521715}
1716
Brian Andersonb44ee372015-01-24 05:48:201717#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351718impl<'a, T> Iterator for IterMut<'a, T> {
1719 type Item = &'a mut T;
1720
Niko Matsakisbc4164d2013-11-16 22:29:391721 #[inline]
Erik Price5731ca32013-12-10 07:16:181722 fn next(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:071723 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391724 return None;
1725 }
Colin Sherratt7a666df2014-10-19 20:19:071726 let tail = self.tail;
Felix S. Klock IIe7c98612015-02-19 07:33:321727 self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111728
1729 unsafe {
Edward Wang101498c2015-02-25 10:11:231730 let elem = self.ring.get_unchecked_mut(tail);
1731 Some(&mut *(elem as *mut _))
Alex Crichton9d5d97b2014-10-15 06:05:011732 }
Niko Matsakisbc4164d2013-11-16 22:29:391733 }
1734
1735 #[inline]
Alexise250fe32015-02-05 02:17:191736 fn size_hint(&self) -> (usize, Option<usize>) {
Edward Wang101498c2015-02-25 10:11:231737 let len = count(self.tail, self.head, self.ring.len());
Colin Sherratt7a666df2014-10-19 20:19:071738 (len, Some(len))
Niko Matsakisbc4164d2013-11-16 22:29:391739 }
1740}
1741
Brian Andersonb44ee372015-01-24 05:48:201742#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351743impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:391744 #[inline]
Erik Price5731ca32013-12-10 07:16:181745 fn next_back(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:071746 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:391747 return None;
1748 }
Felix S. Klock IIe7c98612015-02-19 07:33:321749 self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len());
Alexis Beingessner865c2db2014-11-23 02:34:111750
1751 unsafe {
Edward Wang101498c2015-02-25 10:11:231752 let elem = self.ring.get_unchecked_mut(self.head);
1753 Some(&mut *(elem as *mut _))
Alexis Beingessner865c2db2014-11-23 02:34:111754 }
Niko Matsakisbc4164d2013-11-16 22:29:391755 }
1756}
Daniel Micayb47e1e92013-02-16 22:55:551757
Brian Andersonb44ee372015-01-24 05:48:201758#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351759impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:241760
Aaron Turon5fa9de12015-02-18 07:44:551761/// A by-value VecDeque iterator
Andrew Paseltiner64532f72015-03-23 12:50:471762#[derive(Clone)]
Brian Andersonb44ee372015-01-24 05:48:201763#[stable(feature = "rust1", since = "1.0.0")]
Florian Wilkensf8cfd242014-12-19 20:52:101764pub struct IntoIter<T> {
Aaron Turon5fa9de12015-02-18 07:44:551765 inner: VecDeque<T>,
Alexis Beingessner865c2db2014-11-23 02:34:111766}
1767
Brian Andersonb44ee372015-01-24 05:48:201768#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351769impl<T> Iterator for IntoIter<T> {
1770 type Item = T;
1771
Alexis Beingessner865c2db2014-11-23 02:34:111772 #[inline]
1773 fn next(&mut self) -> Option<T> {
1774 self.inner.pop_front()
1775 }
1776
1777 #[inline]
Alexise250fe32015-02-05 02:17:191778 fn size_hint(&self) -> (usize, Option<usize>) {
Alexis Beingessner865c2db2014-11-23 02:34:111779 let len = self.inner.len();
1780 (len, Some(len))
1781 }
1782}
1783
Brian Andersonb44ee372015-01-24 05:48:201784#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351785impl<T> DoubleEndedIterator for IntoIter<T> {
Alexis Beingessner865c2db2014-11-23 02:34:111786 #[inline]
1787 fn next_back(&mut self) -> Option<T> {
1788 self.inner.pop_back()
1789 }
1790}
1791
Brian Andersonb44ee372015-01-24 05:48:201792#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351793impl<T> ExactSizeIterator for IntoIter<T> {}
Alexis Beingessner865c2db2014-11-23 02:34:111794
Aaron Turon5fa9de12015-02-18 07:44:551795/// A draining VecDeque iterator
Alex Crichtond444d0c2015-06-09 21:39:231796#[unstable(feature = "drain",
Alex Crichton377c11a2015-08-13 05:19:511797 reason = "matches collection reform specification, waiting for dust to settle",
1798 issue = "27711")]
Clark Gaebeld57f2592014-12-16 22:45:031799pub struct Drain<'a, T: 'a> {
Michael Layzell45be6fc2015-08-07 02:03:141800 after_tail: usize,
1801 after_head: usize,
1802 iter: Iter<'a, T>,
1803 deque: *mut VecDeque<T>,
Clark Gaebeld57f2592014-12-16 22:45:031804}
1805
Michael Layzell493355d2015-09-24 22:19:231806unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1807unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1808
Brian Andersonb44ee372015-01-24 05:48:201809#[stable(feature = "rust1", since = "1.0.0")]
Clark Gaebeld57f2592014-12-16 22:45:031810impl<'a, T: 'a> Drop for Drain<'a, T> {
1811 fn drop(&mut self) {
Jorge Apariciof9865ea2015-01-11 02:50:071812 for _ in self.by_ref() {}
Michael Layzell45be6fc2015-08-07 02:03:141813
1814 let source_deque = unsafe { &mut *self.deque };
1815
1816 // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head
1817 //
1818 // T t h H
1819 // [. . . o o x x o o . . .]
1820 //
1821 let orig_tail = source_deque.tail;
1822 let drain_tail = source_deque.head;
1823 let drain_head = self.after_tail;
1824 let orig_head = self.after_head;
1825
1826 let tail_len = count(orig_tail, drain_tail, source_deque.cap());
1827 let head_len = count(drain_head, orig_head, source_deque.cap());
1828
1829 // Restore the original head value
1830 source_deque.head = orig_head;
1831
1832 match (tail_len, head_len) {
1833 (0, 0) => {
1834 source_deque.head = 0;
1835 source_deque.tail = 0;
1836 }
1837 (0, _) => {
1838 source_deque.tail = drain_head;
1839 }
1840 (_, 0) => {
1841 source_deque.head = drain_tail;
1842 }
1843 _ => unsafe {
1844 if tail_len <= head_len {
1845 source_deque.tail = source_deque.wrap_sub(drain_head, tail_len);
1846 source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len);
1847 } else {
1848 source_deque.head = source_deque.wrap_add(drain_tail, head_len);
1849 source_deque.wrap_copy(drain_tail, drain_head, head_len);
1850 }
1851 }
1852 }
Clark Gaebeld57f2592014-12-16 22:45:031853 }
1854}
1855
Brian Andersonb44ee372015-01-24 05:48:201856#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351857impl<'a, T: 'a> Iterator for Drain<'a, T> {
1858 type Item = T;
1859
Clark Gaebeld57f2592014-12-16 22:45:031860 #[inline]
1861 fn next(&mut self) -> Option<T> {
Michael Layzell45be6fc2015-08-07 02:03:141862 self.iter.next().map(|elt|
1863 unsafe {
1864 ptr::read(elt)
1865 }
1866 )
Clark Gaebeld57f2592014-12-16 22:45:031867 }
1868
1869 #[inline]
Alexise250fe32015-02-05 02:17:191870 fn size_hint(&self) -> (usize, Option<usize>) {
Michael Layzell45be6fc2015-08-07 02:03:141871 self.iter.size_hint()
Clark Gaebeld57f2592014-12-16 22:45:031872 }
1873}
1874
Brian Andersonb44ee372015-01-24 05:48:201875#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351876impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
Clark Gaebeld57f2592014-12-16 22:45:031877 #[inline]
1878 fn next_back(&mut self) -> Option<T> {
Michael Layzell45be6fc2015-08-07 02:03:141879 self.iter.next_back().map(|elt|
1880 unsafe {
1881 ptr::read(elt)
1882 }
1883 )
Clark Gaebeld57f2592014-12-16 22:45:031884 }
1885}
1886
Brian Andersonb44ee372015-01-24 05:48:201887#[stable(feature = "rust1", since = "1.0.0")]
Jorge Aparicio6b116be2015-01-02 04:15:351888impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
Clark Gaebeld57f2592014-12-16 22:45:031889
Brian Andersonb44ee372015-01-24 05:48:201890#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551891impl<A: PartialEq> PartialEq for VecDeque<A> {
1892 fn eq(&self, other: &VecDeque<A>) -> bool {
Colin Sherratt7a666df2014-10-19 20:19:071893 self.len() == other.len() &&
Joshua Landauca7418b2015-06-10 16:22:201894 self.iter().zip(other).all(|(a, b)| a.eq(b))
blake2-ppc10c76982013-07-06 13:27:321895 }
blake2-ppc10c76982013-07-06 13:27:321896}
1897
Brian Andersonb44ee372015-01-24 05:48:201898#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551899impl<A: Eq> Eq for VecDeque<A> {}
nham25acfde2014-08-01 20:05:031900
Brian Andersonb44ee372015-01-24 05:48:201901#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551902impl<A: PartialOrd> PartialOrd for VecDeque<A> {
1903 fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> {
Steven Fackler651c42f2015-08-24 04:59:071904 self.iter().partial_cmp(other.iter())
nham63615772014-07-27 03:18:561905 }
1906}
1907
Brian Andersonb44ee372015-01-24 05:48:201908#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551909impl<A: Ord> Ord for VecDeque<A> {
nham3737c532014-08-01 20:22:481910 #[inline]
Aaron Turon5fa9de12015-02-18 07:44:551911 fn cmp(&self, other: &VecDeque<A>) -> Ordering {
Steven Fackler651c42f2015-08-24 04:59:071912 self.iter().cmp(other.iter())
nham3737c532014-08-01 20:22:481913 }
1914}
1915
Brian Andersonb44ee372015-01-24 05:48:201916#[stable(feature = "rust1", since = "1.0.0")]
Alex Crichton5a32b4a2015-02-18 22:34:081917impl<A: Hash> Hash for VecDeque<A> {
Alex Crichtonf83e23a2015-02-18 04:48:071918 fn hash<H: Hasher>(&self, state: &mut H) {
1919 self.len().hash(state);
1920 for elt in self {
1921 elt.hash(state);
1922 }
1923 }
1924}
nham1cfa6562014-07-27 02:33:471925
Brian Andersonb44ee372015-01-24 05:48:201926#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551927impl<A> Index<usize> for VecDeque<A> {
Jorge Aparicio32dd5922015-01-03 15:40:101928 type Output = A;
1929
Niko Matsakisb4d4daf2015-03-21 23:33:271930 #[inline]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251931 fn index(&self, index: usize) -> &A {
1932 self.get(index).expect("Out of bounds access")
Niko Matsakisb4d4daf2015-03-21 23:33:271933 }
Jorge Aparicio32dd5922015-01-03 15:40:101934}
1935
Brian Andersonb44ee372015-01-24 05:48:201936#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551937impl<A> IndexMut<usize> for VecDeque<A> {
Niko Matsakisb4d4daf2015-03-21 23:33:271938 #[inline]
Tshepang Lekhonkhobeef2f4cd2015-07-17 19:28:251939 fn index_mut(&mut self, index: usize) -> &mut A {
1940 self.get_mut(index).expect("Out of bounds access")
Niko Matsakisb4d4daf2015-03-21 23:33:271941 }
Jorge Aparicio32dd5922015-01-03 15:40:101942}
1943
Brian Andersonb44ee372015-01-24 05:48:201944#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551945impl<A> FromIterator<A> for VecDeque<A> {
Alexis66613e22015-02-18 18:06:211946 fn from_iter<T: IntoIterator<Item=A>>(iterable: T) -> VecDeque<A> {
1947 let iterator = iterable.into_iter();
blake2-ppcf8ae5262013-07-30 00:06:491948 let (lower, _) = iterator.size_hint();
Aaron Turon5fa9de12015-02-18 07:44:551949 let mut deq = VecDeque::with_capacity(lower);
blake2-ppcf8ae5262013-07-30 00:06:491950 deq.extend(iterator);
blake2-ppc08dc72f2013-07-06 03:42:451951 deq
1952 }
1953}
1954
Alex Crichtoncc687862015-02-17 18:06:241955#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551956impl<T> IntoIterator for VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101957 type Item = T;
1958 type IntoIter = IntoIter<T>;
1959
Alex Crichton8f5b5f92015-04-17 21:31:301960 /// Consumes the list into a front-to-back iterator yielding elements by
1961 /// value.
Jorge Aparicioe7273782015-02-13 22:55:101962 fn into_iter(self) -> IntoIter<T> {
Alex Crichton8f5b5f92015-04-17 21:31:301963 IntoIter {
1964 inner: self,
1965 }
Jorge Aparicioe7273782015-02-13 22:55:101966 }
1967}
1968
Alex Crichtoncc687862015-02-17 18:06:241969#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551970impl<'a, T> IntoIterator for &'a VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101971 type Item = &'a T;
1972 type IntoIter = Iter<'a, T>;
1973
1974 fn into_iter(self) -> Iter<'a, T> {
1975 self.iter()
1976 }
1977}
1978
Alex Crichtoncc687862015-02-17 18:06:241979#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551980impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
Jorge Aparicioe7273782015-02-13 22:55:101981 type Item = &'a mut T;
1982 type IntoIter = IterMut<'a, T>;
1983
1984 fn into_iter(mut self) -> IterMut<'a, T> {
1985 self.iter_mut()
1986 }
1987}
1988
Brian Andersonb44ee372015-01-24 05:48:201989#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:551990impl<A> Extend<A> for VecDeque<A> {
Alexis4a9d1902015-02-18 15:04:301991 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
1992 for elt in iter {
Alexis Beingessnercf3b2e42014-11-06 17:24:471993 self.push_back(elt);
blake2-ppcf8ae5262013-07-30 00:06:491994 }
1995 }
1996}
1997
Johannes Oertelb36ed7d2015-06-03 10:38:421998#[stable(feature = "extend_ref", since = "1.2.0")]
1999impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
2000 fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
2001 self.extend(iter.into_iter().cloned());
2002 }
2003}
2004
Brian Andersonb44ee372015-01-24 05:48:202005#[stable(feature = "rust1", since = "1.0.0")]
Aaron Turon5fa9de12015-02-18 07:44:552006impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:042007 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Andrew Paseltinerdb187182015-09-25 16:03:032008 f.debug_list().entries(self).finish()
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:042009 }
2010}
Jorge Apariciocb5e4292015-03-12 00:44:022011
2012#[cfg(test)]
Johannes Oertel07cc7d92015-04-24 15:30:412013mod tests {
Wesley Wiser99df3832015-05-30 23:49:562014 use core::iter::Iterator;
Jorge Apariciocb5e4292015-03-12 00:44:022015 use core::option::Option::Some;
2016
2017 use test;
2018
2019 use super::VecDeque;
2020
2021 #[bench]
2022 fn bench_push_back_100(b: &mut test::Bencher) {
2023 let mut deq = VecDeque::with_capacity(101);
2024 b.iter(|| {
2025 for i in 0..100 {
2026 deq.push_back(i);
2027 }
2028 deq.head = 0;
2029 deq.tail = 0;
2030 })
2031 }
2032
2033 #[bench]
2034 fn bench_push_front_100(b: &mut test::Bencher) {
2035 let mut deq = VecDeque::with_capacity(101);
2036 b.iter(|| {
2037 for i in 0..100 {
2038 deq.push_front(i);
2039 }
2040 deq.head = 0;
2041 deq.tail = 0;
2042 })
2043 }
2044
2045 #[bench]
2046 fn bench_pop_back_100(b: &mut test::Bencher) {
2047 let mut deq= VecDeque::<i32>::with_capacity(101);
2048
2049 b.iter(|| {
2050 deq.head = 100;
2051 deq.tail = 0;
2052 while !deq.is_empty() {
2053 test::black_box(deq.pop_back());
2054 }
2055 })
2056 }
2057
2058 #[bench]
2059 fn bench_pop_front_100(b: &mut test::Bencher) {
2060 let mut deq = VecDeque::<i32>::with_capacity(101);
2061
2062 b.iter(|| {
2063 deq.head = 100;
2064 deq.tail = 0;
2065 while !deq.is_empty() {
2066 test::black_box(deq.pop_front());
2067 }
2068 })
2069 }
2070
2071 #[test]
2072 fn test_swap_front_back_remove() {
2073 fn test(back: bool) {
2074 // This test checks that every single combination of tail position and length is tested.
2075 // Capacity 15 should be large enough to cover every case.
2076 let mut tester = VecDeque::with_capacity(15);
2077 let usable_cap = tester.capacity();
2078 let final_len = usable_cap / 2;
2079
2080 for len in 0..final_len {
2081 let expected = if back {
2082 (0..len).collect()
2083 } else {
2084 (0..len).rev().collect()
2085 };
2086 for tail_pos in 0..usable_cap {
2087 tester.tail = tail_pos;
2088 tester.head = tail_pos;
2089 if back {
2090 for i in 0..len * 2 {
2091 tester.push_front(i);
2092 }
2093 for i in 0..len {
2094 assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
2095 }
2096 } else {
2097 for i in 0..len * 2 {
2098 tester.push_back(i);
2099 }
2100 for i in 0..len {
2101 let idx = tester.len() - 1 - i;
2102 assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
2103 }
2104 }
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212105 assert!(tester.tail < tester.cap());
2106 assert!(tester.head < tester.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022107 assert_eq!(tester, expected);
2108 }
2109 }
2110 }
2111 test(true);
2112 test(false);
2113 }
2114
2115 #[test]
2116 fn test_insert() {
2117 // This test checks that every single combination of tail position, length, and
2118 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2119
2120 let mut tester = VecDeque::with_capacity(15);
2121 // can't guarantee we got 15, so have to get what we got.
2122 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2123 // this test isn't covering what it wants to
2124 let cap = tester.capacity();
2125
2126
2127 // len is the length *after* insertion
2128 for len in 1..cap {
2129 // 0, 1, 2, .., len - 1
Alex Crichtond4a2c942015-03-30 18:00:052130 let expected = (0..).take(len).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022131 for tail_pos in 0..cap {
2132 for to_insert in 0..len {
2133 tester.tail = tail_pos;
2134 tester.head = tail_pos;
2135 for i in 0..len {
2136 if i != to_insert {
2137 tester.push_back(i);
2138 }
2139 }
2140 tester.insert(to_insert, to_insert);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212141 assert!(tester.tail < tester.cap());
2142 assert!(tester.head < tester.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022143 assert_eq!(tester, expected);
2144 }
2145 }
2146 }
2147 }
2148
2149 #[test]
2150 fn test_remove() {
2151 // This test checks that every single combination of tail position, length, and
2152 // removal position is tested. Capacity 15 should be large enough to cover every case.
2153
2154 let mut tester = VecDeque::with_capacity(15);
2155 // can't guarantee we got 15, so have to get what we got.
2156 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2157 // this test isn't covering what it wants to
2158 let cap = tester.capacity();
2159
2160 // len is the length *after* removal
2161 for len in 0..cap - 1 {
2162 // 0, 1, 2, .., len - 1
Alex Crichtond4a2c942015-03-30 18:00:052163 let expected = (0..).take(len).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022164 for tail_pos in 0..cap {
2165 for to_remove in 0..len + 1 {
2166 tester.tail = tail_pos;
2167 tester.head = tail_pos;
2168 for i in 0..len {
2169 if i == to_remove {
2170 tester.push_back(1234);
2171 }
2172 tester.push_back(i);
2173 }
2174 if to_remove == len {
2175 tester.push_back(1234);
2176 }
2177 tester.remove(to_remove);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212178 assert!(tester.tail < tester.cap());
2179 assert!(tester.head < tester.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022180 assert_eq!(tester, expected);
2181 }
2182 }
2183 }
2184 }
2185
2186 #[test]
Michael Layzell45be6fc2015-08-07 02:03:142187 fn test_drain() {
2188 let mut tester: VecDeque<usize> = VecDeque::with_capacity(7);
2189
2190 let cap = tester.capacity();
2191 for len in 0..cap + 1 {
2192 for tail in 0..cap + 1 {
2193 for drain_start in 0..len + 1 {
2194 for drain_end in drain_start..len + 1 {
2195 tester.tail = tail;
2196 tester.head = tail;
2197 for i in 0..len {
2198 tester.push_back(i);
2199 }
2200
2201 // Check that we drain the correct values
2202 let drained: VecDeque<_> =
2203 tester.drain(drain_start..drain_end).collect();
2204 let drained_expected: VecDeque<_> =
2205 (drain_start..drain_end).collect();
2206 assert_eq!(drained, drained_expected);
2207
2208 // We shouldn't have changed the capacity or made the
2209 // head or tail out of bounds
2210 assert_eq!(tester.capacity(), cap);
2211 assert!(tester.tail < tester.cap());
2212 assert!(tester.head < tester.cap());
2213
2214 // We should see the correct values in the VecDeque
2215 let expected: VecDeque<_> =
2216 (0..drain_start).chain(drain_end..len).collect();
2217 assert_eq!(expected, tester);
2218 }
2219 }
2220 }
2221 }
2222 }
2223
2224 #[test]
Jorge Apariciocb5e4292015-03-12 00:44:022225 fn test_shrink_to_fit() {
2226 // This test checks that every single combination of head and tail position,
2227 // is tested. Capacity 15 should be large enough to cover every case.
2228
2229 let mut tester = VecDeque::with_capacity(15);
2230 // can't guarantee we got 15, so have to get what we got.
2231 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2232 // this test isn't covering what it wants to
2233 let cap = tester.capacity();
2234 tester.reserve(63);
2235 let max_cap = tester.capacity();
2236
2237 for len in 0..cap + 1 {
2238 // 0, 1, 2, .., len - 1
Alex Crichtond4a2c942015-03-30 18:00:052239 let expected = (0..).take(len).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022240 for tail_pos in 0..max_cap + 1 {
2241 tester.tail = tail_pos;
2242 tester.head = tail_pos;
2243 tester.reserve(63);
2244 for i in 0..len {
2245 tester.push_back(i);
2246 }
2247 tester.shrink_to_fit();
2248 assert!(tester.capacity() <= cap);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212249 assert!(tester.tail < tester.cap());
2250 assert!(tester.head < tester.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022251 assert_eq!(tester, expected);
2252 }
2253 }
2254 }
2255
2256 #[test]
2257 fn test_split_off() {
2258 // This test checks that every single combination of tail position, length, and
2259 // split position is tested. Capacity 15 should be large enough to cover every case.
2260
2261 let mut tester = VecDeque::with_capacity(15);
2262 // can't guarantee we got 15, so have to get what we got.
2263 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2264 // this test isn't covering what it wants to
2265 let cap = tester.capacity();
2266
2267 // len is the length *before* splitting
2268 for len in 0..cap {
2269 // index to split at
2270 for at in 0..len + 1 {
2271 // 0, 1, 2, .., at - 1 (may be empty)
Alex Crichtond4a2c942015-03-30 18:00:052272 let expected_self = (0..).take(at).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022273 // at, at + 1, .., len - 1 (may be empty)
Alex Crichtond4a2c942015-03-30 18:00:052274 let expected_other = (at..).take(len - at).collect();
Jorge Apariciocb5e4292015-03-12 00:44:022275
2276 for tail_pos in 0..cap {
2277 tester.tail = tail_pos;
2278 tester.head = tail_pos;
2279 for i in 0..len {
2280 tester.push_back(i);
2281 }
2282 let result = tester.split_off(at);
Alexis Beingessnerbfa0e1f2015-07-10 04:57:212283 assert!(tester.tail < tester.cap());
2284 assert!(tester.head < tester.cap());
2285 assert!(result.tail < result.cap());
2286 assert!(result.head < result.cap());
Jorge Apariciocb5e4292015-03-12 00:44:022287 assert_eq!(tester, expected_self);
2288 assert_eq!(result, expected_other);
2289 }
2290 }
2291 }
2292 }
Ulrik Sverdrup66f5dc12015-09-18 14:32:522293
2294 #[test]
2295 fn test_zst_push() {
2296 const N: usize = 8;
2297
2298 // Zero sized type
2299 struct Zst;
2300
2301 // Test that for all possible sequences of push_front / push_back,
2302 // we end up with a deque of the correct size
2303
2304 for len in 0..N {
2305 let mut tester = VecDeque::with_capacity(len);
2306 assert_eq!(tester.len(), 0);
2307 assert!(tester.capacity() >= len);
2308 for case in 0..(1 << len) {
2309 assert_eq!(tester.len(), 0);
2310 for bit in 0..len {
2311 if case & (1 << bit) != 0 {
2312 tester.push_front(Zst);
2313 } else {
2314 tester.push_back(Zst);
2315 }
2316 }
2317 assert_eq!(tester.len(), len);
2318 assert_eq!(tester.iter().count(), len);
2319 tester.clear();
2320 }
2321 }
2322 }
Jorge Apariciocb5e4292015-03-12 00:44:022323}