]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
1 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT |
2 | // 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 | ||
cc61c64b | 11 | //! A double-ended queue implemented with a growable ring buffer. |
85aaf69f SL |
12 | //! |
13 | //! This queue has `O(1)` amortized inserts and removals from both ends of the | |
14 | //! container. It also has `O(1)` indexing like a vector. The contained elements | |
15 | //! are not required to be copyable, and the queue will be sendable if the | |
16 | //! contained type is sendable. | |
1a4d82fc | 17 | |
85aaf69f | 18 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 19 | |
1a4d82fc | 20 | use core::cmp::Ordering; |
1a4d82fc | 21 | use core::fmt; |
9e0c209e | 22 | use core::iter::{repeat, FromIterator, FusedIterator}; |
e9174d1e | 23 | use core::mem; |
8bb4bdeb | 24 | use core::ops::{Index, IndexMut, Place, Placer, InPlace}; |
c1a9b12d | 25 | use core::ptr; |
9e0c209e | 26 | use core::ptr::Shared; |
c34b1796 | 27 | use core::slice; |
1a4d82fc | 28 | |
85aaf69f | 29 | use core::hash::{Hash, Hasher}; |
85aaf69f | 30 | use core::cmp; |
1a4d82fc | 31 | |
c1a9b12d | 32 | use alloc::raw_vec::RawVec; |
1a4d82fc | 33 | |
b039eaaf | 34 | use super::range::RangeArgument; |
32a655c1 | 35 | use Bound::{Excluded, Included, Unbounded}; |
a7813a04 | 36 | use super::vec::Vec; |
b039eaaf | 37 | |
c34b1796 AL |
38 | const INITIAL_CAPACITY: usize = 7; // 2^3 - 1 |
39 | const MINIMUM_CAPACITY: usize = 1; // 2 - 1 | |
9cc50fc6 SL |
40 | #[cfg(target_pointer_width = "32")] |
41 | const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two | |
42 | #[cfg(target_pointer_width = "64")] | |
43 | const MAXIMUM_ZST_CAPACITY: usize = 1 << (64 - 1); // Largest possible power of two | |
85aaf69f | 44 | |
cc61c64b | 45 | /// A double-ended queue implemented with a growable ring buffer. |
c1a9b12d | 46 | /// |
cc61c64b XL |
47 | /// The "default" usage of this type as a queue is to use [`push_back`] to add to |
48 | /// the queue, and [`pop_front`] to remove from the queue. [`extend`] and [`append`] | |
b039eaaf SL |
49 | /// push onto the back in this manner, and iterating over `VecDeque` goes front |
50 | /// to back. | |
cc61c64b XL |
51 | /// |
52 | /// [`push_back`]: #method.push_back | |
53 | /// [`pop_front`]: #method.pop_front | |
54 | /// [`extend`]: #method.extend | |
55 | /// [`append`]: #method.append | |
85aaf69f SL |
56 | #[stable(feature = "rust1", since = "1.0.0")] |
57 | pub struct VecDeque<T> { | |
1a4d82fc JJ |
58 | // tail and head are pointers into the buffer. Tail always points |
59 | // to the first element that could be read, Head always points | |
60 | // to where data should be written. | |
c1a9b12d | 61 | // If tail == head the buffer is empty. The length of the ringbuffer |
1a4d82fc | 62 | // is defined as the distance between the two. |
85aaf69f SL |
63 | tail: usize, |
64 | head: usize, | |
c1a9b12d | 65 | buf: RawVec<T>, |
1a4d82fc JJ |
66 | } |
67 | ||
85aaf69f SL |
68 | #[stable(feature = "rust1", since = "1.0.0")] |
69 | impl<T: Clone> Clone for VecDeque<T> { | |
70 | fn clone(&self) -> VecDeque<T> { | |
71 | self.iter().cloned().collect() | |
1a4d82fc JJ |
72 | } |
73 | } | |
74 | ||
85aaf69f | 75 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 76 | unsafe impl<#[may_dangle] T> Drop for VecDeque<T> { |
1a4d82fc | 77 | fn drop(&mut self) { |
54a0048b SL |
78 | let (front, back) = self.as_mut_slices(); |
79 | unsafe { | |
80 | // use drop for [T] | |
81 | ptr::drop_in_place(front); | |
82 | ptr::drop_in_place(back); | |
83 | } | |
c1a9b12d | 84 | // RawVec handles deallocation |
1a4d82fc JJ |
85 | } |
86 | } | |
87 | ||
85aaf69f SL |
88 | #[stable(feature = "rust1", since = "1.0.0")] |
89 | impl<T> Default for VecDeque<T> { | |
9e0c209e | 90 | /// Creates an empty `VecDeque<T>`. |
1a4d82fc | 91 | #[inline] |
92a42be0 SL |
92 | fn default() -> VecDeque<T> { |
93 | VecDeque::new() | |
94 | } | |
1a4d82fc JJ |
95 | } |
96 | ||
85aaf69f | 97 | impl<T> VecDeque<T> { |
c1a9b12d SL |
98 | /// Marginally more convenient |
99 | #[inline] | |
100 | fn ptr(&self) -> *mut T { | |
101 | self.buf.ptr() | |
102 | } | |
103 | ||
104 | /// Marginally more convenient | |
105 | #[inline] | |
106 | fn cap(&self) -> usize { | |
e9174d1e SL |
107 | if mem::size_of::<T>() == 0 { |
108 | // For zero sized types, we are always at maximum capacity | |
109 | MAXIMUM_ZST_CAPACITY | |
110 | } else { | |
111 | self.buf.cap() | |
112 | } | |
c1a9b12d SL |
113 | } |
114 | ||
1a4d82fc JJ |
115 | /// Turn ptr into a slice |
116 | #[inline] | |
117 | unsafe fn buffer_as_slice(&self) -> &[T] { | |
c1a9b12d | 118 | slice::from_raw_parts(self.ptr(), self.cap()) |
1a4d82fc JJ |
119 | } |
120 | ||
121 | /// Turn ptr into a mut slice | |
122 | #[inline] | |
123 | unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] { | |
c1a9b12d | 124 | slice::from_raw_parts_mut(self.ptr(), self.cap()) |
1a4d82fc JJ |
125 | } |
126 | ||
127 | /// Moves an element out of the buffer | |
128 | #[inline] | |
85aaf69f | 129 | unsafe fn buffer_read(&mut self, off: usize) -> T { |
c1a9b12d | 130 | ptr::read(self.ptr().offset(off as isize)) |
1a4d82fc JJ |
131 | } |
132 | ||
133 | /// Writes an element into the buffer, moving it. | |
134 | #[inline] | |
c1a9b12d SL |
135 | unsafe fn buffer_write(&mut self, off: usize, value: T) { |
136 | ptr::write(self.ptr().offset(off as isize), value); | |
1a4d82fc JJ |
137 | } |
138 | ||
cc61c64b | 139 | /// Returns `true` if and only if the buffer is at full capacity. |
1a4d82fc | 140 | #[inline] |
92a42be0 SL |
141 | fn is_full(&self) -> bool { |
142 | self.cap() - self.len() == 1 | |
143 | } | |
1a4d82fc | 144 | |
85aaf69f SL |
145 | /// Returns the index in the underlying buffer for a given logical element |
146 | /// index. | |
1a4d82fc | 147 | #[inline] |
92a42be0 SL |
148 | fn wrap_index(&self, idx: usize) -> usize { |
149 | wrap_index(idx, self.cap()) | |
150 | } | |
1a4d82fc | 151 | |
c34b1796 AL |
152 | /// Returns the index in the underlying buffer for a given logical element |
153 | /// index + addend. | |
154 | #[inline] | |
155 | fn wrap_add(&self, idx: usize, addend: usize) -> usize { | |
c1a9b12d | 156 | wrap_index(idx.wrapping_add(addend), self.cap()) |
c34b1796 AL |
157 | } |
158 | ||
159 | /// Returns the index in the underlying buffer for a given logical element | |
160 | /// index - subtrahend. | |
161 | #[inline] | |
162 | fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize { | |
c1a9b12d | 163 | wrap_index(idx.wrapping_sub(subtrahend), self.cap()) |
c34b1796 AL |
164 | } |
165 | ||
1a4d82fc JJ |
166 | /// Copies a contiguous block of memory len long from src to dst |
167 | #[inline] | |
85aaf69f | 168 | unsafe fn copy(&self, dst: usize, src: usize, len: usize) { |
92a42be0 SL |
169 | debug_assert!(dst + len <= self.cap(), |
170 | "cpy dst={} src={} len={} cap={}", | |
171 | dst, | |
172 | src, | |
173 | len, | |
c1a9b12d | 174 | self.cap()); |
92a42be0 SL |
175 | debug_assert!(src + len <= self.cap(), |
176 | "cpy dst={} src={} len={} cap={}", | |
177 | dst, | |
178 | src, | |
179 | len, | |
c1a9b12d | 180 | self.cap()); |
92a42be0 SL |
181 | ptr::copy(self.ptr().offset(src as isize), |
182 | self.ptr().offset(dst as isize), | |
183 | len); | |
1a4d82fc JJ |
184 | } |
185 | ||
186 | /// Copies a contiguous block of memory len long from src to dst | |
187 | #[inline] | |
85aaf69f | 188 | unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) { |
92a42be0 SL |
189 | debug_assert!(dst + len <= self.cap(), |
190 | "cno dst={} src={} len={} cap={}", | |
191 | dst, | |
192 | src, | |
193 | len, | |
c1a9b12d | 194 | self.cap()); |
92a42be0 SL |
195 | debug_assert!(src + len <= self.cap(), |
196 | "cno dst={} src={} len={} cap={}", | |
197 | dst, | |
198 | src, | |
199 | len, | |
c1a9b12d | 200 | self.cap()); |
92a42be0 SL |
201 | ptr::copy_nonoverlapping(self.ptr().offset(src as isize), |
202 | self.ptr().offset(dst as isize), | |
203 | len); | |
1a4d82fc | 204 | } |
c1a9b12d | 205 | |
b039eaaf SL |
206 | /// Copies a potentially wrapping block of memory len long from src to dest. |
207 | /// (abs(dst - src) + len) must be no larger than cap() (There must be at | |
208 | /// most one continuous overlapping region between src and dest). | |
209 | unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) { | |
92a42be0 SL |
210 | #[allow(dead_code)] |
211 | fn diff(a: usize, b: usize) -> usize { | |
32a655c1 | 212 | if a <= b { b - a } else { a - b } |
92a42be0 SL |
213 | } |
214 | debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(), | |
215 | "wrc dst={} src={} len={} cap={}", | |
216 | dst, | |
217 | src, | |
218 | len, | |
219 | self.cap()); | |
b039eaaf | 220 | |
92a42be0 SL |
221 | if src == dst || len == 0 { |
222 | return; | |
223 | } | |
b039eaaf SL |
224 | |
225 | let dst_after_src = self.wrap_sub(dst, src) < len; | |
226 | ||
227 | let src_pre_wrap_len = self.cap() - src; | |
228 | let dst_pre_wrap_len = self.cap() - dst; | |
229 | let src_wraps = src_pre_wrap_len < len; | |
230 | let dst_wraps = dst_pre_wrap_len < len; | |
231 | ||
232 | match (dst_after_src, src_wraps, dst_wraps) { | |
233 | (_, false, false) => { | |
234 | // src doesn't wrap, dst doesn't wrap | |
235 | // | |
236 | // S . . . | |
237 | // 1 [_ _ A A B B C C _] | |
238 | // 2 [_ _ A A A A B B _] | |
239 | // D . . . | |
240 | // | |
241 | self.copy(dst, src, len); | |
242 | } | |
243 | (false, false, true) => { | |
244 | // dst before src, src doesn't wrap, dst wraps | |
245 | // | |
246 | // S . . . | |
247 | // 1 [A A B B _ _ _ C C] | |
248 | // 2 [A A B B _ _ _ A A] | |
249 | // 3 [B B B B _ _ _ A A] | |
250 | // . . D . | |
251 | // | |
252 | self.copy(dst, src, dst_pre_wrap_len); | |
253 | self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len); | |
254 | } | |
255 | (true, false, true) => { | |
256 | // src before dst, src doesn't wrap, dst wraps | |
257 | // | |
258 | // S . . . | |
259 | // 1 [C C _ _ _ A A B B] | |
260 | // 2 [B B _ _ _ A A B B] | |
261 | // 3 [B B _ _ _ A A A A] | |
262 | // . . D . | |
263 | // | |
264 | self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len); | |
265 | self.copy(dst, src, dst_pre_wrap_len); | |
266 | } | |
267 | (false, true, false) => { | |
268 | // dst before src, src wraps, dst doesn't wrap | |
269 | // | |
270 | // . . S . | |
271 | // 1 [C C _ _ _ A A B B] | |
272 | // 2 [C C _ _ _ B B B B] | |
273 | // 3 [C C _ _ _ B B C C] | |
274 | // D . . . | |
275 | // | |
276 | self.copy(dst, src, src_pre_wrap_len); | |
277 | self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len); | |
278 | } | |
279 | (true, true, false) => { | |
280 | // src before dst, src wraps, dst doesn't wrap | |
281 | // | |
282 | // . . S . | |
283 | // 1 [A A B B _ _ _ C C] | |
284 | // 2 [A A A A _ _ _ C C] | |
285 | // 3 [C C A A _ _ _ C C] | |
286 | // D . . . | |
287 | // | |
288 | self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len); | |
289 | self.copy(dst, src, src_pre_wrap_len); | |
290 | } | |
291 | (false, true, true) => { | |
292 | // dst before src, src wraps, dst wraps | |
293 | // | |
294 | // . . . S . | |
295 | // 1 [A B C D _ E F G H] | |
296 | // 2 [A B C D _ E G H H] | |
297 | // 3 [A B C D _ E G H A] | |
298 | // 4 [B C C D _ E G H A] | |
299 | // . . D . . | |
300 | // | |
301 | debug_assert!(dst_pre_wrap_len > src_pre_wrap_len); | |
302 | let delta = dst_pre_wrap_len - src_pre_wrap_len; | |
303 | self.copy(dst, src, src_pre_wrap_len); | |
304 | self.copy(dst + src_pre_wrap_len, 0, delta); | |
305 | self.copy(0, delta, len - dst_pre_wrap_len); | |
306 | } | |
307 | (true, true, true) => { | |
308 | // src before dst, src wraps, dst wraps | |
309 | // | |
310 | // . . S . . | |
311 | // 1 [A B C D _ E F G H] | |
312 | // 2 [A A B D _ E F G H] | |
313 | // 3 [H A B D _ E F G H] | |
314 | // 4 [H A B D _ E F F G] | |
315 | // . . . D . | |
316 | // | |
317 | debug_assert!(src_pre_wrap_len > dst_pre_wrap_len); | |
318 | let delta = src_pre_wrap_len - dst_pre_wrap_len; | |
319 | self.copy(delta, 0, len - src_pre_wrap_len); | |
320 | self.copy(0, self.cap() - delta, delta); | |
321 | self.copy(dst, src, dst_pre_wrap_len); | |
322 | } | |
323 | } | |
324 | } | |
325 | ||
c1a9b12d SL |
326 | /// Frobs the head and tail sections around to handle the fact that we |
327 | /// just reallocated. Unsafe because it trusts old_cap. | |
328 | #[inline] | |
329 | unsafe fn handle_cap_increase(&mut self, old_cap: usize) { | |
330 | let new_cap = self.cap(); | |
331 | ||
332 | // Move the shortest contiguous section of the ring buffer | |
333 | // T H | |
334 | // [o o o o o o o . ] | |
335 | // T H | |
336 | // A [o o o o o o o . . . . . . . . . ] | |
337 | // H T | |
338 | // [o o . o o o o o ] | |
339 | // T H | |
340 | // B [. . . o o o o o o o . . . . . . ] | |
341 | // H T | |
342 | // [o o o o o . o o ] | |
343 | // H T | |
344 | // C [o o o o o . . . . . . . . . o o ] | |
345 | ||
92a42be0 SL |
346 | if self.tail <= self.head { |
347 | // A | |
c1a9b12d | 348 | // Nop |
92a42be0 SL |
349 | } else if self.head < old_cap - self.tail { |
350 | // B | |
c1a9b12d SL |
351 | self.copy_nonoverlapping(old_cap, 0, self.head); |
352 | self.head += old_cap; | |
353 | debug_assert!(self.head > self.tail); | |
92a42be0 SL |
354 | } else { |
355 | // C | |
c1a9b12d SL |
356 | let new_tail = new_cap - (old_cap - self.tail); |
357 | self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail); | |
358 | self.tail = new_tail; | |
359 | debug_assert!(self.head < self.tail); | |
360 | } | |
361 | debug_assert!(self.head < self.cap()); | |
362 | debug_assert!(self.tail < self.cap()); | |
363 | debug_assert!(self.cap().count_ones() == 1); | |
364 | } | |
1a4d82fc JJ |
365 | } |
366 | ||
85aaf69f SL |
367 | impl<T> VecDeque<T> { |
368 | /// Creates an empty `VecDeque`. | |
5bcae85e SL |
369 | /// |
370 | /// # Examples | |
371 | /// | |
372 | /// ``` | |
373 | /// use std::collections::VecDeque; | |
374 | /// | |
375 | /// let vector: VecDeque<u32> = VecDeque::new(); | |
376 | /// ``` | |
85aaf69f SL |
377 | #[stable(feature = "rust1", since = "1.0.0")] |
378 | pub fn new() -> VecDeque<T> { | |
379 | VecDeque::with_capacity(INITIAL_CAPACITY) | |
1a4d82fc JJ |
380 | } |
381 | ||
85aaf69f | 382 | /// Creates an empty `VecDeque` with space for at least `n` elements. |
5bcae85e SL |
383 | /// |
384 | /// # Examples | |
385 | /// | |
386 | /// ``` | |
387 | /// use std::collections::VecDeque; | |
388 | /// | |
389 | /// let vector: VecDeque<u32> = VecDeque::with_capacity(10); | |
390 | /// ``` | |
85aaf69f SL |
391 | #[stable(feature = "rust1", since = "1.0.0")] |
392 | pub fn with_capacity(n: usize) -> VecDeque<T> { | |
1a4d82fc JJ |
393 | // +1 since the ringbuffer always leaves one space empty |
394 | let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two(); | |
395 | assert!(cap > n, "capacity overflow"); | |
1a4d82fc | 396 | |
85aaf69f | 397 | VecDeque { |
1a4d82fc JJ |
398 | tail: 0, |
399 | head: 0, | |
c1a9b12d | 400 | buf: RawVec::with_capacity(cap), |
1a4d82fc JJ |
401 | } |
402 | } | |
403 | ||
85aaf69f | 404 | /// Retrieves an element in the `VecDeque` by index. |
1a4d82fc | 405 | /// |
5bcae85e SL |
406 | /// Element at index 0 is the front of the queue. |
407 | /// | |
1a4d82fc JJ |
408 | /// # Examples |
409 | /// | |
c34b1796 | 410 | /// ``` |
85aaf69f | 411 | /// use std::collections::VecDeque; |
1a4d82fc | 412 | /// |
85aaf69f SL |
413 | /// let mut buf = VecDeque::new(); |
414 | /// buf.push_back(3); | |
1a4d82fc JJ |
415 | /// buf.push_back(4); |
416 | /// buf.push_back(5); | |
c1a9b12d | 417 | /// assert_eq!(buf.get(1), Some(&4)); |
1a4d82fc | 418 | /// ``` |
85aaf69f | 419 | #[stable(feature = "rust1", since = "1.0.0")] |
c1a9b12d SL |
420 | pub fn get(&self, index: usize) -> Option<&T> { |
421 | if index < self.len() { | |
422 | let idx = self.wrap_add(self.tail, index); | |
423 | unsafe { Some(&*self.ptr().offset(idx as isize)) } | |
1a4d82fc JJ |
424 | } else { |
425 | None | |
426 | } | |
427 | } | |
428 | ||
85aaf69f | 429 | /// Retrieves an element in the `VecDeque` mutably by index. |
1a4d82fc | 430 | /// |
5bcae85e SL |
431 | /// Element at index 0 is the front of the queue. |
432 | /// | |
1a4d82fc JJ |
433 | /// # Examples |
434 | /// | |
c34b1796 | 435 | /// ``` |
85aaf69f | 436 | /// use std::collections::VecDeque; |
1a4d82fc | 437 | /// |
85aaf69f SL |
438 | /// let mut buf = VecDeque::new(); |
439 | /// buf.push_back(3); | |
1a4d82fc JJ |
440 | /// buf.push_back(4); |
441 | /// buf.push_back(5); | |
9346a6ac AL |
442 | /// if let Some(elem) = buf.get_mut(1) { |
443 | /// *elem = 7; | |
1a4d82fc JJ |
444 | /// } |
445 | /// | |
446 | /// assert_eq!(buf[1], 7); | |
447 | /// ``` | |
85aaf69f | 448 | #[stable(feature = "rust1", since = "1.0.0")] |
c1a9b12d SL |
449 | pub fn get_mut(&mut self, index: usize) -> Option<&mut T> { |
450 | if index < self.len() { | |
451 | let idx = self.wrap_add(self.tail, index); | |
452 | unsafe { Some(&mut *self.ptr().offset(idx as isize)) } | |
1a4d82fc JJ |
453 | } else { |
454 | None | |
455 | } | |
456 | } | |
457 | ||
458 | /// Swaps elements at indices `i` and `j`. | |
459 | /// | |
460 | /// `i` and `j` may be equal. | |
461 | /// | |
462 | /// Fails if there is no element with either index. | |
463 | /// | |
5bcae85e SL |
464 | /// Element at index 0 is the front of the queue. |
465 | /// | |
1a4d82fc JJ |
466 | /// # Examples |
467 | /// | |
c34b1796 | 468 | /// ``` |
85aaf69f | 469 | /// use std::collections::VecDeque; |
1a4d82fc | 470 | /// |
85aaf69f SL |
471 | /// let mut buf = VecDeque::new(); |
472 | /// buf.push_back(3); | |
1a4d82fc JJ |
473 | /// buf.push_back(4); |
474 | /// buf.push_back(5); | |
8bb4bdeb | 475 | /// assert_eq!(buf, [3, 4, 5]); |
1a4d82fc | 476 | /// buf.swap(0, 2); |
8bb4bdeb | 477 | /// assert_eq!(buf, [5, 4, 3]); |
1a4d82fc | 478 | /// ``` |
85aaf69f SL |
479 | #[stable(feature = "rust1", since = "1.0.0")] |
480 | pub fn swap(&mut self, i: usize, j: usize) { | |
1a4d82fc JJ |
481 | assert!(i < self.len()); |
482 | assert!(j < self.len()); | |
c34b1796 AL |
483 | let ri = self.wrap_add(self.tail, i); |
484 | let rj = self.wrap_add(self.tail, j); | |
1a4d82fc | 485 | unsafe { |
92a42be0 SL |
486 | ptr::swap(self.ptr().offset(ri as isize), |
487 | self.ptr().offset(rj as isize)) | |
1a4d82fc JJ |
488 | } |
489 | } | |
490 | ||
85aaf69f | 491 | /// Returns the number of elements the `VecDeque` can hold without |
1a4d82fc JJ |
492 | /// reallocating. |
493 | /// | |
494 | /// # Examples | |
495 | /// | |
496 | /// ``` | |
85aaf69f | 497 | /// use std::collections::VecDeque; |
1a4d82fc | 498 | /// |
85aaf69f | 499 | /// let buf: VecDeque<i32> = VecDeque::with_capacity(10); |
1a4d82fc JJ |
500 | /// assert!(buf.capacity() >= 10); |
501 | /// ``` | |
502 | #[inline] | |
85aaf69f | 503 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
504 | pub fn capacity(&self) -> usize { |
505 | self.cap() - 1 | |
506 | } | |
1a4d82fc JJ |
507 | |
508 | /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the | |
85aaf69f | 509 | /// given `VecDeque`. Does nothing if the capacity is already sufficient. |
1a4d82fc JJ |
510 | /// |
511 | /// Note that the allocator may give the collection more space than it requests. Therefore | |
cc61c64b | 512 | /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future |
1a4d82fc JJ |
513 | /// insertions are expected. |
514 | /// | |
515 | /// # Panics | |
516 | /// | |
85aaf69f | 517 | /// Panics if the new capacity overflows `usize`. |
1a4d82fc JJ |
518 | /// |
519 | /// # Examples | |
520 | /// | |
521 | /// ``` | |
85aaf69f | 522 | /// use std::collections::VecDeque; |
1a4d82fc | 523 | /// |
85aaf69f | 524 | /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect(); |
1a4d82fc JJ |
525 | /// buf.reserve_exact(10); |
526 | /// assert!(buf.capacity() >= 11); | |
527 | /// ``` | |
cc61c64b XL |
528 | /// |
529 | /// [`reserve`]: #method.reserve | |
85aaf69f SL |
530 | #[stable(feature = "rust1", since = "1.0.0")] |
531 | pub fn reserve_exact(&mut self, additional: usize) { | |
1a4d82fc JJ |
532 | self.reserve(additional); |
533 | } | |
534 | ||
535 | /// Reserves capacity for at least `additional` more elements to be inserted in the given | |
c1a9b12d | 536 | /// `VecDeque`. The collection may reserve more space to avoid frequent reallocations. |
1a4d82fc JJ |
537 | /// |
538 | /// # Panics | |
539 | /// | |
85aaf69f | 540 | /// Panics if the new capacity overflows `usize`. |
1a4d82fc JJ |
541 | /// |
542 | /// # Examples | |
543 | /// | |
544 | /// ``` | |
85aaf69f | 545 | /// use std::collections::VecDeque; |
1a4d82fc | 546 | /// |
85aaf69f | 547 | /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect(); |
1a4d82fc JJ |
548 | /// buf.reserve(10); |
549 | /// assert!(buf.capacity() >= 11); | |
550 | /// ``` | |
85aaf69f SL |
551 | #[stable(feature = "rust1", since = "1.0.0")] |
552 | pub fn reserve(&mut self, additional: usize) { | |
c1a9b12d SL |
553 | let old_cap = self.cap(); |
554 | let used_cap = self.len() + 1; | |
92a42be0 | 555 | let new_cap = used_cap.checked_add(additional) |
32a655c1 SL |
556 | .and_then(|needed_cap| needed_cap.checked_next_power_of_two()) |
557 | .expect("capacity overflow"); | |
c1a9b12d SL |
558 | |
559 | if new_cap > self.capacity() { | |
560 | self.buf.reserve_exact(used_cap, new_cap - used_cap); | |
92a42be0 SL |
561 | unsafe { |
562 | self.handle_cap_increase(old_cap); | |
563 | } | |
1a4d82fc JJ |
564 | } |
565 | } | |
566 | ||
c1a9b12d | 567 | /// Shrinks the capacity of the `VecDeque` as much as possible. |
1a4d82fc JJ |
568 | /// |
569 | /// It will drop down as close as possible to the length but the allocator may still inform the | |
c1a9b12d | 570 | /// `VecDeque` that there is space for a few more elements. |
1a4d82fc JJ |
571 | /// |
572 | /// # Examples | |
573 | /// | |
574 | /// ``` | |
85aaf69f | 575 | /// use std::collections::VecDeque; |
1a4d82fc | 576 | /// |
85aaf69f SL |
577 | /// let mut buf = VecDeque::with_capacity(15); |
578 | /// buf.extend(0..4); | |
1a4d82fc JJ |
579 | /// assert_eq!(buf.capacity(), 15); |
580 | /// buf.shrink_to_fit(); | |
581 | /// assert!(buf.capacity() >= 4); | |
582 | /// ``` | |
b039eaaf | 583 | #[stable(feature = "deque_extras_15", since = "1.5.0")] |
1a4d82fc JJ |
584 | pub fn shrink_to_fit(&mut self) { |
585 | // +1 since the ringbuffer always leaves one space empty | |
c1a9b12d | 586 | // len + 1 can't overflow for an existing, well-formed ringbuffer. |
1a4d82fc | 587 | let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two(); |
c1a9b12d | 588 | if target_cap < self.cap() { |
1a4d82fc JJ |
589 | // There are three cases of interest: |
590 | // All elements are out of desired bounds | |
591 | // Elements are contiguous, and head is out of desired bounds | |
592 | // Elements are discontiguous, and tail is out of desired bounds | |
593 | // | |
594 | // At all other times, element positions are unaffected. | |
595 | // | |
596 | // Indicates that elements at the head should be moved. | |
597 | let head_outside = self.head == 0 || self.head >= target_cap; | |
598 | // Move elements from out of desired bounds (positions after target_cap) | |
599 | if self.tail >= target_cap && head_outside { | |
600 | // T H | |
601 | // [. . . . . . . . o o o o o o o . ] | |
602 | // T H | |
603 | // [o o o o o o o . ] | |
604 | unsafe { | |
605 | self.copy_nonoverlapping(0, self.tail, self.len()); | |
606 | } | |
607 | self.head = self.len(); | |
608 | self.tail = 0; | |
609 | } else if self.tail != 0 && self.tail < target_cap && head_outside { | |
610 | // T H | |
611 | // [. . . o o o o o o o . . . . . . ] | |
612 | // H T | |
613 | // [o o . o o o o o ] | |
c34b1796 | 614 | let len = self.wrap_sub(self.head, target_cap); |
1a4d82fc JJ |
615 | unsafe { |
616 | self.copy_nonoverlapping(0, target_cap, len); | |
617 | } | |
618 | self.head = len; | |
619 | debug_assert!(self.head < self.tail); | |
620 | } else if self.tail >= target_cap { | |
621 | // H T | |
622 | // [o o o o o . . . . . . . . . o o ] | |
623 | // H T | |
624 | // [o o o o o . o o ] | |
c34b1796 | 625 | debug_assert!(self.wrap_sub(self.head, 1) < target_cap); |
c1a9b12d | 626 | let len = self.cap() - self.tail; |
1a4d82fc JJ |
627 | let new_tail = target_cap - len; |
628 | unsafe { | |
629 | self.copy_nonoverlapping(new_tail, self.tail, len); | |
630 | } | |
631 | self.tail = new_tail; | |
632 | debug_assert!(self.head < self.tail); | |
633 | } | |
634 | ||
c1a9b12d SL |
635 | self.buf.shrink_to_fit(target_cap); |
636 | ||
637 | debug_assert!(self.head < self.cap()); | |
638 | debug_assert!(self.tail < self.cap()); | |
639 | debug_assert!(self.cap().count_ones() == 1); | |
1a4d82fc JJ |
640 | } |
641 | } | |
642 | ||
cc61c64b | 643 | /// Shortens the `VecDeque`, dropping excess elements from the back. |
1a4d82fc | 644 | /// |
c1a9b12d | 645 | /// If `len` is greater than the `VecDeque`'s current length, this has no |
1a4d82fc JJ |
646 | /// effect. |
647 | /// | |
648 | /// # Examples | |
649 | /// | |
650 | /// ``` | |
85aaf69f | 651 | /// use std::collections::VecDeque; |
1a4d82fc | 652 | /// |
85aaf69f SL |
653 | /// let mut buf = VecDeque::new(); |
654 | /// buf.push_back(5); | |
655 | /// buf.push_back(10); | |
1a4d82fc | 656 | /// buf.push_back(15); |
8bb4bdeb | 657 | /// assert_eq!(buf, [5, 10, 15]); |
1a4d82fc | 658 | /// buf.truncate(1); |
8bb4bdeb | 659 | /// assert_eq!(buf, [5]); |
1a4d82fc | 660 | /// ``` |
32a655c1 | 661 | #[stable(feature = "deque_extras", since = "1.16.0")] |
85aaf69f SL |
662 | pub fn truncate(&mut self, len: usize) { |
663 | for _ in len..self.len() { | |
1a4d82fc JJ |
664 | self.pop_back(); |
665 | } | |
666 | } | |
667 | ||
668 | /// Returns a front-to-back iterator. | |
669 | /// | |
670 | /// # Examples | |
671 | /// | |
c34b1796 | 672 | /// ``` |
85aaf69f | 673 | /// use std::collections::VecDeque; |
1a4d82fc | 674 | /// |
85aaf69f SL |
675 | /// let mut buf = VecDeque::new(); |
676 | /// buf.push_back(5); | |
1a4d82fc JJ |
677 | /// buf.push_back(3); |
678 | /// buf.push_back(4); | |
679 | /// let b: &[_] = &[&5, &3, &4]; | |
c34b1796 AL |
680 | /// let c: Vec<&i32> = buf.iter().collect(); |
681 | /// assert_eq!(&c[..], b); | |
1a4d82fc | 682 | /// ``` |
85aaf69f | 683 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
684 | pub fn iter(&self) -> Iter<T> { |
685 | Iter { | |
686 | tail: self.tail, | |
687 | head: self.head, | |
92a42be0 | 688 | ring: unsafe { self.buffer_as_slice() }, |
1a4d82fc JJ |
689 | } |
690 | } | |
691 | ||
692 | /// Returns a front-to-back iterator that returns mutable references. | |
693 | /// | |
694 | /// # Examples | |
695 | /// | |
c34b1796 | 696 | /// ``` |
85aaf69f | 697 | /// use std::collections::VecDeque; |
1a4d82fc | 698 | /// |
85aaf69f SL |
699 | /// let mut buf = VecDeque::new(); |
700 | /// buf.push_back(5); | |
1a4d82fc JJ |
701 | /// buf.push_back(3); |
702 | /// buf.push_back(4); | |
703 | /// for num in buf.iter_mut() { | |
704 | /// *num = *num - 2; | |
705 | /// } | |
706 | /// let b: &[_] = &[&mut 3, &mut 1, &mut 2]; | |
c34b1796 | 707 | /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b); |
1a4d82fc | 708 | /// ``` |
85aaf69f SL |
709 | #[stable(feature = "rust1", since = "1.0.0")] |
710 | pub fn iter_mut(&mut self) -> IterMut<T> { | |
1a4d82fc JJ |
711 | IterMut { |
712 | tail: self.tail, | |
713 | head: self.head, | |
c34b1796 | 714 | ring: unsafe { self.buffer_as_mut_slice() }, |
1a4d82fc JJ |
715 | } |
716 | } | |
717 | ||
1a4d82fc | 718 | /// Returns a pair of slices which contain, in order, the contents of the |
85aaf69f | 719 | /// `VecDeque`. |
5bcae85e SL |
720 | /// |
721 | /// # Examples | |
722 | /// | |
723 | /// ``` | |
724 | /// use std::collections::VecDeque; | |
725 | /// | |
9e0c209e | 726 | /// let mut vector = VecDeque::new(); |
5bcae85e SL |
727 | /// |
728 | /// vector.push_back(0); | |
729 | /// vector.push_back(1); | |
730 | /// vector.push_back(2); | |
731 | /// | |
9e0c209e | 732 | /// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..])); |
5bcae85e SL |
733 | /// |
734 | /// vector.push_front(10); | |
735 | /// vector.push_front(9); | |
736 | /// | |
9e0c209e | 737 | /// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..])); |
5bcae85e | 738 | /// ``` |
1a4d82fc | 739 | #[inline] |
b039eaaf | 740 | #[stable(feature = "deque_extras_15", since = "1.5.0")] |
85aaf69f | 741 | pub fn as_slices(&self) -> (&[T], &[T]) { |
1a4d82fc | 742 | unsafe { |
1a4d82fc | 743 | let buf = self.buffer_as_slice(); |
c30ab7b3 | 744 | RingSlices::ring_slices(buf, self.head, self.tail) |
1a4d82fc JJ |
745 | } |
746 | } | |
747 | ||
748 | /// Returns a pair of slices which contain, in order, the contents of the | |
85aaf69f | 749 | /// `VecDeque`. |
5bcae85e SL |
750 | /// |
751 | /// # Examples | |
752 | /// | |
753 | /// ``` | |
754 | /// use std::collections::VecDeque; | |
755 | /// | |
9e0c209e | 756 | /// let mut vector = VecDeque::new(); |
5bcae85e SL |
757 | /// |
758 | /// vector.push_back(0); | |
759 | /// vector.push_back(1); | |
760 | /// | |
761 | /// vector.push_front(10); | |
762 | /// vector.push_front(9); | |
763 | /// | |
764 | /// vector.as_mut_slices().0[0] = 42; | |
765 | /// vector.as_mut_slices().1[0] = 24; | |
9e0c209e | 766 | /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..])); |
5bcae85e | 767 | /// ``` |
1a4d82fc | 768 | #[inline] |
b039eaaf | 769 | #[stable(feature = "deque_extras_15", since = "1.5.0")] |
85aaf69f | 770 | pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) { |
1a4d82fc | 771 | unsafe { |
1a4d82fc JJ |
772 | let head = self.head; |
773 | let tail = self.tail; | |
774 | let buf = self.buffer_as_mut_slice(); | |
c30ab7b3 | 775 | RingSlices::ring_slices(buf, head, tail) |
1a4d82fc JJ |
776 | } |
777 | } | |
778 | ||
85aaf69f | 779 | /// Returns the number of elements in the `VecDeque`. |
1a4d82fc JJ |
780 | /// |
781 | /// # Examples | |
782 | /// | |
783 | /// ``` | |
85aaf69f | 784 | /// use std::collections::VecDeque; |
1a4d82fc | 785 | /// |
85aaf69f | 786 | /// let mut v = VecDeque::new(); |
1a4d82fc | 787 | /// assert_eq!(v.len(), 0); |
85aaf69f | 788 | /// v.push_back(1); |
1a4d82fc JJ |
789 | /// assert_eq!(v.len(), 1); |
790 | /// ``` | |
85aaf69f | 791 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
792 | pub fn len(&self) -> usize { |
793 | count(self.tail, self.head, self.cap()) | |
794 | } | |
1a4d82fc | 795 | |
cc61c64b | 796 | /// Returns `true` if the `VecDeque` is empty. |
1a4d82fc JJ |
797 | /// |
798 | /// # Examples | |
799 | /// | |
800 | /// ``` | |
85aaf69f | 801 | /// use std::collections::VecDeque; |
1a4d82fc | 802 | /// |
85aaf69f | 803 | /// let mut v = VecDeque::new(); |
1a4d82fc | 804 | /// assert!(v.is_empty()); |
85aaf69f | 805 | /// v.push_front(1); |
1a4d82fc JJ |
806 | /// assert!(!v.is_empty()); |
807 | /// ``` | |
85aaf69f | 808 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 809 | pub fn is_empty(&self) -> bool { |
476ff2be | 810 | self.tail == self.head |
92a42be0 | 811 | } |
1a4d82fc | 812 | |
b039eaaf | 813 | /// Create a draining iterator that removes the specified range in the |
9cc50fc6 | 814 | /// `VecDeque` and yields the removed items. |
b039eaaf | 815 | /// |
9cc50fc6 SL |
816 | /// Note 1: The element range is removed even if the iterator is not |
817 | /// consumed until the end. | |
818 | /// | |
819 | /// Note 2: It is unspecified how many elements are removed from the deque, | |
b039eaaf SL |
820 | /// if the `Drain` value is not dropped, but the borrow it holds expires |
821 | /// (eg. due to mem::forget). | |
822 | /// | |
823 | /// # Panics | |
824 | /// | |
825 | /// Panics if the starting point is greater than the end point or if | |
826 | /// the end point is greater than the length of the vector. | |
1a4d82fc JJ |
827 | /// |
828 | /// # Examples | |
829 | /// | |
830 | /// ``` | |
85aaf69f | 831 | /// use std::collections::VecDeque; |
5bcae85e | 832 | /// |
9cc50fc6 | 833 | /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect(); |
8bb4bdeb XL |
834 | /// let drained = v.drain(2..).collect::<VecDeque<_>>(); |
835 | /// assert_eq!(drained, [3]); | |
836 | /// assert_eq!(v, [1, 2]); | |
1a4d82fc | 837 | /// |
9cc50fc6 SL |
838 | /// // A full range clears all contents |
839 | /// v.drain(..); | |
1a4d82fc JJ |
840 | /// assert!(v.is_empty()); |
841 | /// ``` | |
842 | #[inline] | |
92a42be0 SL |
843 | #[stable(feature = "drain", since = "1.6.0")] |
844 | pub fn drain<R>(&mut self, range: R) -> Drain<T> | |
845 | where R: RangeArgument<usize> | |
846 | { | |
b039eaaf SL |
847 | // Memory safety |
848 | // | |
849 | // When the Drain is first created, the source deque is shortened to | |
850 | // make sure no uninitialized or moved-from elements are accessible at | |
851 | // all if the Drain's destructor never gets to run. | |
852 | // | |
853 | // Drain will ptr::read out the values to remove. | |
854 | // When finished, the remaining data will be copied back to cover the hole, | |
855 | // and the head/tail values will be restored correctly. | |
856 | // | |
857 | let len = self.len(); | |
32a655c1 SL |
858 | let start = match range.start() { |
859 | Included(&n) => n, | |
860 | Excluded(&n) => n + 1, | |
861 | Unbounded => 0, | |
862 | }; | |
863 | let end = match range.end() { | |
864 | Included(&n) => n + 1, | |
865 | Excluded(&n) => n, | |
866 | Unbounded => len, | |
867 | }; | |
b039eaaf SL |
868 | assert!(start <= end, "drain lower bound was too large"); |
869 | assert!(end <= len, "drain upper bound was too large"); | |
870 | ||
871 | // The deque's elements are parted into three segments: | |
872 | // * self.tail -> drain_tail | |
873 | // * drain_tail -> drain_head | |
874 | // * drain_head -> self.head | |
875 | // | |
876 | // T = self.tail; H = self.head; t = drain_tail; h = drain_head | |
877 | // | |
878 | // We store drain_tail as self.head, and drain_head and self.head as | |
879 | // after_tail and after_head respectively on the Drain. This also | |
880 | // truncates the effective array such that if the Drain is leaked, we | |
881 | // have forgotten about the potentially moved values after the start of | |
882 | // the drain. | |
883 | // | |
884 | // T t h H | |
885 | // [. . . o o x x o o . . .] | |
886 | // | |
887 | let drain_tail = self.wrap_add(self.tail, start); | |
888 | let drain_head = self.wrap_add(self.tail, end); | |
889 | let head = self.head; | |
890 | ||
891 | // "forget" about the values after the start of the drain until after | |
892 | // the drain is complete and the Drain destructor is run. | |
893 | self.head = drain_tail; | |
894 | ||
1a4d82fc | 895 | Drain { |
9e0c209e | 896 | deque: unsafe { Shared::new(self as *mut _) }, |
b039eaaf SL |
897 | after_tail: drain_head, |
898 | after_head: head, | |
899 | iter: Iter { | |
900 | tail: drain_tail, | |
901 | head: drain_head, | |
902 | ring: unsafe { self.buffer_as_mut_slice() }, | |
903 | }, | |
1a4d82fc JJ |
904 | } |
905 | } | |
906 | ||
907 | /// Clears the buffer, removing all values. | |
908 | /// | |
909 | /// # Examples | |
910 | /// | |
911 | /// ``` | |
85aaf69f | 912 | /// use std::collections::VecDeque; |
1a4d82fc | 913 | /// |
85aaf69f SL |
914 | /// let mut v = VecDeque::new(); |
915 | /// v.push_back(1); | |
1a4d82fc JJ |
916 | /// v.clear(); |
917 | /// assert!(v.is_empty()); | |
918 | /// ``` | |
85aaf69f | 919 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
920 | #[inline] |
921 | pub fn clear(&mut self) { | |
b039eaaf | 922 | self.drain(..); |
1a4d82fc JJ |
923 | } |
924 | ||
a7813a04 XL |
925 | /// Returns `true` if the `VecDeque` contains an element equal to the |
926 | /// given value. | |
5bcae85e SL |
927 | /// |
928 | /// # Examples | |
929 | /// | |
930 | /// ``` | |
931 | /// use std::collections::VecDeque; | |
932 | /// | |
933 | /// let mut vector: VecDeque<u32> = VecDeque::new(); | |
934 | /// | |
935 | /// vector.push_back(0); | |
936 | /// vector.push_back(1); | |
937 | /// | |
938 | /// assert_eq!(vector.contains(&1), true); | |
939 | /// assert_eq!(vector.contains(&10), false); | |
940 | /// ``` | |
941 | #[stable(feature = "vec_deque_contains", since = "1.12.0")] | |
a7813a04 XL |
942 | pub fn contains(&self, x: &T) -> bool |
943 | where T: PartialEq<T> | |
944 | { | |
945 | let (a, b) = self.as_slices(); | |
946 | a.contains(x) || b.contains(x) | |
947 | } | |
948 | ||
cc61c64b | 949 | /// Provides a reference to the front element, or `None` if the `VecDeque` is |
1a4d82fc JJ |
950 | /// empty. |
951 | /// | |
952 | /// # Examples | |
953 | /// | |
954 | /// ``` | |
85aaf69f | 955 | /// use std::collections::VecDeque; |
1a4d82fc | 956 | /// |
85aaf69f | 957 | /// let mut d = VecDeque::new(); |
1a4d82fc JJ |
958 | /// assert_eq!(d.front(), None); |
959 | /// | |
85aaf69f SL |
960 | /// d.push_back(1); |
961 | /// d.push_back(2); | |
962 | /// assert_eq!(d.front(), Some(&1)); | |
1a4d82fc | 963 | /// ``` |
85aaf69f | 964 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 965 | pub fn front(&self) -> Option<&T> { |
92a42be0 SL |
966 | if !self.is_empty() { |
967 | Some(&self[0]) | |
968 | } else { | |
969 | None | |
970 | } | |
1a4d82fc JJ |
971 | } |
972 | ||
973 | /// Provides a mutable reference to the front element, or `None` if the | |
cc61c64b | 974 | /// `VecDeque` is empty. |
1a4d82fc JJ |
975 | /// |
976 | /// # Examples | |
977 | /// | |
978 | /// ``` | |
85aaf69f | 979 | /// use std::collections::VecDeque; |
1a4d82fc | 980 | /// |
85aaf69f | 981 | /// let mut d = VecDeque::new(); |
1a4d82fc JJ |
982 | /// assert_eq!(d.front_mut(), None); |
983 | /// | |
85aaf69f SL |
984 | /// d.push_back(1); |
985 | /// d.push_back(2); | |
1a4d82fc | 986 | /// match d.front_mut() { |
85aaf69f | 987 | /// Some(x) => *x = 9, |
1a4d82fc JJ |
988 | /// None => (), |
989 | /// } | |
85aaf69f | 990 | /// assert_eq!(d.front(), Some(&9)); |
1a4d82fc | 991 | /// ``` |
85aaf69f | 992 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 993 | pub fn front_mut(&mut self) -> Option<&mut T> { |
92a42be0 SL |
994 | if !self.is_empty() { |
995 | Some(&mut self[0]) | |
996 | } else { | |
997 | None | |
998 | } | |
1a4d82fc JJ |
999 | } |
1000 | ||
cc61c64b | 1001 | /// Provides a reference to the back element, or `None` if the `VecDeque` is |
1a4d82fc JJ |
1002 | /// empty. |
1003 | /// | |
1004 | /// # Examples | |
1005 | /// | |
1006 | /// ``` | |
85aaf69f | 1007 | /// use std::collections::VecDeque; |
1a4d82fc | 1008 | /// |
85aaf69f | 1009 | /// let mut d = VecDeque::new(); |
1a4d82fc JJ |
1010 | /// assert_eq!(d.back(), None); |
1011 | /// | |
85aaf69f SL |
1012 | /// d.push_back(1); |
1013 | /// d.push_back(2); | |
1014 | /// assert_eq!(d.back(), Some(&2)); | |
1a4d82fc | 1015 | /// ``` |
85aaf69f | 1016 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1017 | pub fn back(&self) -> Option<&T> { |
92a42be0 SL |
1018 | if !self.is_empty() { |
1019 | Some(&self[self.len() - 1]) | |
1020 | } else { | |
1021 | None | |
1022 | } | |
1a4d82fc JJ |
1023 | } |
1024 | ||
1025 | /// Provides a mutable reference to the back element, or `None` if the | |
cc61c64b | 1026 | /// `VecDeque` is empty. |
1a4d82fc JJ |
1027 | /// |
1028 | /// # Examples | |
1029 | /// | |
1030 | /// ``` | |
85aaf69f | 1031 | /// use std::collections::VecDeque; |
1a4d82fc | 1032 | /// |
85aaf69f | 1033 | /// let mut d = VecDeque::new(); |
1a4d82fc JJ |
1034 | /// assert_eq!(d.back(), None); |
1035 | /// | |
85aaf69f SL |
1036 | /// d.push_back(1); |
1037 | /// d.push_back(2); | |
1a4d82fc | 1038 | /// match d.back_mut() { |
85aaf69f | 1039 | /// Some(x) => *x = 9, |
1a4d82fc JJ |
1040 | /// None => (), |
1041 | /// } | |
85aaf69f | 1042 | /// assert_eq!(d.back(), Some(&9)); |
1a4d82fc | 1043 | /// ``` |
85aaf69f | 1044 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1045 | pub fn back_mut(&mut self) -> Option<&mut T> { |
1046 | let len = self.len(); | |
92a42be0 SL |
1047 | if !self.is_empty() { |
1048 | Some(&mut self[len - 1]) | |
1049 | } else { | |
1050 | None | |
1051 | } | |
1a4d82fc JJ |
1052 | } |
1053 | ||
cc61c64b | 1054 | /// Removes the first element and returns it, or `None` if the `VecDeque` is |
1a4d82fc JJ |
1055 | /// empty. |
1056 | /// | |
1057 | /// # Examples | |
1058 | /// | |
1059 | /// ``` | |
85aaf69f | 1060 | /// use std::collections::VecDeque; |
1a4d82fc | 1061 | /// |
85aaf69f SL |
1062 | /// let mut d = VecDeque::new(); |
1063 | /// d.push_back(1); | |
1064 | /// d.push_back(2); | |
1a4d82fc | 1065 | /// |
85aaf69f SL |
1066 | /// assert_eq!(d.pop_front(), Some(1)); |
1067 | /// assert_eq!(d.pop_front(), Some(2)); | |
1a4d82fc JJ |
1068 | /// assert_eq!(d.pop_front(), None); |
1069 | /// ``` | |
85aaf69f | 1070 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1071 | pub fn pop_front(&mut self) -> Option<T> { |
1072 | if self.is_empty() { | |
1073 | None | |
1074 | } else { | |
1075 | let tail = self.tail; | |
c34b1796 | 1076 | self.tail = self.wrap_add(self.tail, 1); |
1a4d82fc JJ |
1077 | unsafe { Some(self.buffer_read(tail)) } |
1078 | } | |
1079 | } | |
1080 | ||
cc61c64b | 1081 | /// Prepends an element to the `VecDeque`. |
1a4d82fc JJ |
1082 | /// |
1083 | /// # Examples | |
1084 | /// | |
1085 | /// ``` | |
85aaf69f | 1086 | /// use std::collections::VecDeque; |
1a4d82fc | 1087 | /// |
85aaf69f SL |
1088 | /// let mut d = VecDeque::new(); |
1089 | /// d.push_front(1); | |
1090 | /// d.push_front(2); | |
1091 | /// assert_eq!(d.front(), Some(&2)); | |
1a4d82fc | 1092 | /// ``` |
85aaf69f | 1093 | #[stable(feature = "rust1", since = "1.0.0")] |
c1a9b12d | 1094 | pub fn push_front(&mut self, value: T) { |
8bb4bdeb | 1095 | self.grow_if_necessary(); |
1a4d82fc | 1096 | |
c34b1796 | 1097 | self.tail = self.wrap_sub(self.tail, 1); |
1a4d82fc | 1098 | let tail = self.tail; |
92a42be0 SL |
1099 | unsafe { |
1100 | self.buffer_write(tail, value); | |
1101 | } | |
1a4d82fc JJ |
1102 | } |
1103 | ||
cc61c64b | 1104 | /// Appends an element to the back of the `VecDeque`. |
1a4d82fc JJ |
1105 | /// |
1106 | /// # Examples | |
1107 | /// | |
c34b1796 | 1108 | /// ``` |
85aaf69f | 1109 | /// use std::collections::VecDeque; |
1a4d82fc | 1110 | /// |
85aaf69f SL |
1111 | /// let mut buf = VecDeque::new(); |
1112 | /// buf.push_back(1); | |
1a4d82fc JJ |
1113 | /// buf.push_back(3); |
1114 | /// assert_eq!(3, *buf.back().unwrap()); | |
1115 | /// ``` | |
85aaf69f | 1116 | #[stable(feature = "rust1", since = "1.0.0")] |
c1a9b12d | 1117 | pub fn push_back(&mut self, value: T) { |
8bb4bdeb | 1118 | self.grow_if_necessary(); |
1a4d82fc JJ |
1119 | |
1120 | let head = self.head; | |
c34b1796 | 1121 | self.head = self.wrap_add(self.head, 1); |
c1a9b12d | 1122 | unsafe { self.buffer_write(head, value) } |
1a4d82fc JJ |
1123 | } |
1124 | ||
cc61c64b | 1125 | /// Removes the last element from the `VecDeque` and returns it, or `None` if |
1a4d82fc JJ |
1126 | /// it is empty. |
1127 | /// | |
1128 | /// # Examples | |
1129 | /// | |
c34b1796 | 1130 | /// ``` |
85aaf69f | 1131 | /// use std::collections::VecDeque; |
1a4d82fc | 1132 | /// |
85aaf69f | 1133 | /// let mut buf = VecDeque::new(); |
1a4d82fc | 1134 | /// assert_eq!(buf.pop_back(), None); |
85aaf69f | 1135 | /// buf.push_back(1); |
1a4d82fc JJ |
1136 | /// buf.push_back(3); |
1137 | /// assert_eq!(buf.pop_back(), Some(3)); | |
1138 | /// ``` | |
85aaf69f | 1139 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1140 | pub fn pop_back(&mut self) -> Option<T> { |
1141 | if self.is_empty() { | |
1142 | None | |
1143 | } else { | |
c34b1796 | 1144 | self.head = self.wrap_sub(self.head, 1); |
1a4d82fc JJ |
1145 | let head = self.head; |
1146 | unsafe { Some(self.buffer_read(head)) } | |
1147 | } | |
1148 | } | |
1149 | ||
1150 | #[inline] | |
1151 | fn is_contiguous(&self) -> bool { | |
1152 | self.tail <= self.head | |
1153 | } | |
1154 | ||
c1a9b12d SL |
1155 | /// Removes an element from anywhere in the `VecDeque` and returns it, replacing it with the |
1156 | /// last element. | |
1a4d82fc JJ |
1157 | /// |
1158 | /// This does not preserve ordering, but is O(1). | |
1159 | /// | |
1160 | /// Returns `None` if `index` is out of bounds. | |
1161 | /// | |
5bcae85e SL |
1162 | /// Element at index 0 is the front of the queue. |
1163 | /// | |
1a4d82fc JJ |
1164 | /// # Examples |
1165 | /// | |
1166 | /// ``` | |
85aaf69f | 1167 | /// use std::collections::VecDeque; |
1a4d82fc | 1168 | /// |
85aaf69f | 1169 | /// let mut buf = VecDeque::new(); |
b039eaaf | 1170 | /// assert_eq!(buf.swap_remove_back(0), None); |
c1a9b12d SL |
1171 | /// buf.push_back(1); |
1172 | /// buf.push_back(2); | |
1173 | /// buf.push_back(3); | |
8bb4bdeb | 1174 | /// assert_eq!(buf, [1, 2, 3]); |
c1a9b12d | 1175 | /// |
b039eaaf | 1176 | /// assert_eq!(buf.swap_remove_back(0), Some(1)); |
8bb4bdeb | 1177 | /// assert_eq!(buf, [3, 2]); |
1a4d82fc | 1178 | /// ``` |
b039eaaf SL |
1179 | #[stable(feature = "deque_extras_15", since = "1.5.0")] |
1180 | pub fn swap_remove_back(&mut self, index: usize) -> Option<T> { | |
1a4d82fc JJ |
1181 | let length = self.len(); |
1182 | if length > 0 && index < length - 1 { | |
1183 | self.swap(index, length - 1); | |
1184 | } else if index >= length { | |
1185 | return None; | |
1186 | } | |
1187 | self.pop_back() | |
1188 | } | |
1189 | ||
c1a9b12d | 1190 | /// Removes an element from anywhere in the `VecDeque` and returns it, |
62682a34 | 1191 | /// replacing it with the first element. |
1a4d82fc JJ |
1192 | /// |
1193 | /// This does not preserve ordering, but is O(1). | |
1194 | /// | |
1195 | /// Returns `None` if `index` is out of bounds. | |
1196 | /// | |
5bcae85e SL |
1197 | /// Element at index 0 is the front of the queue. |
1198 | /// | |
1a4d82fc JJ |
1199 | /// # Examples |
1200 | /// | |
1201 | /// ``` | |
85aaf69f | 1202 | /// use std::collections::VecDeque; |
1a4d82fc | 1203 | /// |
85aaf69f | 1204 | /// let mut buf = VecDeque::new(); |
b039eaaf | 1205 | /// assert_eq!(buf.swap_remove_front(0), None); |
c1a9b12d SL |
1206 | /// buf.push_back(1); |
1207 | /// buf.push_back(2); | |
1208 | /// buf.push_back(3); | |
8bb4bdeb | 1209 | /// assert_eq!(buf, [1, 2, 3]); |
c1a9b12d | 1210 | /// |
b039eaaf | 1211 | /// assert_eq!(buf.swap_remove_front(2), Some(3)); |
8bb4bdeb | 1212 | /// assert_eq!(buf, [2, 1]); |
1a4d82fc | 1213 | /// ``` |
b039eaaf SL |
1214 | #[stable(feature = "deque_extras_15", since = "1.5.0")] |
1215 | pub fn swap_remove_front(&mut self, index: usize) -> Option<T> { | |
1a4d82fc JJ |
1216 | let length = self.len(); |
1217 | if length > 0 && index < length && index != 0 { | |
1218 | self.swap(index, 0); | |
1219 | } else if index >= length { | |
1220 | return None; | |
1221 | } | |
1222 | self.pop_front() | |
1223 | } | |
1224 | ||
32a655c1 SL |
1225 | /// Inserts an element at `index` within the `VecDeque`, shifting all elements with indices |
1226 | /// greater than or equal to `index` towards the back. | |
1a4d82fc | 1227 | /// |
5bcae85e SL |
1228 | /// Element at index 0 is the front of the queue. |
1229 | /// | |
1a4d82fc JJ |
1230 | /// # Panics |
1231 | /// | |
c1a9b12d | 1232 | /// Panics if `index` is greater than `VecDeque`'s length |
1a4d82fc JJ |
1233 | /// |
1234 | /// # Examples | |
32a655c1 | 1235 | /// |
c34b1796 | 1236 | /// ``` |
85aaf69f | 1237 | /// use std::collections::VecDeque; |
1a4d82fc | 1238 | /// |
32a655c1 SL |
1239 | /// let mut vec_deque = VecDeque::new(); |
1240 | /// vec_deque.push_back('a'); | |
1241 | /// vec_deque.push_back('b'); | |
1242 | /// vec_deque.push_back('c'); | |
8bb4bdeb | 1243 | /// assert_eq!(vec_deque, &['a', 'b', 'c']); |
32a655c1 SL |
1244 | /// |
1245 | /// vec_deque.insert(1, 'd'); | |
8bb4bdeb | 1246 | /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']); |
1a4d82fc | 1247 | /// ``` |
b039eaaf | 1248 | #[stable(feature = "deque_extras_15", since = "1.5.0")] |
c1a9b12d SL |
1249 | pub fn insert(&mut self, index: usize, value: T) { |
1250 | assert!(index <= self.len(), "index out of bounds"); | |
8bb4bdeb | 1251 | self.grow_if_necessary(); |
1a4d82fc JJ |
1252 | |
1253 | // Move the least number of elements in the ring buffer and insert | |
1254 | // the given object | |
1255 | // | |
1256 | // At most len/2 - 1 elements will be moved. O(min(n, n-i)) | |
1257 | // | |
1258 | // There are three main cases: | |
1259 | // Elements are contiguous | |
1260 | // - special case when tail is 0 | |
1261 | // Elements are discontiguous and the insert is in the tail section | |
1262 | // Elements are discontiguous and the insert is in the head section | |
1263 | // | |
1264 | // For each of those there are two more cases: | |
1265 | // Insert is closer to tail | |
1266 | // Insert is closer to head | |
1267 | // | |
1268 | // Key: H - self.head | |
1269 | // T - self.tail | |
1270 | // o - Valid element | |
1271 | // I - Insertion element | |
1272 | // A - The element that should be after the insertion point | |
1273 | // M - Indicates element was moved | |
1274 | ||
c1a9b12d | 1275 | let idx = self.wrap_add(self.tail, index); |
1a4d82fc | 1276 | |
c1a9b12d SL |
1277 | let distance_to_tail = index; |
1278 | let distance_to_head = self.len() - index; | |
1a4d82fc JJ |
1279 | |
1280 | let contiguous = self.is_contiguous(); | |
1281 | ||
32a655c1 | 1282 | match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) { |
c1a9b12d | 1283 | (true, true, _) if index == 0 => { |
1a4d82fc JJ |
1284 | // push_front |
1285 | // | |
1286 | // T | |
1287 | // I H | |
1288 | // [A o o o o o o . . . . . . . . .] | |
1289 | // | |
1290 | // H T | |
1291 | // [A o o o o o o o . . . . . I] | |
1292 | // | |
1293 | ||
c34b1796 | 1294 | self.tail = self.wrap_sub(self.tail, 1); |
92a42be0 SL |
1295 | } |
1296 | (true, true, _) => { | |
1297 | unsafe { | |
1298 | // contiguous, insert closer to tail: | |
1299 | // | |
1300 | // T I H | |
1301 | // [. . . o o A o o o o . . . . . .] | |
1302 | // | |
1303 | // T H | |
1304 | // [. . o o I A o o o o . . . . . .] | |
1305 | // M M | |
1306 | // | |
1307 | // contiguous, insert closer to tail and tail is 0: | |
1308 | // | |
1309 | // | |
1310 | // T I H | |
1311 | // [o o A o o o o . . . . . . . . .] | |
1312 | // | |
1313 | // H T | |
1314 | // [o I A o o o o o . . . . . . . o] | |
1315 | // M M | |
1316 | ||
1317 | let new_tail = self.wrap_sub(self.tail, 1); | |
1318 | ||
1319 | self.copy(new_tail, self.tail, 1); | |
1320 | // Already moved the tail, so we only copy `index - 1` elements. | |
1321 | self.copy(self.tail, self.tail + 1, index - 1); | |
1322 | ||
1323 | self.tail = new_tail; | |
1324 | } | |
1325 | } | |
1326 | (true, false, _) => { | |
1327 | unsafe { | |
1328 | // contiguous, insert closer to head: | |
1329 | // | |
1330 | // T I H | |
1331 | // [. . . o o o o A o o . . . . . .] | |
1332 | // | |
1333 | // T H | |
1334 | // [. . . o o o o I A o o . . . . .] | |
1335 | // M M M | |
1336 | ||
1337 | self.copy(idx + 1, idx, self.head - idx); | |
1338 | self.head = self.wrap_add(self.head, 1); | |
1339 | } | |
1340 | } | |
1341 | (false, true, true) => { | |
1342 | unsafe { | |
1343 | // discontiguous, insert closer to tail, tail section: | |
1344 | // | |
1345 | // H T I | |
1346 | // [o o o o o o . . . . . o o A o o] | |
1347 | // | |
1348 | // H T | |
1349 | // [o o o o o o . . . . o o I A o o] | |
1350 | // M M | |
1351 | ||
1352 | self.copy(self.tail - 1, self.tail, index); | |
1353 | self.tail -= 1; | |
1354 | } | |
1355 | } | |
1356 | (false, false, true) => { | |
1357 | unsafe { | |
1358 | // discontiguous, insert closer to head, tail section: | |
1359 | // | |
1360 | // H T I | |
1361 | // [o o . . . . . . . o o o o o A o] | |
1362 | // | |
1363 | // H T | |
1364 | // [o o o . . . . . . o o o o o I A] | |
1365 | // M M M M | |
1a4d82fc | 1366 | |
92a42be0 SL |
1367 | // copy elements up to new head |
1368 | self.copy(1, 0, self.head); | |
1a4d82fc | 1369 | |
92a42be0 SL |
1370 | // copy last element into empty spot at bottom of buffer |
1371 | self.copy(0, self.cap() - 1, 1); | |
1a4d82fc | 1372 | |
92a42be0 SL |
1373 | // move elements from idx to end forward not including ^ element |
1374 | self.copy(idx + 1, idx, self.cap() - 1 - idx); | |
1a4d82fc | 1375 | |
92a42be0 SL |
1376 | self.head += 1; |
1377 | } | |
1378 | } | |
1379 | (false, true, false) if idx == 0 => { | |
1380 | unsafe { | |
1381 | // discontiguous, insert is closer to tail, head section, | |
1382 | // and is at index zero in the internal buffer: | |
1383 | // | |
1384 | // I H T | |
1385 | // [A o o o o o o o o o . . . o o o] | |
1386 | // | |
1387 | // H T | |
1388 | // [A o o o o o o o o o . . o o o I] | |
1389 | // M M M | |
1390 | ||
1391 | // copy elements up to new tail | |
1392 | self.copy(self.tail - 1, self.tail, self.cap() - self.tail); | |
1393 | ||
1394 | // copy last element into empty spot at bottom of buffer | |
1395 | self.copy(self.cap() - 1, 0, 1); | |
1a4d82fc | 1396 | |
92a42be0 SL |
1397 | self.tail -= 1; |
1398 | } | |
1399 | } | |
1400 | (false, true, false) => { | |
1401 | unsafe { | |
1402 | // discontiguous, insert closer to tail, head section: | |
1403 | // | |
1404 | // I H T | |
1405 | // [o o o A o o o o o o . . . o o o] | |
1406 | // | |
1407 | // H T | |
1408 | // [o o I A o o o o o o . . o o o o] | |
1409 | // M M M M M M | |
1410 | ||
1411 | // copy elements up to new tail | |
1412 | self.copy(self.tail - 1, self.tail, self.cap() - self.tail); | |
1413 | ||
1414 | // copy last element into empty spot at bottom of buffer | |
1415 | self.copy(self.cap() - 1, 0, 1); | |
1a4d82fc | 1416 | |
92a42be0 SL |
1417 | // move elements from idx-1 to end forward not including ^ element |
1418 | self.copy(0, 1, idx - 1); | |
1a4d82fc | 1419 | |
92a42be0 SL |
1420 | self.tail -= 1; |
1421 | } | |
1422 | } | |
1423 | (false, false, false) => { | |
1424 | unsafe { | |
1425 | // discontiguous, insert closer to head, head section: | |
1426 | // | |
1427 | // I H T | |
1428 | // [o o o o A o o . . . . . . o o o] | |
1429 | // | |
1430 | // H T | |
1431 | // [o o o o I A o o . . . . . o o o] | |
1432 | // M M M | |
1433 | ||
1434 | self.copy(idx + 1, idx, self.head - idx); | |
1435 | self.head += 1; | |
1436 | } | |
1a4d82fc JJ |
1437 | } |
1438 | } | |
1439 | ||
1440 | // tail might've been changed so we need to recalculate | |
c1a9b12d | 1441 | let new_idx = self.wrap_add(self.tail, index); |
1a4d82fc | 1442 | unsafe { |
c1a9b12d | 1443 | self.buffer_write(new_idx, value); |
1a4d82fc JJ |
1444 | } |
1445 | } | |
1446 | ||
c1a9b12d | 1447 | /// Removes and returns the element at `index` from the `VecDeque`. |
1a4d82fc JJ |
1448 | /// Whichever end is closer to the removal point will be moved to make |
1449 | /// room, and all the affected elements will be moved to new positions. | |
c1a9b12d | 1450 | /// Returns `None` if `index` is out of bounds. |
1a4d82fc | 1451 | /// |
5bcae85e SL |
1452 | /// Element at index 0 is the front of the queue. |
1453 | /// | |
1a4d82fc | 1454 | /// # Examples |
5bcae85e | 1455 | /// |
c34b1796 | 1456 | /// ``` |
85aaf69f | 1457 | /// use std::collections::VecDeque; |
1a4d82fc | 1458 | /// |
85aaf69f | 1459 | /// let mut buf = VecDeque::new(); |
c1a9b12d SL |
1460 | /// buf.push_back(1); |
1461 | /// buf.push_back(2); | |
1462 | /// buf.push_back(3); | |
8bb4bdeb | 1463 | /// assert_eq!(buf, [1, 2, 3]); |
c1a9b12d SL |
1464 | /// |
1465 | /// assert_eq!(buf.remove(1), Some(2)); | |
8bb4bdeb | 1466 | /// assert_eq!(buf, [1, 3]); |
1a4d82fc | 1467 | /// ``` |
85aaf69f | 1468 | #[stable(feature = "rust1", since = "1.0.0")] |
c1a9b12d SL |
1469 | pub fn remove(&mut self, index: usize) -> Option<T> { |
1470 | if self.is_empty() || self.len() <= index { | |
1a4d82fc JJ |
1471 | return None; |
1472 | } | |
1473 | ||
1474 | // There are three main cases: | |
1475 | // Elements are contiguous | |
1476 | // Elements are discontiguous and the removal is in the tail section | |
1477 | // Elements are discontiguous and the removal is in the head section | |
1478 | // - special case when elements are technically contiguous, | |
1479 | // but self.head = 0 | |
1480 | // | |
1481 | // For each of those there are two more cases: | |
1482 | // Insert is closer to tail | |
1483 | // Insert is closer to head | |
1484 | // | |
1485 | // Key: H - self.head | |
1486 | // T - self.tail | |
1487 | // o - Valid element | |
1488 | // x - Element marked for removal | |
1489 | // R - Indicates element that is being removed | |
1490 | // M - Indicates element was moved | |
1491 | ||
c1a9b12d | 1492 | let idx = self.wrap_add(self.tail, index); |
1a4d82fc | 1493 | |
92a42be0 | 1494 | let elem = unsafe { Some(self.buffer_read(idx)) }; |
1a4d82fc | 1495 | |
c1a9b12d SL |
1496 | let distance_to_tail = index; |
1497 | let distance_to_head = self.len() - index; | |
1a4d82fc JJ |
1498 | |
1499 | let contiguous = self.is_contiguous(); | |
1500 | ||
32a655c1 | 1501 | match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) { |
92a42be0 SL |
1502 | (true, true, _) => { |
1503 | unsafe { | |
1504 | // contiguous, remove closer to tail: | |
1505 | // | |
1506 | // T R H | |
1507 | // [. . . o o x o o o o . . . . . .] | |
1508 | // | |
1509 | // T H | |
1510 | // [. . . . o o o o o o . . . . . .] | |
1511 | // M M | |
1512 | ||
1513 | self.copy(self.tail + 1, self.tail, index); | |
1514 | self.tail += 1; | |
1515 | } | |
1516 | } | |
1517 | (true, false, _) => { | |
1518 | unsafe { | |
1519 | // contiguous, remove closer to head: | |
1520 | // | |
1521 | // T R H | |
1522 | // [. . . o o o o x o o . . . . . .] | |
1523 | // | |
1524 | // T H | |
1525 | // [. . . o o o o o o . . . . . . .] | |
1526 | // M M | |
1527 | ||
1528 | self.copy(idx, idx + 1, self.head - idx - 1); | |
1529 | self.head -= 1; | |
1530 | } | |
1531 | } | |
1532 | (false, true, true) => { | |
1533 | unsafe { | |
1534 | // discontiguous, remove closer to tail, tail section: | |
1535 | // | |
1536 | // H T R | |
1537 | // [o o o o o o . . . . . o o x o o] | |
1538 | // | |
1539 | // H T | |
1540 | // [o o o o o o . . . . . . o o o o] | |
1541 | // M M | |
1542 | ||
1543 | self.copy(self.tail + 1, self.tail, index); | |
1544 | self.tail = self.wrap_add(self.tail, 1); | |
1a4d82fc | 1545 | } |
92a42be0 SL |
1546 | } |
1547 | (false, false, false) => { | |
1548 | unsafe { | |
1549 | // discontiguous, remove closer to head, head section: | |
1550 | // | |
1551 | // R H T | |
1552 | // [o o o o x o o . . . . . . o o o] | |
1553 | // | |
1554 | // H T | |
1555 | // [o o o o o o . . . . . . . o o o] | |
1556 | // M M | |
1557 | ||
1558 | self.copy(idx, idx + 1, self.head - idx - 1); | |
1559 | self.head -= 1; | |
1560 | } | |
1561 | } | |
1562 | (false, false, true) => { | |
1563 | unsafe { | |
1564 | // discontiguous, remove closer to head, tail section: | |
1565 | // | |
1566 | // H T R | |
1567 | // [o o o . . . . . . o o o o o x o] | |
1568 | // | |
1569 | // H T | |
1570 | // [o o . . . . . . . o o o o o o o] | |
1571 | // M M M M | |
1572 | // | |
1573 | // or quasi-discontiguous, remove next to head, tail section: | |
1574 | // | |
1575 | // H T R | |
1576 | // [. . . . . . . . . o o o o o x o] | |
1577 | // | |
1578 | // T H | |
1579 | // [. . . . . . . . . o o o o o o .] | |
1580 | // M | |
1581 | ||
1582 | // draw in elements in the tail section | |
1583 | self.copy(idx, idx + 1, self.cap() - idx - 1); | |
1584 | ||
1585 | // Prevents underflow. | |
1586 | if self.head != 0 { | |
1587 | // copy first element into empty spot | |
1588 | self.copy(self.cap() - 1, 0, 1); | |
1589 | ||
1590 | // move elements in the head section backwards | |
1591 | self.copy(0, 1, self.head - 1); | |
1592 | } | |
1a4d82fc | 1593 | |
92a42be0 SL |
1594 | self.head = self.wrap_sub(self.head, 1); |
1595 | } | |
1596 | } | |
1597 | (false, true, false) => { | |
1598 | unsafe { | |
1599 | // discontiguous, remove closer to tail, head section: | |
1600 | // | |
1601 | // R H T | |
1602 | // [o o x o o o o o o o . . . o o o] | |
1603 | // | |
1604 | // H T | |
1605 | // [o o o o o o o o o o . . . . o o] | |
1606 | // M M M M M | |
1a4d82fc | 1607 | |
92a42be0 SL |
1608 | // draw in elements up to idx |
1609 | self.copy(1, 0, idx); | |
1a4d82fc | 1610 | |
92a42be0 SL |
1611 | // copy last element into empty spot |
1612 | self.copy(0, self.cap() - 1, 1); | |
1a4d82fc | 1613 | |
92a42be0 SL |
1614 | // move elements from tail to end forward, excluding the last one |
1615 | self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1); | |
1a4d82fc | 1616 | |
92a42be0 SL |
1617 | self.tail = self.wrap_add(self.tail, 1); |
1618 | } | |
1a4d82fc JJ |
1619 | } |
1620 | } | |
1621 | ||
1622 | return elem; | |
1623 | } | |
85aaf69f SL |
1624 | |
1625 | /// Splits the collection into two at the given index. | |
1626 | /// | |
1627 | /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`, | |
1628 | /// and the returned `Self` contains elements `[at, len)`. | |
1629 | /// | |
1630 | /// Note that the capacity of `self` does not change. | |
1631 | /// | |
5bcae85e SL |
1632 | /// Element at index 0 is the front of the queue. |
1633 | /// | |
85aaf69f SL |
1634 | /// # Panics |
1635 | /// | |
1636 | /// Panics if `at > len` | |
1637 | /// | |
1638 | /// # Examples | |
1639 | /// | |
1640 | /// ``` | |
1641 | /// use std::collections::VecDeque; | |
1642 | /// | |
1643 | /// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect(); | |
1644 | /// let buf2 = buf.split_off(1); | |
8bb4bdeb XL |
1645 | /// assert_eq!(buf, [1]); |
1646 | /// assert_eq!(buf2, [2, 3]); | |
85aaf69f SL |
1647 | /// ``` |
1648 | #[inline] | |
e9174d1e | 1649 | #[stable(feature = "split_off", since = "1.4.0")] |
85aaf69f SL |
1650 | pub fn split_off(&mut self, at: usize) -> Self { |
1651 | let len = self.len(); | |
1652 | assert!(at <= len, "`at` out of bounds"); | |
1653 | ||
1654 | let other_len = len - at; | |
1655 | let mut other = VecDeque::with_capacity(other_len); | |
1656 | ||
1657 | unsafe { | |
1658 | let (first_half, second_half) = self.as_slices(); | |
1659 | ||
1660 | let first_len = first_half.len(); | |
1661 | let second_len = second_half.len(); | |
1662 | if at < first_len { | |
1663 | // `at` lies in the first half. | |
1664 | let amount_in_first = first_len - at; | |
1665 | ||
c34b1796 | 1666 | ptr::copy_nonoverlapping(first_half.as_ptr().offset(at as isize), |
c1a9b12d | 1667 | other.ptr(), |
c34b1796 | 1668 | amount_in_first); |
85aaf69f SL |
1669 | |
1670 | // just take all of the second half. | |
c34b1796 | 1671 | ptr::copy_nonoverlapping(second_half.as_ptr(), |
c1a9b12d | 1672 | other.ptr().offset(amount_in_first as isize), |
c34b1796 | 1673 | second_len); |
85aaf69f SL |
1674 | } else { |
1675 | // `at` lies in the second half, need to factor in the elements we skipped | |
1676 | // in the first half. | |
1677 | let offset = at - first_len; | |
1678 | let amount_in_second = second_len - offset; | |
c34b1796 | 1679 | ptr::copy_nonoverlapping(second_half.as_ptr().offset(offset as isize), |
c1a9b12d | 1680 | other.ptr(), |
c34b1796 | 1681 | amount_in_second); |
85aaf69f SL |
1682 | } |
1683 | } | |
1684 | ||
1685 | // Cleanup where the ends of the buffers are | |
c34b1796 | 1686 | self.head = self.wrap_sub(self.head, other_len); |
85aaf69f SL |
1687 | other.head = other.wrap_index(other_len); |
1688 | ||
1689 | other | |
1690 | } | |
1691 | ||
1692 | /// Moves all the elements of `other` into `Self`, leaving `other` empty. | |
1693 | /// | |
1694 | /// # Panics | |
1695 | /// | |
1696 | /// Panics if the new number of elements in self overflows a `usize`. | |
1697 | /// | |
1698 | /// # Examples | |
1699 | /// | |
1700 | /// ``` | |
1701 | /// use std::collections::VecDeque; | |
1702 | /// | |
8bb4bdeb XL |
1703 | /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect(); |
1704 | /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect(); | |
85aaf69f | 1705 | /// buf.append(&mut buf2); |
8bb4bdeb XL |
1706 | /// assert_eq!(buf, [1, 2, 3, 4]); |
1707 | /// assert_eq!(buf2, []); | |
85aaf69f SL |
1708 | /// ``` |
1709 | #[inline] | |
e9174d1e | 1710 | #[stable(feature = "append", since = "1.4.0")] |
85aaf69f SL |
1711 | pub fn append(&mut self, other: &mut Self) { |
1712 | // naive impl | |
b039eaaf | 1713 | self.extend(other.drain(..)); |
85aaf69f | 1714 | } |
d9579d0f AL |
1715 | |
1716 | /// Retains only the elements specified by the predicate. | |
1717 | /// | |
1718 | /// In other words, remove all elements `e` such that `f(&e)` returns false. | |
1719 | /// This method operates in place and preserves the order of the retained | |
1720 | /// elements. | |
1721 | /// | |
1722 | /// # Examples | |
1723 | /// | |
1724 | /// ``` | |
d9579d0f AL |
1725 | /// use std::collections::VecDeque; |
1726 | /// | |
1727 | /// let mut buf = VecDeque::new(); | |
1728 | /// buf.extend(1..5); | |
1729 | /// buf.retain(|&x| x%2 == 0); | |
8bb4bdeb | 1730 | /// assert_eq!(buf, [2, 4]); |
d9579d0f | 1731 | /// ``` |
e9174d1e | 1732 | #[stable(feature = "vec_deque_retain", since = "1.4.0")] |
92a42be0 SL |
1733 | pub fn retain<F>(&mut self, mut f: F) |
1734 | where F: FnMut(&T) -> bool | |
1735 | { | |
d9579d0f AL |
1736 | let len = self.len(); |
1737 | let mut del = 0; | |
1738 | for i in 0..len { | |
1739 | if !f(&self[i]) { | |
1740 | del += 1; | |
1741 | } else if del > 0 { | |
92a42be0 | 1742 | self.swap(i - del, i); |
d9579d0f AL |
1743 | } |
1744 | } | |
1745 | if del > 0 { | |
1746 | self.truncate(len - del); | |
1747 | } | |
1748 | } | |
8bb4bdeb XL |
1749 | |
1750 | // This may panic or abort | |
1751 | #[inline] | |
1752 | fn grow_if_necessary(&mut self) { | |
1753 | if self.is_full() { | |
1754 | let old_cap = self.cap(); | |
1755 | self.buf.double(); | |
1756 | unsafe { | |
1757 | self.handle_cap_increase(old_cap); | |
1758 | } | |
1759 | debug_assert!(!self.is_full()); | |
1760 | } | |
1761 | } | |
1762 | ||
1763 | /// Returns a place for insertion at the back of the `VecDeque`. | |
1764 | /// | |
1765 | /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back), | |
1766 | /// but may be more efficient. | |
1767 | /// | |
1768 | /// # Examples | |
1769 | /// | |
1770 | /// ``` | |
1771 | /// #![feature(collection_placement)] | |
1772 | /// #![feature(placement_in_syntax)] | |
1773 | /// | |
1774 | /// use std::collections::VecDeque; | |
1775 | /// | |
1776 | /// let mut buf = VecDeque::new(); | |
1777 | /// buf.place_back() <- 3; | |
1778 | /// buf.place_back() <- 4; | |
1779 | /// assert_eq!(&buf, &[3, 4]); | |
1780 | /// ``` | |
1781 | #[unstable(feature = "collection_placement", | |
1782 | reason = "placement protocol is subject to change", | |
1783 | issue = "30172")] | |
1784 | pub fn place_back(&mut self) -> PlaceBack<T> { | |
1785 | PlaceBack { vec_deque: self } | |
1786 | } | |
1787 | ||
1788 | /// Returns a place for insertion at the front of the `VecDeque`. | |
1789 | /// | |
1790 | /// Using this method with placement syntax is equivalent to [`push_front`](#method.push_front), | |
1791 | /// but may be more efficient. | |
1792 | /// | |
1793 | /// # Examples | |
1794 | /// | |
1795 | /// ``` | |
1796 | /// #![feature(collection_placement)] | |
1797 | /// #![feature(placement_in_syntax)] | |
1798 | /// | |
1799 | /// use std::collections::VecDeque; | |
1800 | /// | |
1801 | /// let mut buf = VecDeque::new(); | |
1802 | /// buf.place_front() <- 3; | |
1803 | /// buf.place_front() <- 4; | |
1804 | /// assert_eq!(&buf, &[4, 3]); | |
1805 | /// ``` | |
1806 | #[unstable(feature = "collection_placement", | |
1807 | reason = "placement protocol is subject to change", | |
1808 | issue = "30172")] | |
1809 | pub fn place_front(&mut self) -> PlaceFront<T> { | |
1810 | PlaceFront { vec_deque: self } | |
1811 | } | |
1a4d82fc JJ |
1812 | } |
1813 | ||
85aaf69f | 1814 | impl<T: Clone> VecDeque<T> { |
c1a9b12d | 1815 | /// Modifies the `VecDeque` in-place so that `len()` is equal to new_len, |
8bb4bdeb | 1816 | /// either by removing excess elements or by appending clones of `value` to the back. |
1a4d82fc JJ |
1817 | /// |
1818 | /// # Examples | |
1819 | /// | |
1820 | /// ``` | |
85aaf69f | 1821 | /// use std::collections::VecDeque; |
1a4d82fc | 1822 | /// |
85aaf69f SL |
1823 | /// let mut buf = VecDeque::new(); |
1824 | /// buf.push_back(5); | |
1825 | /// buf.push_back(10); | |
1a4d82fc | 1826 | /// buf.push_back(15); |
8bb4bdeb XL |
1827 | /// assert_eq!(buf, [5, 10, 15]); |
1828 | /// | |
1a4d82fc | 1829 | /// buf.resize(2, 0); |
8bb4bdeb XL |
1830 | /// assert_eq!(buf, [5, 10]); |
1831 | /// | |
1832 | /// buf.resize(5, 20); | |
1833 | /// assert_eq!(buf, [5, 10, 20, 20, 20]); | |
1a4d82fc | 1834 | /// ``` |
32a655c1 | 1835 | #[stable(feature = "deque_extras", since = "1.16.0")] |
85aaf69f | 1836 | pub fn resize(&mut self, new_len: usize, value: T) { |
1a4d82fc JJ |
1837 | let len = self.len(); |
1838 | ||
1839 | if new_len > len { | |
1840 | self.extend(repeat(value).take(new_len - len)) | |
1841 | } else { | |
1842 | self.truncate(new_len); | |
1843 | } | |
1844 | } | |
1845 | } | |
1846 | ||
1847 | /// Returns the index in the underlying buffer for a given logical element index. | |
1848 | #[inline] | |
85aaf69f | 1849 | fn wrap_index(index: usize, size: usize) -> usize { |
1a4d82fc | 1850 | // size is always a power of 2 |
e9174d1e | 1851 | debug_assert!(size.is_power_of_two()); |
1a4d82fc JJ |
1852 | index & (size - 1) |
1853 | } | |
1854 | ||
cc61c64b | 1855 | /// Returns the two slices that cover the `VecDeque`'s valid range |
32a655c1 | 1856 | trait RingSlices: Sized { |
c30ab7b3 SL |
1857 | fn slice(self, from: usize, to: usize) -> Self; |
1858 | fn split_at(self, i: usize) -> (Self, Self); | |
1859 | ||
1860 | fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) { | |
1861 | let contiguous = tail <= head; | |
1862 | if contiguous { | |
1863 | let (empty, buf) = buf.split_at(0); | |
1864 | (buf.slice(tail, head), empty) | |
1865 | } else { | |
1866 | let (mid, right) = buf.split_at(tail); | |
1867 | let (left, _) = mid.split_at(head); | |
1868 | (right, left) | |
1869 | } | |
1870 | } | |
1871 | } | |
1872 | ||
1873 | impl<'a, T> RingSlices for &'a [T] { | |
1874 | fn slice(self, from: usize, to: usize) -> Self { | |
1875 | &self[from..to] | |
1876 | } | |
1877 | fn split_at(self, i: usize) -> (Self, Self) { | |
1878 | (*self).split_at(i) | |
1879 | } | |
1880 | } | |
1881 | ||
1882 | impl<'a, T> RingSlices for &'a mut [T] { | |
1883 | fn slice(self, from: usize, to: usize) -> Self { | |
1884 | &mut self[from..to] | |
1885 | } | |
1886 | fn split_at(self, i: usize) -> (Self, Self) { | |
1887 | (*self).split_at_mut(i) | |
1888 | } | |
1889 | } | |
1890 | ||
1a4d82fc JJ |
1891 | /// Calculate the number of elements left to be read in the buffer |
1892 | #[inline] | |
85aaf69f | 1893 | fn count(tail: usize, head: usize, size: usize) -> usize { |
1a4d82fc | 1894 | // size is always a power of 2 |
c34b1796 | 1895 | (head.wrapping_sub(tail)) & (size - 1) |
1a4d82fc JJ |
1896 | } |
1897 | ||
cc61c64b XL |
1898 | /// An iterator over the elements of a `VecDeque`. |
1899 | /// | |
1900 | /// This `struct` is created by the [`iter`] method on [`VecDeque`]. See its | |
1901 | /// documentation for more. | |
1902 | /// | |
1903 | /// [`iter`]: struct.VecDeque.html#method.iter | |
1904 | /// [`VecDeque`]: struct.VecDeque.html | |
85aaf69f | 1905 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 1906 | pub struct Iter<'a, T: 'a> { |
1a4d82fc | 1907 | ring: &'a [T], |
85aaf69f | 1908 | tail: usize, |
92a42be0 | 1909 | head: usize, |
1a4d82fc JJ |
1910 | } |
1911 | ||
8bb4bdeb XL |
1912 | #[stable(feature = "collection_debug", since = "1.17.0")] |
1913 | impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> { | |
1914 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
1915 | f.debug_tuple("Iter") | |
cc61c64b XL |
1916 | .field(&self.ring) |
1917 | .field(&self.tail) | |
1918 | .field(&self.head) | |
8bb4bdeb XL |
1919 | .finish() |
1920 | } | |
1921 | } | |
1922 | ||
1a4d82fc | 1923 | // FIXME(#19839) Remove in favor of `#[derive(Clone)]` |
92a42be0 | 1924 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1925 | impl<'a, T> Clone for Iter<'a, T> { |
1926 | fn clone(&self) -> Iter<'a, T> { | |
1927 | Iter { | |
1928 | ring: self.ring, | |
1929 | tail: self.tail, | |
92a42be0 | 1930 | head: self.head, |
1a4d82fc JJ |
1931 | } |
1932 | } | |
1933 | } | |
1934 | ||
85aaf69f | 1935 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1936 | impl<'a, T> Iterator for Iter<'a, T> { |
1937 | type Item = &'a T; | |
1938 | ||
1939 | #[inline] | |
1940 | fn next(&mut self) -> Option<&'a T> { | |
1941 | if self.tail == self.head { | |
1942 | return None; | |
1943 | } | |
1944 | let tail = self.tail; | |
c34b1796 | 1945 | self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len()); |
1a4d82fc JJ |
1946 | unsafe { Some(self.ring.get_unchecked(tail)) } |
1947 | } | |
1948 | ||
1949 | #[inline] | |
85aaf69f | 1950 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
1951 | let len = count(self.tail, self.head, self.ring.len()); |
1952 | (len, Some(len)) | |
1953 | } | |
c30ab7b3 SL |
1954 | |
1955 | fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc | |
32a655c1 | 1956 | where F: FnMut(Acc, Self::Item) -> Acc |
c30ab7b3 SL |
1957 | { |
1958 | let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail); | |
1959 | accum = front.iter().fold(accum, &mut f); | |
1960 | back.iter().fold(accum, &mut f) | |
1961 | } | |
1a4d82fc JJ |
1962 | } |
1963 | ||
85aaf69f | 1964 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1965 | impl<'a, T> DoubleEndedIterator for Iter<'a, T> { |
1966 | #[inline] | |
1967 | fn next_back(&mut self) -> Option<&'a T> { | |
1968 | if self.tail == self.head { | |
1969 | return None; | |
1970 | } | |
c34b1796 | 1971 | self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len()); |
1a4d82fc JJ |
1972 | unsafe { Some(self.ring.get_unchecked(self.head)) } |
1973 | } | |
1974 | } | |
1975 | ||
85aaf69f | 1976 | #[stable(feature = "rust1", since = "1.0.0")] |
476ff2be SL |
1977 | impl<'a, T> ExactSizeIterator for Iter<'a, T> { |
1978 | fn is_empty(&self) -> bool { | |
1979 | self.head == self.tail | |
1980 | } | |
1981 | } | |
1a4d82fc | 1982 | |
9e0c209e SL |
1983 | #[unstable(feature = "fused", issue = "35602")] |
1984 | impl<'a, T> FusedIterator for Iter<'a, T> {} | |
1985 | ||
1986 | ||
cc61c64b XL |
1987 | /// A mutable iterator over the elements of a `VecDeque`. |
1988 | /// | |
1989 | /// This `struct` is created by the [`iter_mut`] method on [`VecDeque`]. See its | |
1990 | /// documentation for more. | |
1991 | /// | |
1992 | /// [`iter_mut`]: struct.VecDeque.html#method.iter_mut | |
1993 | /// [`VecDeque`]: struct.VecDeque.html | |
85aaf69f | 1994 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 1995 | pub struct IterMut<'a, T: 'a> { |
c34b1796 | 1996 | ring: &'a mut [T], |
85aaf69f SL |
1997 | tail: usize, |
1998 | head: usize, | |
1a4d82fc JJ |
1999 | } |
2000 | ||
8bb4bdeb XL |
2001 | #[stable(feature = "collection_debug", since = "1.17.0")] |
2002 | impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> { | |
2003 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
2004 | f.debug_tuple("IterMut") | |
cc61c64b XL |
2005 | .field(&self.ring) |
2006 | .field(&self.tail) | |
2007 | .field(&self.head) | |
8bb4bdeb XL |
2008 | .finish() |
2009 | } | |
2010 | } | |
2011 | ||
85aaf69f | 2012 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2013 | impl<'a, T> Iterator for IterMut<'a, T> { |
2014 | type Item = &'a mut T; | |
2015 | ||
2016 | #[inline] | |
2017 | fn next(&mut self) -> Option<&'a mut T> { | |
2018 | if self.tail == self.head { | |
2019 | return None; | |
2020 | } | |
2021 | let tail = self.tail; | |
c34b1796 | 2022 | self.tail = wrap_index(self.tail.wrapping_add(1), self.ring.len()); |
1a4d82fc JJ |
2023 | |
2024 | unsafe { | |
c34b1796 AL |
2025 | let elem = self.ring.get_unchecked_mut(tail); |
2026 | Some(&mut *(elem as *mut _)) | |
1a4d82fc JJ |
2027 | } |
2028 | } | |
2029 | ||
2030 | #[inline] | |
85aaf69f | 2031 | fn size_hint(&self) -> (usize, Option<usize>) { |
c34b1796 | 2032 | let len = count(self.tail, self.head, self.ring.len()); |
1a4d82fc JJ |
2033 | (len, Some(len)) |
2034 | } | |
c30ab7b3 SL |
2035 | |
2036 | fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc | |
32a655c1 | 2037 | where F: FnMut(Acc, Self::Item) -> Acc |
c30ab7b3 SL |
2038 | { |
2039 | let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail); | |
2040 | accum = front.iter_mut().fold(accum, &mut f); | |
2041 | back.iter_mut().fold(accum, &mut f) | |
2042 | } | |
1a4d82fc JJ |
2043 | } |
2044 | ||
85aaf69f | 2045 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2046 | impl<'a, T> DoubleEndedIterator for IterMut<'a, T> { |
2047 | #[inline] | |
2048 | fn next_back(&mut self) -> Option<&'a mut T> { | |
2049 | if self.tail == self.head { | |
2050 | return None; | |
2051 | } | |
c34b1796 | 2052 | self.head = wrap_index(self.head.wrapping_sub(1), self.ring.len()); |
1a4d82fc JJ |
2053 | |
2054 | unsafe { | |
c34b1796 AL |
2055 | let elem = self.ring.get_unchecked_mut(self.head); |
2056 | Some(&mut *(elem as *mut _)) | |
1a4d82fc JJ |
2057 | } |
2058 | } | |
2059 | } | |
2060 | ||
85aaf69f | 2061 | #[stable(feature = "rust1", since = "1.0.0")] |
476ff2be SL |
2062 | impl<'a, T> ExactSizeIterator for IterMut<'a, T> { |
2063 | fn is_empty(&self) -> bool { | |
2064 | self.head == self.tail | |
2065 | } | |
2066 | } | |
1a4d82fc | 2067 | |
9e0c209e SL |
2068 | #[unstable(feature = "fused", issue = "35602")] |
2069 | impl<'a, T> FusedIterator for IterMut<'a, T> {} | |
2070 | ||
cc61c64b XL |
2071 | /// An owning iterator over the elements of a `VecDeque`. |
2072 | /// | |
2073 | /// This `struct` is created by the [`into_iter`] method on [`VecDeque`][`VecDeque`] | |
2074 | /// (provided by the `IntoIterator` trait). See its documentation for more. | |
2075 | /// | |
2076 | /// [`into_iter`]: struct.VecDeque.html#method.into_iter | |
2077 | /// [`VecDeque`]: struct.VecDeque.html | |
c34b1796 | 2078 | #[derive(Clone)] |
85aaf69f | 2079 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2080 | pub struct IntoIter<T> { |
85aaf69f | 2081 | inner: VecDeque<T>, |
1a4d82fc JJ |
2082 | } |
2083 | ||
8bb4bdeb XL |
2084 | #[stable(feature = "collection_debug", since = "1.17.0")] |
2085 | impl<T: fmt::Debug> fmt::Debug for IntoIter<T> { | |
2086 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
2087 | f.debug_tuple("IntoIter") | |
cc61c64b | 2088 | .field(&self.inner) |
8bb4bdeb XL |
2089 | .finish() |
2090 | } | |
2091 | } | |
2092 | ||
85aaf69f | 2093 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2094 | impl<T> Iterator for IntoIter<T> { |
2095 | type Item = T; | |
2096 | ||
2097 | #[inline] | |
2098 | fn next(&mut self) -> Option<T> { | |
2099 | self.inner.pop_front() | |
2100 | } | |
2101 | ||
2102 | #[inline] | |
85aaf69f | 2103 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
2104 | let len = self.inner.len(); |
2105 | (len, Some(len)) | |
2106 | } | |
2107 | } | |
2108 | ||
85aaf69f | 2109 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2110 | impl<T> DoubleEndedIterator for IntoIter<T> { |
2111 | #[inline] | |
2112 | fn next_back(&mut self) -> Option<T> { | |
2113 | self.inner.pop_back() | |
2114 | } | |
2115 | } | |
2116 | ||
85aaf69f | 2117 | #[stable(feature = "rust1", since = "1.0.0")] |
476ff2be SL |
2118 | impl<T> ExactSizeIterator for IntoIter<T> { |
2119 | fn is_empty(&self) -> bool { | |
2120 | self.inner.is_empty() | |
2121 | } | |
2122 | } | |
1a4d82fc | 2123 | |
9e0c209e SL |
2124 | #[unstable(feature = "fused", issue = "35602")] |
2125 | impl<T> FusedIterator for IntoIter<T> {} | |
2126 | ||
cc61c64b XL |
2127 | /// A draining iterator over the elements of a `VecDeque`. |
2128 | /// | |
2129 | /// This `struct` is created by the [`drain`] method on [`VecDeque`]. See its | |
2130 | /// documentation for more. | |
2131 | /// | |
2132 | /// [`drain`]: struct.VecDeque.html#method.drain | |
2133 | /// [`VecDeque`]: struct.VecDeque.html | |
92a42be0 | 2134 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc | 2135 | pub struct Drain<'a, T: 'a> { |
b039eaaf SL |
2136 | after_tail: usize, |
2137 | after_head: usize, | |
2138 | iter: Iter<'a, T>, | |
9e0c209e | 2139 | deque: Shared<VecDeque<T>>, |
1a4d82fc JJ |
2140 | } |
2141 | ||
8bb4bdeb XL |
2142 | #[stable(feature = "collection_debug", since = "1.17.0")] |
2143 | impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> { | |
2144 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
2145 | f.debug_tuple("Drain") | |
cc61c64b XL |
2146 | .field(&self.after_tail) |
2147 | .field(&self.after_head) | |
2148 | .field(&self.iter) | |
8bb4bdeb XL |
2149 | .finish() |
2150 | } | |
2151 | } | |
2152 | ||
92a42be0 | 2153 | #[stable(feature = "drain", since = "1.6.0")] |
b039eaaf | 2154 | unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {} |
92a42be0 | 2155 | #[stable(feature = "drain", since = "1.6.0")] |
b039eaaf SL |
2156 | unsafe impl<'a, T: Send> Send for Drain<'a, T> {} |
2157 | ||
c30ab7b3 | 2158 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2159 | impl<'a, T: 'a> Drop for Drain<'a, T> { |
2160 | fn drop(&mut self) { | |
85aaf69f | 2161 | for _ in self.by_ref() {} |
b039eaaf | 2162 | |
7cac9316 | 2163 | let source_deque = unsafe { self.deque.as_mut() }; |
b039eaaf SL |
2164 | |
2165 | // T = source_deque_tail; H = source_deque_head; t = drain_tail; h = drain_head | |
2166 | // | |
2167 | // T t h H | |
2168 | // [. . . o o x x o o . . .] | |
2169 | // | |
2170 | let orig_tail = source_deque.tail; | |
2171 | let drain_tail = source_deque.head; | |
2172 | let drain_head = self.after_tail; | |
2173 | let orig_head = self.after_head; | |
2174 | ||
2175 | let tail_len = count(orig_tail, drain_tail, source_deque.cap()); | |
2176 | let head_len = count(drain_head, orig_head, source_deque.cap()); | |
2177 | ||
2178 | // Restore the original head value | |
2179 | source_deque.head = orig_head; | |
2180 | ||
2181 | match (tail_len, head_len) { | |
2182 | (0, 0) => { | |
2183 | source_deque.head = 0; | |
2184 | source_deque.tail = 0; | |
2185 | } | |
2186 | (0, _) => { | |
2187 | source_deque.tail = drain_head; | |
2188 | } | |
2189 | (_, 0) => { | |
2190 | source_deque.head = drain_tail; | |
2191 | } | |
32a655c1 SL |
2192 | _ => unsafe { |
2193 | if tail_len <= head_len { | |
2194 | source_deque.tail = source_deque.wrap_sub(drain_head, tail_len); | |
2195 | source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len); | |
2196 | } else { | |
2197 | source_deque.head = source_deque.wrap_add(drain_tail, head_len); | |
2198 | source_deque.wrap_copy(drain_tail, drain_head, head_len); | |
b039eaaf | 2199 | } |
32a655c1 | 2200 | }, |
b039eaaf | 2201 | } |
1a4d82fc JJ |
2202 | } |
2203 | } | |
2204 | ||
c30ab7b3 | 2205 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2206 | impl<'a, T: 'a> Iterator for Drain<'a, T> { |
2207 | type Item = T; | |
2208 | ||
2209 | #[inline] | |
2210 | fn next(&mut self) -> Option<T> { | |
92a42be0 | 2211 | self.iter.next().map(|elt| unsafe { ptr::read(elt) }) |
1a4d82fc JJ |
2212 | } |
2213 | ||
2214 | #[inline] | |
85aaf69f | 2215 | fn size_hint(&self) -> (usize, Option<usize>) { |
b039eaaf | 2216 | self.iter.size_hint() |
1a4d82fc JJ |
2217 | } |
2218 | } | |
2219 | ||
c30ab7b3 | 2220 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2221 | impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> { |
2222 | #[inline] | |
2223 | fn next_back(&mut self) -> Option<T> { | |
92a42be0 | 2224 | self.iter.next_back().map(|elt| unsafe { ptr::read(elt) }) |
1a4d82fc JJ |
2225 | } |
2226 | } | |
2227 | ||
c30ab7b3 | 2228 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2229 | impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {} |
2230 | ||
9e0c209e SL |
2231 | #[unstable(feature = "fused", issue = "35602")] |
2232 | impl<'a, T: 'a> FusedIterator for Drain<'a, T> {} | |
2233 | ||
85aaf69f SL |
2234 | #[stable(feature = "rust1", since = "1.0.0")] |
2235 | impl<A: PartialEq> PartialEq for VecDeque<A> { | |
2236 | fn eq(&self, other: &VecDeque<A>) -> bool { | |
7453a54e SL |
2237 | if self.len() != other.len() { |
2238 | return false; | |
2239 | } | |
2240 | let (sa, sb) = self.as_slices(); | |
2241 | let (oa, ob) = other.as_slices(); | |
2242 | if sa.len() == oa.len() { | |
2243 | sa == oa && sb == ob | |
2244 | } else if sa.len() < oa.len() { | |
2245 | // Always divisible in three sections, for example: | |
2246 | // self: [a b c|d e f] | |
2247 | // other: [0 1 2 3|4 5] | |
2248 | // front = 3, mid = 1, | |
2249 | // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5] | |
2250 | let front = sa.len(); | |
2251 | let mid = oa.len() - front; | |
2252 | ||
2253 | let (oa_front, oa_mid) = oa.split_at(front); | |
2254 | let (sb_mid, sb_back) = sb.split_at(mid); | |
2255 | debug_assert_eq!(sa.len(), oa_front.len()); | |
2256 | debug_assert_eq!(sb_mid.len(), oa_mid.len()); | |
2257 | debug_assert_eq!(sb_back.len(), ob.len()); | |
2258 | sa == oa_front && sb_mid == oa_mid && sb_back == ob | |
2259 | } else { | |
2260 | let front = oa.len(); | |
2261 | let mid = sa.len() - front; | |
2262 | ||
2263 | let (sa_front, sa_mid) = sa.split_at(front); | |
2264 | let (ob_mid, ob_back) = ob.split_at(mid); | |
2265 | debug_assert_eq!(sa_front.len(), oa.len()); | |
2266 | debug_assert_eq!(sa_mid.len(), ob_mid.len()); | |
2267 | debug_assert_eq!(sb.len(), ob_back.len()); | |
2268 | sa_front == oa && sa_mid == ob_mid && sb == ob_back | |
2269 | } | |
1a4d82fc JJ |
2270 | } |
2271 | } | |
2272 | ||
85aaf69f SL |
2273 | #[stable(feature = "rust1", since = "1.0.0")] |
2274 | impl<A: Eq> Eq for VecDeque<A> {} | |
1a4d82fc | 2275 | |
8bb4bdeb XL |
2276 | macro_rules! __impl_slice_eq1 { |
2277 | ($Lhs: ty, $Rhs: ty) => { | |
2278 | __impl_slice_eq1! { $Lhs, $Rhs, Sized } | |
2279 | }; | |
2280 | ($Lhs: ty, $Rhs: ty, $Bound: ident) => { | |
cc61c64b | 2281 | #[stable(feature = "vec-deque-partial-eq-slice", since = "1.17.0")] |
8bb4bdeb XL |
2282 | impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> { |
2283 | fn eq(&self, other: &$Rhs) -> bool { | |
2284 | if self.len() != other.len() { | |
2285 | return false; | |
2286 | } | |
2287 | let (sa, sb) = self.as_slices(); | |
2288 | let (oa, ob) = other[..].split_at(sa.len()); | |
2289 | sa == oa && sb == ob | |
2290 | } | |
2291 | } | |
2292 | } | |
2293 | } | |
2294 | ||
2295 | __impl_slice_eq1! { VecDeque<A>, Vec<B> } | |
2296 | __impl_slice_eq1! { VecDeque<A>, &'b [B] } | |
2297 | __impl_slice_eq1! { VecDeque<A>, &'b mut [B] } | |
2298 | ||
2299 | macro_rules! array_impls { | |
2300 | ($($N: expr)+) => { | |
2301 | $( | |
2302 | __impl_slice_eq1! { VecDeque<A>, [B; $N] } | |
2303 | __impl_slice_eq1! { VecDeque<A>, &'b [B; $N] } | |
2304 | __impl_slice_eq1! { VecDeque<A>, &'b mut [B; $N] } | |
2305 | )+ | |
2306 | } | |
2307 | } | |
2308 | ||
2309 | array_impls! { | |
2310 | 0 1 2 3 4 5 6 7 8 9 | |
2311 | 10 11 12 13 14 15 16 17 18 19 | |
2312 | 20 21 22 23 24 25 26 27 28 29 | |
2313 | 30 31 32 | |
2314 | } | |
2315 | ||
85aaf69f SL |
2316 | #[stable(feature = "rust1", since = "1.0.0")] |
2317 | impl<A: PartialOrd> PartialOrd for VecDeque<A> { | |
2318 | fn partial_cmp(&self, other: &VecDeque<A>) -> Option<Ordering> { | |
e9174d1e | 2319 | self.iter().partial_cmp(other.iter()) |
1a4d82fc JJ |
2320 | } |
2321 | } | |
2322 | ||
85aaf69f SL |
2323 | #[stable(feature = "rust1", since = "1.0.0")] |
2324 | impl<A: Ord> Ord for VecDeque<A> { | |
1a4d82fc | 2325 | #[inline] |
85aaf69f | 2326 | fn cmp(&self, other: &VecDeque<A>) -> Ordering { |
e9174d1e | 2327 | self.iter().cmp(other.iter()) |
1a4d82fc JJ |
2328 | } |
2329 | } | |
2330 | ||
85aaf69f | 2331 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2332 | impl<A: Hash> Hash for VecDeque<A> { |
2333 | fn hash<H: Hasher>(&self, state: &mut H) { | |
2334 | self.len().hash(state); | |
7453a54e SL |
2335 | let (a, b) = self.as_slices(); |
2336 | Hash::hash_slice(a, state); | |
2337 | Hash::hash_slice(b, state); | |
1a4d82fc JJ |
2338 | } |
2339 | } | |
2340 | ||
85aaf69f SL |
2341 | #[stable(feature = "rust1", since = "1.0.0")] |
2342 | impl<A> Index<usize> for VecDeque<A> { | |
1a4d82fc JJ |
2343 | type Output = A; |
2344 | ||
2345 | #[inline] | |
c1a9b12d SL |
2346 | fn index(&self, index: usize) -> &A { |
2347 | self.get(index).expect("Out of bounds access") | |
1a4d82fc JJ |
2348 | } |
2349 | } | |
2350 | ||
85aaf69f SL |
2351 | #[stable(feature = "rust1", since = "1.0.0")] |
2352 | impl<A> IndexMut<usize> for VecDeque<A> { | |
1a4d82fc | 2353 | #[inline] |
c1a9b12d SL |
2354 | fn index_mut(&mut self, index: usize) -> &mut A { |
2355 | self.get_mut(index).expect("Out of bounds access") | |
1a4d82fc JJ |
2356 | } |
2357 | } | |
2358 | ||
85aaf69f SL |
2359 | #[stable(feature = "rust1", since = "1.0.0")] |
2360 | impl<A> FromIterator<A> for VecDeque<A> { | |
54a0048b SL |
2361 | fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> VecDeque<A> { |
2362 | let iterator = iter.into_iter(); | |
1a4d82fc | 2363 | let (lower, _) = iterator.size_hint(); |
85aaf69f | 2364 | let mut deq = VecDeque::with_capacity(lower); |
1a4d82fc JJ |
2365 | deq.extend(iterator); |
2366 | deq | |
2367 | } | |
2368 | } | |
2369 | ||
85aaf69f SL |
2370 | #[stable(feature = "rust1", since = "1.0.0")] |
2371 | impl<T> IntoIterator for VecDeque<T> { | |
2372 | type Item = T; | |
2373 | type IntoIter = IntoIter<T>; | |
2374 | ||
9346a6ac AL |
2375 | /// Consumes the list into a front-to-back iterator yielding elements by |
2376 | /// value. | |
85aaf69f | 2377 | fn into_iter(self) -> IntoIter<T> { |
92a42be0 | 2378 | IntoIter { inner: self } |
85aaf69f SL |
2379 | } |
2380 | } | |
2381 | ||
2382 | #[stable(feature = "rust1", since = "1.0.0")] | |
2383 | impl<'a, T> IntoIterator for &'a VecDeque<T> { | |
2384 | type Item = &'a T; | |
2385 | type IntoIter = Iter<'a, T>; | |
2386 | ||
2387 | fn into_iter(self) -> Iter<'a, T> { | |
2388 | self.iter() | |
2389 | } | |
2390 | } | |
2391 | ||
2392 | #[stable(feature = "rust1", since = "1.0.0")] | |
2393 | impl<'a, T> IntoIterator for &'a mut VecDeque<T> { | |
2394 | type Item = &'a mut T; | |
2395 | type IntoIter = IterMut<'a, T>; | |
2396 | ||
2397 | fn into_iter(mut self) -> IterMut<'a, T> { | |
2398 | self.iter_mut() | |
2399 | } | |
2400 | } | |
2401 | ||
2402 | #[stable(feature = "rust1", since = "1.0.0")] | |
2403 | impl<A> Extend<A> for VecDeque<A> { | |
92a42be0 | 2404 | fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) { |
85aaf69f | 2405 | for elt in iter { |
1a4d82fc JJ |
2406 | self.push_back(elt); |
2407 | } | |
2408 | } | |
2409 | } | |
2410 | ||
62682a34 SL |
2411 | #[stable(feature = "extend_ref", since = "1.2.0")] |
2412 | impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> { | |
92a42be0 | 2413 | fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { |
62682a34 SL |
2414 | self.extend(iter.into_iter().cloned()); |
2415 | } | |
2416 | } | |
2417 | ||
85aaf69f SL |
2418 | #[stable(feature = "rust1", since = "1.0.0")] |
2419 | impl<T: fmt::Debug> fmt::Debug for VecDeque<T> { | |
1a4d82fc | 2420 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
b039eaaf | 2421 | f.debug_list().entries(self).finish() |
1a4d82fc JJ |
2422 | } |
2423 | } | |
2424 | ||
a7813a04 XL |
2425 | #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")] |
2426 | impl<T> From<Vec<T>> for VecDeque<T> { | |
2427 | fn from(mut other: Vec<T>) -> Self { | |
2428 | unsafe { | |
2429 | let other_buf = other.as_mut_ptr(); | |
2430 | let mut buf = RawVec::from_raw_parts(other_buf, other.capacity()); | |
2431 | let len = other.len(); | |
2432 | mem::forget(other); | |
2433 | ||
2434 | // We need to extend the buf if it's not a power of two, too small | |
2435 | // or doesn't have at least one free space | |
32a655c1 SL |
2436 | if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) || |
2437 | (buf.cap() == len) { | |
a7813a04 XL |
2438 | let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two(); |
2439 | buf.reserve_exact(len, cap - len); | |
2440 | } | |
2441 | ||
2442 | VecDeque { | |
2443 | tail: 0, | |
2444 | head: len, | |
32a655c1 | 2445 | buf: buf, |
a7813a04 XL |
2446 | } |
2447 | } | |
2448 | } | |
2449 | } | |
2450 | ||
2451 | #[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")] | |
2452 | impl<T> From<VecDeque<T>> for Vec<T> { | |
2453 | fn from(other: VecDeque<T>) -> Self { | |
2454 | unsafe { | |
2455 | let buf = other.buf.ptr(); | |
2456 | let len = other.len(); | |
2457 | let tail = other.tail; | |
2458 | let head = other.head; | |
2459 | let cap = other.cap(); | |
2460 | ||
2461 | // Need to move the ring to the front of the buffer, as vec will expect this. | |
2462 | if other.is_contiguous() { | |
2463 | ptr::copy(buf.offset(tail as isize), buf, len); | |
2464 | } else { | |
2465 | if (tail - head) >= cmp::min((cap - tail), head) { | |
2466 | // There is enough free space in the centre for the shortest block so we can | |
2467 | // do this in at most three copy moves. | |
2468 | if (cap - tail) > head { | |
2469 | // right hand block is the long one; move that enough for the left | |
32a655c1 SL |
2470 | ptr::copy(buf.offset(tail as isize), |
2471 | buf.offset((tail - head) as isize), | |
2472 | cap - tail); | |
a7813a04 XL |
2473 | // copy left in the end |
2474 | ptr::copy(buf, buf.offset((cap - head) as isize), head); | |
2475 | // shift the new thing to the start | |
32a655c1 | 2476 | ptr::copy(buf.offset((tail - head) as isize), buf, len); |
a7813a04 XL |
2477 | } else { |
2478 | // left hand block is the long one, we can do it in two! | |
32a655c1 SL |
2479 | ptr::copy(buf, buf.offset((cap - tail) as isize), head); |
2480 | ptr::copy(buf.offset(tail as isize), buf, cap - tail); | |
a7813a04 XL |
2481 | } |
2482 | } else { | |
2483 | // Need to use N swaps to move the ring | |
2484 | // We can use the space at the end of the ring as a temp store | |
2485 | ||
2486 | let mut left_edge: usize = 0; | |
2487 | let mut right_edge: usize = tail; | |
2488 | ||
2489 | // The general problem looks like this | |
2490 | // GHIJKLM...ABCDEF - before any swaps | |
2491 | // ABCDEFM...GHIJKL - after 1 pass of swaps | |
2492 | // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store | |
2493 | // - then restart the algorithm with a new (smaller) store | |
2494 | // Sometimes the temp store is reached when the right edge is at the end | |
2495 | // of the buffer - this means we've hit the right order with fewer swaps! | |
2496 | // E.g | |
2497 | // EF..ABCD | |
2498 | // ABCDEF.. - after four only swaps we've finished | |
2499 | ||
2500 | while left_edge < len && right_edge != cap { | |
2501 | let mut right_offset = 0; | |
2502 | for i in left_edge..right_edge { | |
2503 | right_offset = (i - left_edge) % (cap - right_edge); | |
2504 | let src: isize = (right_edge + right_offset) as isize; | |
2505 | ptr::swap(buf.offset(i as isize), buf.offset(src)); | |
2506 | } | |
2507 | let n_ops = right_edge - left_edge; | |
2508 | left_edge += n_ops; | |
2509 | right_edge += right_offset + 1; | |
2510 | ||
2511 | } | |
2512 | } | |
2513 | ||
2514 | } | |
2515 | let out = Vec::from_raw_parts(buf, len, cap); | |
2516 | mem::forget(other); | |
2517 | out | |
2518 | } | |
2519 | } | |
2520 | } | |
2521 | ||
8bb4bdeb XL |
2522 | /// A place for insertion at the back of a `VecDeque`. |
2523 | /// | |
2524 | /// See [`VecDeque::place_back`](struct.VecDeque.html#method.place_back) for details. | |
2525 | #[must_use = "places do nothing unless written to with `<-` syntax"] | |
2526 | #[unstable(feature = "collection_placement", | |
2527 | reason = "struct name and placement protocol are subject to change", | |
2528 | issue = "30172")] | |
2529 | #[derive(Debug)] | |
2530 | pub struct PlaceBack<'a, T: 'a> { | |
2531 | vec_deque: &'a mut VecDeque<T>, | |
2532 | } | |
2533 | ||
2534 | #[unstable(feature = "collection_placement", | |
2535 | reason = "placement protocol is subject to change", | |
2536 | issue = "30172")] | |
2537 | impl<'a, T> Placer<T> for PlaceBack<'a, T> { | |
2538 | type Place = PlaceBack<'a, T>; | |
2539 | ||
2540 | fn make_place(self) -> Self { | |
2541 | self.vec_deque.grow_if_necessary(); | |
2542 | self | |
2543 | } | |
2544 | } | |
2545 | ||
2546 | #[unstable(feature = "collection_placement", | |
2547 | reason = "placement protocol is subject to change", | |
2548 | issue = "30172")] | |
2549 | impl<'a, T> Place<T> for PlaceBack<'a, T> { | |
2550 | fn pointer(&mut self) -> *mut T { | |
2551 | unsafe { self.vec_deque.ptr().offset(self.vec_deque.head as isize) } | |
2552 | } | |
2553 | } | |
2554 | ||
2555 | #[unstable(feature = "collection_placement", | |
2556 | reason = "placement protocol is subject to change", | |
2557 | issue = "30172")] | |
2558 | impl<'a, T> InPlace<T> for PlaceBack<'a, T> { | |
2559 | type Owner = &'a mut T; | |
2560 | ||
2561 | unsafe fn finalize(mut self) -> &'a mut T { | |
2562 | let head = self.vec_deque.head; | |
2563 | self.vec_deque.head = self.vec_deque.wrap_add(head, 1); | |
2564 | &mut *(self.vec_deque.ptr().offset(head as isize)) | |
2565 | } | |
2566 | } | |
2567 | ||
2568 | /// A place for insertion at the front of a `VecDeque`. | |
2569 | /// | |
2570 | /// See [`VecDeque::place_front`](struct.VecDeque.html#method.place_front) for details. | |
2571 | #[must_use = "places do nothing unless written to with `<-` syntax"] | |
2572 | #[unstable(feature = "collection_placement", | |
2573 | reason = "struct name and placement protocol are subject to change", | |
2574 | issue = "30172")] | |
2575 | #[derive(Debug)] | |
2576 | pub struct PlaceFront<'a, T: 'a> { | |
2577 | vec_deque: &'a mut VecDeque<T>, | |
2578 | } | |
2579 | ||
2580 | #[unstable(feature = "collection_placement", | |
2581 | reason = "placement protocol is subject to change", | |
2582 | issue = "30172")] | |
2583 | impl<'a, T> Placer<T> for PlaceFront<'a, T> { | |
2584 | type Place = PlaceFront<'a, T>; | |
2585 | ||
2586 | fn make_place(self) -> Self { | |
2587 | self.vec_deque.grow_if_necessary(); | |
2588 | self | |
2589 | } | |
2590 | } | |
2591 | ||
2592 | #[unstable(feature = "collection_placement", | |
2593 | reason = "placement protocol is subject to change", | |
2594 | issue = "30172")] | |
2595 | impl<'a, T> Place<T> for PlaceFront<'a, T> { | |
2596 | fn pointer(&mut self) -> *mut T { | |
2597 | let tail = self.vec_deque.wrap_sub(self.vec_deque.tail, 1); | |
2598 | unsafe { self.vec_deque.ptr().offset(tail as isize) } | |
2599 | } | |
2600 | } | |
2601 | ||
2602 | #[unstable(feature = "collection_placement", | |
2603 | reason = "placement protocol is subject to change", | |
2604 | issue = "30172")] | |
2605 | impl<'a, T> InPlace<T> for PlaceFront<'a, T> { | |
2606 | type Owner = &'a mut T; | |
2607 | ||
2608 | unsafe fn finalize(mut self) -> &'a mut T { | |
2609 | self.vec_deque.tail = self.vec_deque.wrap_sub(self.vec_deque.tail, 1); | |
2610 | &mut *(self.vec_deque.ptr().offset(self.vec_deque.tail as isize)) | |
2611 | } | |
2612 | } | |
2613 | ||
1a4d82fc | 2614 | #[cfg(test)] |
d9579d0f | 2615 | mod tests { |
1a4d82fc JJ |
2616 | use test; |
2617 | ||
85aaf69f | 2618 | use super::VecDeque; |
1a4d82fc | 2619 | |
1a4d82fc JJ |
2620 | #[bench] |
2621 | fn bench_push_back_100(b: &mut test::Bencher) { | |
85aaf69f | 2622 | let mut deq = VecDeque::with_capacity(101); |
1a4d82fc | 2623 | b.iter(|| { |
85aaf69f | 2624 | for i in 0..100 { |
1a4d82fc JJ |
2625 | deq.push_back(i); |
2626 | } | |
2627 | deq.head = 0; | |
2628 | deq.tail = 0; | |
2629 | }) | |
2630 | } | |
2631 | ||
2632 | #[bench] | |
2633 | fn bench_push_front_100(b: &mut test::Bencher) { | |
85aaf69f | 2634 | let mut deq = VecDeque::with_capacity(101); |
1a4d82fc | 2635 | b.iter(|| { |
85aaf69f | 2636 | for i in 0..100 { |
1a4d82fc JJ |
2637 | deq.push_front(i); |
2638 | } | |
2639 | deq.head = 0; | |
2640 | deq.tail = 0; | |
2641 | }) | |
2642 | } | |
2643 | ||
2644 | #[bench] | |
2645 | fn bench_pop_back_100(b: &mut test::Bencher) { | |
92a42be0 | 2646 | let mut deq = VecDeque::<i32>::with_capacity(101); |
1a4d82fc JJ |
2647 | |
2648 | b.iter(|| { | |
2649 | deq.head = 100; | |
2650 | deq.tail = 0; | |
2651 | while !deq.is_empty() { | |
2652 | test::black_box(deq.pop_back()); | |
2653 | } | |
2654 | }) | |
2655 | } | |
2656 | ||
2657 | #[bench] | |
2658 | fn bench_pop_front_100(b: &mut test::Bencher) { | |
85aaf69f | 2659 | let mut deq = VecDeque::<i32>::with_capacity(101); |
1a4d82fc JJ |
2660 | |
2661 | b.iter(|| { | |
2662 | deq.head = 100; | |
2663 | deq.tail = 0; | |
2664 | while !deq.is_empty() { | |
2665 | test::black_box(deq.pop_front()); | |
2666 | } | |
2667 | }) | |
2668 | } | |
2669 | ||
1a4d82fc JJ |
2670 | #[test] |
2671 | fn test_swap_front_back_remove() { | |
2672 | fn test(back: bool) { | |
2673 | // This test checks that every single combination of tail position and length is tested. | |
2674 | // Capacity 15 should be large enough to cover every case. | |
85aaf69f | 2675 | let mut tester = VecDeque::with_capacity(15); |
1a4d82fc JJ |
2676 | let usable_cap = tester.capacity(); |
2677 | let final_len = usable_cap / 2; | |
2678 | ||
85aaf69f | 2679 | for len in 0..final_len { |
8bb4bdeb | 2680 | let expected: VecDeque<_> = if back { |
85aaf69f | 2681 | (0..len).collect() |
1a4d82fc | 2682 | } else { |
85aaf69f | 2683 | (0..len).rev().collect() |
1a4d82fc | 2684 | }; |
85aaf69f | 2685 | for tail_pos in 0..usable_cap { |
1a4d82fc JJ |
2686 | tester.tail = tail_pos; |
2687 | tester.head = tail_pos; | |
2688 | if back { | |
85aaf69f | 2689 | for i in 0..len * 2 { |
1a4d82fc JJ |
2690 | tester.push_front(i); |
2691 | } | |
85aaf69f | 2692 | for i in 0..len { |
9cc50fc6 | 2693 | assert_eq!(tester.swap_remove_back(i), Some(len * 2 - 1 - i)); |
1a4d82fc JJ |
2694 | } |
2695 | } else { | |
85aaf69f | 2696 | for i in 0..len * 2 { |
1a4d82fc JJ |
2697 | tester.push_back(i); |
2698 | } | |
85aaf69f | 2699 | for i in 0..len { |
1a4d82fc | 2700 | let idx = tester.len() - 1 - i; |
9cc50fc6 | 2701 | assert_eq!(tester.swap_remove_front(idx), Some(len * 2 - 1 - i)); |
1a4d82fc JJ |
2702 | } |
2703 | } | |
c1a9b12d SL |
2704 | assert!(tester.tail < tester.cap()); |
2705 | assert!(tester.head < tester.cap()); | |
1a4d82fc JJ |
2706 | assert_eq!(tester, expected); |
2707 | } | |
2708 | } | |
2709 | } | |
2710 | test(true); | |
2711 | test(false); | |
2712 | } | |
2713 | ||
2714 | #[test] | |
2715 | fn test_insert() { | |
2716 | // This test checks that every single combination of tail position, length, and | |
2717 | // insertion position is tested. Capacity 15 should be large enough to cover every case. | |
2718 | ||
85aaf69f | 2719 | let mut tester = VecDeque::with_capacity(15); |
1a4d82fc JJ |
2720 | // can't guarantee we got 15, so have to get what we got. |
2721 | // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else | |
2722 | // this test isn't covering what it wants to | |
2723 | let cap = tester.capacity(); | |
2724 | ||
2725 | ||
2726 | // len is the length *after* insertion | |
85aaf69f | 2727 | for len in 1..cap { |
1a4d82fc | 2728 | // 0, 1, 2, .., len - 1 |
8bb4bdeb | 2729 | let expected = (0..).take(len).collect::<VecDeque<_>>(); |
85aaf69f SL |
2730 | for tail_pos in 0..cap { |
2731 | for to_insert in 0..len { | |
1a4d82fc JJ |
2732 | tester.tail = tail_pos; |
2733 | tester.head = tail_pos; | |
85aaf69f | 2734 | for i in 0..len { |
1a4d82fc JJ |
2735 | if i != to_insert { |
2736 | tester.push_back(i); | |
2737 | } | |
2738 | } | |
2739 | tester.insert(to_insert, to_insert); | |
c1a9b12d SL |
2740 | assert!(tester.tail < tester.cap()); |
2741 | assert!(tester.head < tester.cap()); | |
1a4d82fc JJ |
2742 | assert_eq!(tester, expected); |
2743 | } | |
2744 | } | |
2745 | } | |
2746 | } | |
2747 | ||
2748 | #[test] | |
2749 | fn test_remove() { | |
2750 | // This test checks that every single combination of tail position, length, and | |
2751 | // removal position is tested. Capacity 15 should be large enough to cover every case. | |
2752 | ||
85aaf69f | 2753 | let mut tester = VecDeque::with_capacity(15); |
1a4d82fc JJ |
2754 | // can't guarantee we got 15, so have to get what we got. |
2755 | // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else | |
2756 | // this test isn't covering what it wants to | |
2757 | let cap = tester.capacity(); | |
2758 | ||
2759 | // len is the length *after* removal | |
85aaf69f | 2760 | for len in 0..cap - 1 { |
1a4d82fc | 2761 | // 0, 1, 2, .., len - 1 |
8bb4bdeb | 2762 | let expected = (0..).take(len).collect::<VecDeque<_>>(); |
85aaf69f SL |
2763 | for tail_pos in 0..cap { |
2764 | for to_remove in 0..len + 1 { | |
1a4d82fc JJ |
2765 | tester.tail = tail_pos; |
2766 | tester.head = tail_pos; | |
85aaf69f | 2767 | for i in 0..len { |
1a4d82fc JJ |
2768 | if i == to_remove { |
2769 | tester.push_back(1234); | |
2770 | } | |
2771 | tester.push_back(i); | |
2772 | } | |
2773 | if to_remove == len { | |
2774 | tester.push_back(1234); | |
2775 | } | |
2776 | tester.remove(to_remove); | |
c1a9b12d SL |
2777 | assert!(tester.tail < tester.cap()); |
2778 | assert!(tester.head < tester.cap()); | |
1a4d82fc JJ |
2779 | assert_eq!(tester, expected); |
2780 | } | |
2781 | } | |
2782 | } | |
2783 | } | |
2784 | ||
b039eaaf SL |
2785 | #[test] |
2786 | fn test_drain() { | |
2787 | let mut tester: VecDeque<usize> = VecDeque::with_capacity(7); | |
2788 | ||
2789 | let cap = tester.capacity(); | |
2790 | for len in 0..cap + 1 { | |
2791 | for tail in 0..cap + 1 { | |
2792 | for drain_start in 0..len + 1 { | |
2793 | for drain_end in drain_start..len + 1 { | |
2794 | tester.tail = tail; | |
2795 | tester.head = tail; | |
2796 | for i in 0..len { | |
2797 | tester.push_back(i); | |
2798 | } | |
2799 | ||
2800 | // Check that we drain the correct values | |
92a42be0 SL |
2801 | let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect(); |
2802 | let drained_expected: VecDeque<_> = (drain_start..drain_end).collect(); | |
b039eaaf SL |
2803 | assert_eq!(drained, drained_expected); |
2804 | ||
2805 | // We shouldn't have changed the capacity or made the | |
2806 | // head or tail out of bounds | |
2807 | assert_eq!(tester.capacity(), cap); | |
2808 | assert!(tester.tail < tester.cap()); | |
2809 | assert!(tester.head < tester.cap()); | |
2810 | ||
2811 | // We should see the correct values in the VecDeque | |
92a42be0 | 2812 | let expected: VecDeque<_> = (0..drain_start) |
32a655c1 SL |
2813 | .chain(drain_end..len) |
2814 | .collect(); | |
b039eaaf SL |
2815 | assert_eq!(expected, tester); |
2816 | } | |
2817 | } | |
2818 | } | |
2819 | } | |
2820 | } | |
2821 | ||
1a4d82fc JJ |
2822 | #[test] |
2823 | fn test_shrink_to_fit() { | |
2824 | // This test checks that every single combination of head and tail position, | |
2825 | // is tested. Capacity 15 should be large enough to cover every case. | |
2826 | ||
85aaf69f | 2827 | let mut tester = VecDeque::with_capacity(15); |
1a4d82fc JJ |
2828 | // can't guarantee we got 15, so have to get what we got. |
2829 | // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else | |
2830 | // this test isn't covering what it wants to | |
2831 | let cap = tester.capacity(); | |
2832 | tester.reserve(63); | |
2833 | let max_cap = tester.capacity(); | |
2834 | ||
85aaf69f | 2835 | for len in 0..cap + 1 { |
1a4d82fc | 2836 | // 0, 1, 2, .., len - 1 |
8bb4bdeb | 2837 | let expected = (0..).take(len).collect::<VecDeque<_>>(); |
85aaf69f | 2838 | for tail_pos in 0..max_cap + 1 { |
1a4d82fc JJ |
2839 | tester.tail = tail_pos; |
2840 | tester.head = tail_pos; | |
2841 | tester.reserve(63); | |
85aaf69f | 2842 | for i in 0..len { |
1a4d82fc JJ |
2843 | tester.push_back(i); |
2844 | } | |
2845 | tester.shrink_to_fit(); | |
2846 | assert!(tester.capacity() <= cap); | |
c1a9b12d SL |
2847 | assert!(tester.tail < tester.cap()); |
2848 | assert!(tester.head < tester.cap()); | |
1a4d82fc JJ |
2849 | assert_eq!(tester, expected); |
2850 | } | |
2851 | } | |
2852 | } | |
2853 | ||
85aaf69f SL |
2854 | #[test] |
2855 | fn test_split_off() { | |
2856 | // This test checks that every single combination of tail position, length, and | |
2857 | // split position is tested. Capacity 15 should be large enough to cover every case. | |
2858 | ||
2859 | let mut tester = VecDeque::with_capacity(15); | |
2860 | // can't guarantee we got 15, so have to get what we got. | |
2861 | // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else | |
2862 | // this test isn't covering what it wants to | |
2863 | let cap = tester.capacity(); | |
2864 | ||
2865 | // len is the length *before* splitting | |
2866 | for len in 0..cap { | |
2867 | // index to split at | |
2868 | for at in 0..len + 1 { | |
2869 | // 0, 1, 2, .., at - 1 (may be empty) | |
8bb4bdeb | 2870 | let expected_self = (0..).take(at).collect::<VecDeque<_>>(); |
85aaf69f | 2871 | // at, at + 1, .., len - 1 (may be empty) |
8bb4bdeb | 2872 | let expected_other = (at..).take(len - at).collect::<VecDeque<_>>(); |
85aaf69f SL |
2873 | |
2874 | for tail_pos in 0..cap { | |
2875 | tester.tail = tail_pos; | |
2876 | tester.head = tail_pos; | |
2877 | for i in 0..len { | |
2878 | tester.push_back(i); | |
2879 | } | |
2880 | let result = tester.split_off(at); | |
c1a9b12d SL |
2881 | assert!(tester.tail < tester.cap()); |
2882 | assert!(tester.head < tester.cap()); | |
2883 | assert!(result.tail < result.cap()); | |
2884 | assert!(result.head < result.cap()); | |
85aaf69f SL |
2885 | assert_eq!(tester, expected_self); |
2886 | assert_eq!(result, expected_other); | |
2887 | } | |
2888 | } | |
2889 | } | |
2890 | } | |
a7813a04 XL |
2891 | |
2892 | #[test] | |
2893 | fn test_from_vec() { | |
2894 | use super::super::vec::Vec; | |
2895 | for cap in 0..35 { | |
2896 | for len in 0..cap + 1 { | |
2897 | let mut vec = Vec::with_capacity(cap); | |
2898 | vec.extend(0..len); | |
2899 | ||
2900 | let vd = VecDeque::from(vec.clone()); | |
2901 | assert!(vd.cap().is_power_of_two()); | |
2902 | assert_eq!(vd.len(), vec.len()); | |
2903 | assert!(vd.into_iter().eq(vec)); | |
2904 | } | |
2905 | } | |
2906 | } | |
2907 | ||
2908 | #[test] | |
2909 | fn test_vec_from_vecdeque() { | |
2910 | use super::super::vec::Vec; | |
2911 | ||
2912 | fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) { | |
2913 | let mut vd = VecDeque::with_capacity(cap); | |
2914 | for _ in 0..offset { | |
2915 | vd.push_back(0); | |
2916 | vd.pop_front(); | |
2917 | } | |
2918 | vd.extend(0..len); | |
2919 | ||
2920 | let vec: Vec<_> = Vec::from(vd.clone()); | |
2921 | assert_eq!(vec.len(), vd.len()); | |
2922 | assert!(vec.into_iter().eq(vd)); | |
2923 | } | |
2924 | ||
2925 | for cap_pwr in 0..7 { | |
2926 | // Make capacity as a (2^x)-1, so that the ring size is 2^x | |
2927 | let cap = (2i32.pow(cap_pwr) - 1) as usize; | |
2928 | ||
2929 | // In these cases there is enough free space to solve it with copies | |
32a655c1 | 2930 | for len in 0..((cap + 1) / 2) { |
a7813a04 | 2931 | // Test contiguous cases |
32a655c1 | 2932 | for offset in 0..(cap - len) { |
a7813a04 XL |
2933 | create_vec_and_test_convert(cap, offset, len) |
2934 | } | |
2935 | ||
2936 | // Test cases where block at end of buffer is bigger than block at start | |
32a655c1 | 2937 | for offset in (cap - len)..(cap - (len / 2)) { |
a7813a04 XL |
2938 | create_vec_and_test_convert(cap, offset, len) |
2939 | } | |
2940 | ||
2941 | // Test cases where block at start of buffer is bigger than block at end | |
32a655c1 | 2942 | for offset in (cap - (len / 2))..cap { |
a7813a04 XL |
2943 | create_vec_and_test_convert(cap, offset, len) |
2944 | } | |
2945 | } | |
2946 | ||
2947 | // Now there's not (necessarily) space to straighten the ring with simple copies, | |
2948 | // the ring will use swapping when: | |
2949 | // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len)) | |
2950 | // right block size > free space && left block size > free space | |
32a655c1 | 2951 | for len in ((cap + 1) / 2)..cap { |
a7813a04 | 2952 | // Test contiguous cases |
32a655c1 | 2953 | for offset in 0..(cap - len) { |
a7813a04 XL |
2954 | create_vec_and_test_convert(cap, offset, len) |
2955 | } | |
2956 | ||
2957 | // Test cases where block at end of buffer is bigger than block at start | |
32a655c1 | 2958 | for offset in (cap - len)..(cap - (len / 2)) { |
a7813a04 XL |
2959 | create_vec_and_test_convert(cap, offset, len) |
2960 | } | |
2961 | ||
2962 | // Test cases where block at start of buffer is bigger than block at end | |
32a655c1 | 2963 | for offset in (cap - (len / 2))..cap { |
a7813a04 XL |
2964 | create_vec_and_test_convert(cap, offset, len) |
2965 | } | |
2966 | } | |
2967 | } | |
2968 | } | |
8bb4bdeb | 2969 | |
1a4d82fc | 2970 | } |