]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
1 | // Copyright 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 | ||
7453a54e SL |
11 | //! A contiguous growable array type with heap-allocated contents, written |
12 | //! `Vec<T>` but pronounced 'vector.' | |
1a4d82fc | 13 | //! |
62682a34 SL |
14 | //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and |
15 | //! `O(1)` pop (from the end). | |
1a4d82fc JJ |
16 | //! |
17 | //! # Examples | |
18 | //! | |
c30ab7b3 | 19 | //! You can explicitly create a [`Vec<T>`] with [`new()`]: |
1a4d82fc JJ |
20 | //! |
21 | //! ``` | |
d9579d0f | 22 | //! let v: Vec<i32> = Vec::new(); |
1a4d82fc JJ |
23 | //! ``` |
24 | //! | |
c30ab7b3 | 25 | //! ...or by using the [`vec!`] macro: |
1a4d82fc JJ |
26 | //! |
27 | //! ``` | |
d9579d0f | 28 | //! let v: Vec<i32> = vec![]; |
1a4d82fc | 29 | //! |
d9579d0f AL |
30 | //! let v = vec![1, 2, 3, 4, 5]; |
31 | //! | |
32 | //! let v = vec![0; 10]; // ten zeroes | |
1a4d82fc JJ |
33 | //! ``` |
34 | //! | |
c30ab7b3 | 35 | //! You can [`push`] values onto the end of a vector (which will grow the vector |
e9174d1e | 36 | //! as needed): |
1a4d82fc JJ |
37 | //! |
38 | //! ``` | |
d9579d0f | 39 | //! let mut v = vec![1, 2]; |
1a4d82fc | 40 | //! |
d9579d0f | 41 | //! v.push(3); |
1a4d82fc JJ |
42 | //! ``` |
43 | //! | |
d9579d0f AL |
44 | //! Popping values works in much the same way: |
45 | //! | |
46 | //! ``` | |
47 | //! let mut v = vec![1, 2]; | |
1a4d82fc | 48 | //! |
d9579d0f | 49 | //! let two = v.pop(); |
1a4d82fc | 50 | //! ``` |
1a4d82fc | 51 | //! |
c30ab7b3 | 52 | //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits): |
d9579d0f AL |
53 | //! |
54 | //! ``` | |
55 | //! let mut v = vec![1, 2, 3]; | |
56 | //! let three = v[2]; | |
57 | //! v[1] = v[1] + 5; | |
1a4d82fc | 58 | //! ``` |
c30ab7b3 SL |
59 | //! |
60 | //! [`Vec<T>`]: ../../std/vec/struct.Vec.html | |
61 | //! [`new()`]: ../../std/vec/struct.Vec.html#method.new | |
62 | //! [`push`]: ../../std/vec/struct.Vec.html#method.push | |
63 | //! [`Index`]: ../../std/ops/trait.Index.html | |
64 | //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html | |
65 | //! [`vec!`]: ../../std/macro.vec.html | |
1a4d82fc | 66 | |
85aaf69f | 67 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 68 | |
1a4d82fc | 69 | use alloc::boxed::Box; |
c1a9b12d | 70 | use alloc::heap::EMPTY; |
7453a54e SL |
71 | use alloc::raw_vec::RawVec; |
72 | use borrow::ToOwned; | |
54a0048b | 73 | use borrow::Cow; |
c34b1796 | 74 | use core::cmp::Ordering; |
1a4d82fc JJ |
75 | use core::fmt; |
76 | use core::hash::{self, Hash}; | |
54a0048b | 77 | use core::intrinsics::{arith_offset, assume}; |
c30ab7b3 | 78 | use core::iter::{FromIterator, FusedIterator, TrustedLen}; |
1a4d82fc | 79 | use core::mem; |
9cc50fc6 | 80 | use core::ops::{Index, IndexMut}; |
1a4d82fc JJ |
81 | use core::ops; |
82 | use core::ptr; | |
5bcae85e | 83 | use core::ptr::Shared; |
85aaf69f | 84 | use core::slice; |
85aaf69f | 85 | |
d9579d0f AL |
86 | use super::range::RangeArgument; |
87 | ||
c30ab7b3 | 88 | /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'. |
1a4d82fc JJ |
89 | /// |
90 | /// # Examples | |
91 | /// | |
92 | /// ``` | |
93 | /// let mut vec = Vec::new(); | |
85aaf69f SL |
94 | /// vec.push(1); |
95 | /// vec.push(2); | |
1a4d82fc JJ |
96 | /// |
97 | /// assert_eq!(vec.len(), 2); | |
98 | /// assert_eq!(vec[0], 1); | |
99 | /// | |
100 | /// assert_eq!(vec.pop(), Some(2)); | |
101 | /// assert_eq!(vec.len(), 1); | |
102 | /// | |
85aaf69f | 103 | /// vec[0] = 7; |
1a4d82fc JJ |
104 | /// assert_eq!(vec[0], 7); |
105 | /// | |
62682a34 | 106 | /// vec.extend([1, 2, 3].iter().cloned()); |
1a4d82fc | 107 | /// |
62682a34 | 108 | /// for x in &vec { |
1a4d82fc JJ |
109 | /// println!("{}", x); |
110 | /// } | |
c34b1796 | 111 | /// assert_eq!(vec, [7, 1, 2, 3]); |
1a4d82fc JJ |
112 | /// ``` |
113 | /// | |
c30ab7b3 | 114 | /// The [`vec!`] macro is provided to make initialization more convenient: |
1a4d82fc JJ |
115 | /// |
116 | /// ``` | |
85aaf69f | 117 | /// let mut vec = vec![1, 2, 3]; |
1a4d82fc | 118 | /// vec.push(4); |
c34b1796 | 119 | /// assert_eq!(vec, [1, 2, 3, 4]); |
1a4d82fc JJ |
120 | /// ``` |
121 | /// | |
c1a9b12d SL |
122 | /// It can also initialize each element of a `Vec<T>` with a given value: |
123 | /// | |
124 | /// ``` | |
125 | /// let vec = vec![0; 5]; | |
126 | /// assert_eq!(vec, [0, 0, 0, 0, 0]); | |
127 | /// ``` | |
128 | /// | |
1a4d82fc JJ |
129 | /// Use a `Vec<T>` as an efficient stack: |
130 | /// | |
131 | /// ``` | |
132 | /// let mut stack = Vec::new(); | |
133 | /// | |
85aaf69f SL |
134 | /// stack.push(1); |
135 | /// stack.push(2); | |
136 | /// stack.push(3); | |
1a4d82fc | 137 | /// |
bd371182 | 138 | /// while let Some(top) = stack.pop() { |
1a4d82fc JJ |
139 | /// // Prints 3, 2, 1 |
140 | /// println!("{}", top); | |
141 | /// } | |
142 | /// ``` | |
143 | /// | |
7453a54e SL |
144 | /// # Indexing |
145 | /// | |
c30ab7b3 SL |
146 | /// The `Vec` type allows to access values by index, because it implements the |
147 | /// [`Index`] trait. An example will be more explicit: | |
7453a54e SL |
148 | /// |
149 | /// ``` | |
c30ab7b3 | 150 | /// let v = vec![0, 2, 4, 6]; |
7453a54e SL |
151 | /// println!("{}", v[1]); // it will display '2' |
152 | /// ``` | |
153 | /// | |
c30ab7b3 | 154 | /// However be careful: if you try to access an index which isn't in the `Vec`, |
7453a54e SL |
155 | /// your software will panic! You cannot do this: |
156 | /// | |
157 | /// ```ignore | |
c30ab7b3 | 158 | /// let v = vec![0, 2, 4, 6]; |
7453a54e SL |
159 | /// println!("{}", v[6]); // it will panic! |
160 | /// ``` | |
161 | /// | |
162 | /// In conclusion: always check if the index you want to get really exists | |
163 | /// before doing it. | |
164 | /// | |
165 | /// # Slicing | |
166 | /// | |
c30ab7b3 SL |
167 | /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects. |
168 | /// To get a slice, use `&`. Example: | |
7453a54e SL |
169 | /// |
170 | /// ``` | |
171 | /// fn read_slice(slice: &[usize]) { | |
172 | /// // ... | |
173 | /// } | |
174 | /// | |
c30ab7b3 | 175 | /// let v = vec![0, 1]; |
7453a54e SL |
176 | /// read_slice(&v); |
177 | /// | |
178 | /// // ... and that's all! | |
179 | /// // you can also do it like this: | |
180 | /// let x : &[usize] = &v; | |
181 | /// ``` | |
182 | /// | |
183 | /// In Rust, it's more common to pass slices as arguments rather than vectors | |
c30ab7b3 SL |
184 | /// when you just want to provide a read access. The same goes for [`String`] and |
185 | /// [`&str`]. | |
7453a54e | 186 | /// |
1a4d82fc JJ |
187 | /// # Capacity and reallocation |
188 | /// | |
c34b1796 AL |
189 | /// The capacity of a vector is the amount of space allocated for any future |
190 | /// elements that will be added onto the vector. This is not to be confused with | |
191 | /// the *length* of a vector, which specifies the number of actual elements | |
192 | /// within the vector. If a vector's length exceeds its capacity, its capacity | |
193 | /// will automatically be increased, but its elements will have to be | |
1a4d82fc JJ |
194 | /// reallocated. |
195 | /// | |
c34b1796 AL |
196 | /// For example, a vector with capacity 10 and length 0 would be an empty vector |
197 | /// with space for 10 more elements. Pushing 10 or fewer elements onto the | |
198 | /// vector will not change its capacity or cause reallocation to occur. However, | |
199 | /// if the vector's length is increased to 11, it will have to reallocate, which | |
c30ab7b3 | 200 | /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`] |
c34b1796 | 201 | /// whenever possible to specify how big the vector is expected to get. |
b039eaaf SL |
202 | /// |
203 | /// # Guarantees | |
204 | /// | |
c30ab7b3 | 205 | /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees |
b039eaaf SL |
206 | /// about its design. This ensures that it's as low-overhead as possible in |
207 | /// the general case, and can be correctly manipulated in primitive ways | |
208 | /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`. | |
209 | /// If additional type parameters are added (e.g. to support custom allocators), | |
210 | /// overriding their defaults may change the behavior. | |
211 | /// | |
c30ab7b3 | 212 | /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length) |
b039eaaf SL |
213 | /// triplet. No more, no less. The order of these fields is completely |
214 | /// unspecified, and you should use the appropriate methods to modify these. | |
215 | /// The pointer will never be null, so this type is null-pointer-optimized. | |
216 | /// | |
217 | /// However, the pointer may not actually point to allocated memory. In particular, | |
c30ab7b3 SL |
218 | /// if you construct a `Vec` with capacity 0 via [`Vec::new()`], [`vec![]`][`vec!`], |
219 | /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit()`] | |
220 | /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized | |
221 | /// types inside a `Vec`, it will not allocate space for them. *Note that in this case | |
222 | /// the `Vec` may not report a [`capacity()`] of 0*. `Vec` will allocate if and only | |
223 | /// if [`mem::size_of::<T>()`]` * capacity() > 0`. In general, `Vec`'s allocation | |
b039eaaf | 224 | /// details are subtle enough that it is strongly recommended that you only |
c30ab7b3 | 225 | /// free memory allocated by a `Vec` by creating a new `Vec` and dropping it. |
b039eaaf | 226 | /// |
c30ab7b3 | 227 | /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap |
b039eaaf | 228 | /// (as defined by the allocator Rust is configured to use by default), and its |
c30ab7b3 SL |
229 | /// pointer points to [`len()`] initialized elements in order (what you would see |
230 | /// if you coerced it to a slice), followed by [`capacity()`]` - `[`len()`] | |
231 | /// logically uninitialized elements. | |
b039eaaf | 232 | /// |
c30ab7b3 | 233 | /// `Vec` will never perform a "small optimization" where elements are actually |
b039eaaf SL |
234 | /// stored on the stack for two reasons: |
235 | /// | |
236 | /// * It would make it more difficult for unsafe code to correctly manipulate | |
c30ab7b3 SL |
237 | /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were |
238 | /// only moved, and it would be more difficult to determine if a `Vec` had | |
b039eaaf SL |
239 | /// actually allocated memory. |
240 | /// | |
241 | /// * It would penalize the general case, incurring an additional branch | |
242 | /// on every access. | |
243 | /// | |
c30ab7b3 SL |
244 | /// `Vec` will never automatically shrink itself, even if completely empty. This |
245 | /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec` | |
246 | /// and then filling it back up to the same [`len()`] should incur no calls to | |
247 | /// the allocator. If you wish to free up unused memory, use | |
248 | /// [`shrink_to_fit`][`shrink_to_fit()`]. | |
b039eaaf | 249 | /// |
c30ab7b3 SL |
250 | /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is |
251 | /// sufficient. [`push`] and [`insert`] *will* (re)allocate if | |
252 | /// [`len()`]` == `[`capacity()`]. That is, the reported capacity is completely | |
253 | /// accurate, and can be relied on. It can even be used to manually free the memory | |
254 | /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even | |
255 | /// when not necessary. | |
b039eaaf | 256 | /// |
c30ab7b3 SL |
257 | /// `Vec` does not guarantee any particular growth strategy when reallocating |
258 | /// when full, nor when [`reserve`] is called. The current strategy is basic | |
b039eaaf | 259 | /// and it may prove desirable to use a non-constant growth factor. Whatever |
c30ab7b3 | 260 | /// strategy is used will of course guarantee `O(1)` amortized [`push`]. |
b039eaaf | 261 | /// |
c30ab7b3 SL |
262 | /// `vec![x; n]`, `vec![a, b, c, d]`, and |
263 | /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec` | |
264 | /// with exactly the requested capacity. If [`len()`]` == `[`capacity()`], | |
265 | /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to | |
266 | /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements. | |
b039eaaf | 267 | /// |
c30ab7b3 | 268 | /// `Vec` will not specifically overwrite any data that is removed from it, |
b039eaaf SL |
269 | /// but also won't specifically preserve it. Its uninitialized memory is |
270 | /// scratch space that it may use however it wants. It will generally just do | |
271 | /// whatever is most efficient or otherwise easy to implement. Do not rely on | |
c30ab7b3 SL |
272 | /// removed data to be erased for security purposes. Even if you drop a `Vec`, its |
273 | /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory | |
b039eaaf SL |
274 | /// first, that may not actually happen because the optimizer does not consider |
275 | /// this a side-effect that must be preserved. | |
276 | /// | |
c30ab7b3 | 277 | /// `Vec` does not currently guarantee the order in which elements are dropped |
b039eaaf SL |
278 | /// (the order has changed in the past, and may change again). |
279 | /// | |
c30ab7b3 SL |
280 | /// [`vec!`]: ../../std/macro.vec.html |
281 | /// [`Index`]: ../../std/ops/trait.Index.html | |
282 | /// [`String`]: ../../std/string/struct.String.html | |
283 | /// [`&str`]: ../../std/primitive.str.html | |
284 | /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity | |
285 | /// [`Vec::new()`]: ../../std/vec/struct.Vec.html#method.new | |
286 | /// [`shrink_to_fit()`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit | |
287 | /// [`capacity()`]: ../../std/vec/struct.Vec.html#method.capacity | |
288 | /// [`mem::size_of::<T>()`]: ../../std/mem/fn.size_of.html | |
289 | /// [`len()`]: ../../std/vec/struct.Vec.html#method.len | |
290 | /// [`push`]: ../../std/vec/struct.Vec.html#method.push | |
291 | /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert | |
292 | /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve | |
293 | /// [owned slice]: ../../std/boxed/struct.Box.html | |
85aaf69f | 294 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 295 | pub struct Vec<T> { |
c1a9b12d | 296 | buf: RawVec<T>, |
85aaf69f | 297 | len: usize, |
1a4d82fc JJ |
298 | } |
299 | ||
1a4d82fc JJ |
300 | //////////////////////////////////////////////////////////////////////////////// |
301 | // Inherent methods | |
302 | //////////////////////////////////////////////////////////////////////////////// | |
303 | ||
304 | impl<T> Vec<T> { | |
305 | /// Constructs a new, empty `Vec<T>`. | |
306 | /// | |
307 | /// The vector will not allocate until elements are pushed onto it. | |
308 | /// | |
309 | /// # Examples | |
310 | /// | |
311 | /// ``` | |
92a42be0 | 312 | /// # #![allow(unused_mut)] |
85aaf69f | 313 | /// let mut vec: Vec<i32> = Vec::new(); |
1a4d82fc JJ |
314 | /// ``` |
315 | #[inline] | |
85aaf69f | 316 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 317 | pub fn new() -> Vec<T> { |
92a42be0 SL |
318 | Vec { |
319 | buf: RawVec::new(), | |
320 | len: 0, | |
321 | } | |
1a4d82fc JJ |
322 | } |
323 | ||
324 | /// Constructs a new, empty `Vec<T>` with the specified capacity. | |
325 | /// | |
e9174d1e SL |
326 | /// The vector will be able to hold exactly `capacity` elements without |
327 | /// reallocating. If `capacity` is 0, the vector will not allocate. | |
1a4d82fc | 328 | /// |
e9174d1e | 329 | /// It is important to note that this function does not specify the *length* |
c30ab7b3 SL |
330 | /// of the returned vector, but only the *capacity*. For an explanation of |
331 | /// the difference between length and capacity, see *[Capacity and reallocation]*. | |
332 | /// | |
333 | /// [Capacity and reallocation]: #capacity-and-reallocation | |
1a4d82fc JJ |
334 | /// |
335 | /// # Examples | |
336 | /// | |
337 | /// ``` | |
9346a6ac | 338 | /// let mut vec = Vec::with_capacity(10); |
1a4d82fc JJ |
339 | /// |
340 | /// // The vector contains no items, even though it has capacity for more | |
341 | /// assert_eq!(vec.len(), 0); | |
342 | /// | |
343 | /// // These are all done without reallocating... | |
85aaf69f | 344 | /// for i in 0..10 { |
1a4d82fc JJ |
345 | /// vec.push(i); |
346 | /// } | |
347 | /// | |
348 | /// // ...but this may make the vector reallocate | |
349 | /// vec.push(11); | |
350 | /// ``` | |
351 | #[inline] | |
85aaf69f SL |
352 | #[stable(feature = "rust1", since = "1.0.0")] |
353 | pub fn with_capacity(capacity: usize) -> Vec<T> { | |
92a42be0 SL |
354 | Vec { |
355 | buf: RawVec::with_capacity(capacity), | |
356 | len: 0, | |
357 | } | |
1a4d82fc JJ |
358 | } |
359 | ||
360 | /// Creates a `Vec<T>` directly from the raw components of another vector. | |
361 | /// | |
b039eaaf | 362 | /// # Safety |
c1a9b12d SL |
363 | /// |
364 | /// This is highly unsafe, due to the number of invariants that aren't | |
365 | /// checked: | |
366 | /// | |
c30ab7b3 | 367 | /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>` |
c1a9b12d | 368 | /// (at least, it's highly likely to be incorrect if it wasn't). |
5bcae85e | 369 | /// * `length` needs to be less than or equal to `capacity`. |
c1a9b12d SL |
370 | /// * `capacity` needs to be the capacity that the pointer was allocated with. |
371 | /// | |
372 | /// Violating these may cause problems like corrupting the allocator's | |
373 | /// internal datastructures. | |
1a4d82fc | 374 | /// |
5bcae85e SL |
375 | /// The ownership of `ptr` is effectively transferred to the |
376 | /// `Vec<T>` which may then deallocate, reallocate or change the | |
377 | /// contents of memory pointed to by the pointer at will. Ensure | |
378 | /// that nothing else uses the pointer after calling this | |
379 | /// function. | |
380 | /// | |
c30ab7b3 SL |
381 | /// [`String`]: ../../std/string/struct.String.html |
382 | /// | |
1a4d82fc JJ |
383 | /// # Examples |
384 | /// | |
385 | /// ``` | |
386 | /// use std::ptr; | |
387 | /// use std::mem; | |
388 | /// | |
389 | /// fn main() { | |
85aaf69f | 390 | /// let mut v = vec![1, 2, 3]; |
1a4d82fc JJ |
391 | /// |
392 | /// // Pull out the various important pieces of information about `v` | |
393 | /// let p = v.as_mut_ptr(); | |
394 | /// let len = v.len(); | |
395 | /// let cap = v.capacity(); | |
396 | /// | |
397 | /// unsafe { | |
398 | /// // Cast `v` into the void: no destructor run, so we are in | |
399 | /// // complete control of the allocation to which `p` points. | |
400 | /// mem::forget(v); | |
401 | /// | |
402 | /// // Overwrite memory with 4, 5, 6 | |
85aaf69f | 403 | /// for i in 0..len as isize { |
1a4d82fc JJ |
404 | /// ptr::write(p.offset(i), 4 + i); |
405 | /// } | |
406 | /// | |
407 | /// // Put everything back together into a Vec | |
408 | /// let rebuilt = Vec::from_raw_parts(p, len, cap); | |
c34b1796 | 409 | /// assert_eq!(rebuilt, [4, 5, 6]); |
1a4d82fc JJ |
410 | /// } |
411 | /// } | |
412 | /// ``` | |
85aaf69f | 413 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 414 | pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> { |
85aaf69f | 415 | Vec { |
c1a9b12d | 416 | buf: RawVec::from_raw_parts(ptr, capacity), |
85aaf69f | 417 | len: length, |
85aaf69f | 418 | } |
1a4d82fc JJ |
419 | } |
420 | ||
1a4d82fc JJ |
421 | /// Returns the number of elements the vector can hold without |
422 | /// reallocating. | |
423 | /// | |
424 | /// # Examples | |
425 | /// | |
426 | /// ``` | |
85aaf69f | 427 | /// let vec: Vec<i32> = Vec::with_capacity(10); |
1a4d82fc JJ |
428 | /// assert_eq!(vec.capacity(), 10); |
429 | /// ``` | |
430 | #[inline] | |
85aaf69f SL |
431 | #[stable(feature = "rust1", since = "1.0.0")] |
432 | pub fn capacity(&self) -> usize { | |
c1a9b12d | 433 | self.buf.cap() |
1a4d82fc JJ |
434 | } |
435 | ||
c34b1796 AL |
436 | /// Reserves capacity for at least `additional` more elements to be inserted |
437 | /// in the given `Vec<T>`. The collection may reserve more space to avoid | |
438 | /// frequent reallocations. | |
1a4d82fc JJ |
439 | /// |
440 | /// # Panics | |
441 | /// | |
85aaf69f | 442 | /// Panics if the new capacity overflows `usize`. |
1a4d82fc JJ |
443 | /// |
444 | /// # Examples | |
445 | /// | |
446 | /// ``` | |
85aaf69f | 447 | /// let mut vec = vec![1]; |
1a4d82fc JJ |
448 | /// vec.reserve(10); |
449 | /// assert!(vec.capacity() >= 11); | |
450 | /// ``` | |
85aaf69f SL |
451 | #[stable(feature = "rust1", since = "1.0.0")] |
452 | pub fn reserve(&mut self, additional: usize) { | |
c1a9b12d | 453 | self.buf.reserve(self.len, additional); |
1a4d82fc JJ |
454 | } |
455 | ||
456 | /// Reserves the minimum capacity for exactly `additional` more elements to | |
457 | /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already | |
458 | /// sufficient. | |
459 | /// | |
460 | /// Note that the allocator may give the collection more space than it | |
461 | /// requests. Therefore capacity can not be relied upon to be precisely | |
462 | /// minimal. Prefer `reserve` if future insertions are expected. | |
463 | /// | |
464 | /// # Panics | |
465 | /// | |
85aaf69f | 466 | /// Panics if the new capacity overflows `usize`. |
1a4d82fc JJ |
467 | /// |
468 | /// # Examples | |
469 | /// | |
470 | /// ``` | |
85aaf69f | 471 | /// let mut vec = vec![1]; |
1a4d82fc JJ |
472 | /// vec.reserve_exact(10); |
473 | /// assert!(vec.capacity() >= 11); | |
474 | /// ``` | |
85aaf69f SL |
475 | #[stable(feature = "rust1", since = "1.0.0")] |
476 | pub fn reserve_exact(&mut self, additional: usize) { | |
c1a9b12d | 477 | self.buf.reserve_exact(self.len, additional); |
1a4d82fc JJ |
478 | } |
479 | ||
480 | /// Shrinks the capacity of the vector as much as possible. | |
481 | /// | |
482 | /// It will drop down as close as possible to the length but the allocator | |
483 | /// may still inform the vector that there is space for a few more elements. | |
484 | /// | |
485 | /// # Examples | |
486 | /// | |
487 | /// ``` | |
85aaf69f | 488 | /// let mut vec = Vec::with_capacity(10); |
62682a34 | 489 | /// vec.extend([1, 2, 3].iter().cloned()); |
1a4d82fc JJ |
490 | /// assert_eq!(vec.capacity(), 10); |
491 | /// vec.shrink_to_fit(); | |
492 | /// assert!(vec.capacity() >= 3); | |
493 | /// ``` | |
85aaf69f | 494 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 495 | pub fn shrink_to_fit(&mut self) { |
c1a9b12d | 496 | self.buf.shrink_to_fit(self.len); |
1a4d82fc JJ |
497 | } |
498 | ||
c30ab7b3 | 499 | /// Converts the vector into [`Box<[T]>`][owned slice]. |
1a4d82fc JJ |
500 | /// |
501 | /// Note that this will drop any excess capacity. Calling this and | |
c30ab7b3 SL |
502 | /// converting back to a vector with [`into_vec()`] is equivalent to calling |
503 | /// [`shrink_to_fit()`]. | |
504 | /// | |
505 | /// [owned slice]: ../../std/boxed/struct.Box.html | |
506 | /// [`into_vec()`]: ../../std/primitive.slice.html#method.into_vec | |
507 | /// [`shrink_to_fit()`]: #method.shrink_to_fit | |
5bcae85e SL |
508 | /// |
509 | /// # Examples | |
510 | /// | |
511 | /// ``` | |
512 | /// let v = vec![1, 2, 3]; | |
513 | /// | |
514 | /// let slice = v.into_boxed_slice(); | |
515 | /// ``` | |
516 | /// | |
517 | /// Any excess capacity is removed: | |
518 | /// | |
519 | /// ``` | |
520 | /// let mut vec = Vec::with_capacity(10); | |
521 | /// vec.extend([1, 2, 3].iter().cloned()); | |
522 | /// | |
523 | /// assert_eq!(vec.capacity(), 10); | |
524 | /// let slice = vec.into_boxed_slice(); | |
525 | /// assert_eq!(slice.into_vec().capacity(), 3); | |
526 | /// ``` | |
c34b1796 | 527 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 528 | pub fn into_boxed_slice(mut self) -> Box<[T]> { |
1a4d82fc | 529 | unsafe { |
c1a9b12d SL |
530 | self.shrink_to_fit(); |
531 | let buf = ptr::read(&self.buf); | |
1a4d82fc | 532 | mem::forget(self); |
c1a9b12d | 533 | buf.into_box() |
1a4d82fc JJ |
534 | } |
535 | } | |
536 | ||
5bcae85e SL |
537 | /// Shortens the vector, keeping the first `len` elements and dropping |
538 | /// the rest. | |
1a4d82fc JJ |
539 | /// |
540 | /// If `len` is greater than the vector's current length, this has no | |
541 | /// effect. | |
542 | /// | |
5bcae85e SL |
543 | /// The [`drain`] method can emulate `truncate`, but causes the excess |
544 | /// elements to be returned instead of dropped. | |
545 | /// | |
1a4d82fc JJ |
546 | /// # Examples |
547 | /// | |
5bcae85e SL |
548 | /// Truncating a five element vector to two elements: |
549 | /// | |
1a4d82fc | 550 | /// ``` |
92a42be0 | 551 | /// let mut vec = vec![1, 2, 3, 4, 5]; |
1a4d82fc | 552 | /// vec.truncate(2); |
c34b1796 | 553 | /// assert_eq!(vec, [1, 2]); |
1a4d82fc | 554 | /// ``` |
5bcae85e SL |
555 | /// |
556 | /// No truncation occurs when `len` is greater than the vector's current | |
557 | /// length: | |
558 | /// | |
559 | /// ``` | |
560 | /// let mut vec = vec![1, 2, 3]; | |
561 | /// vec.truncate(8); | |
562 | /// assert_eq!(vec, [1, 2, 3]); | |
563 | /// ``` | |
564 | /// | |
565 | /// Truncating when `len == 0` is equivalent to calling the [`clear`] | |
566 | /// method. | |
567 | /// | |
568 | /// ``` | |
569 | /// let mut vec = vec![1, 2, 3]; | |
570 | /// vec.truncate(0); | |
571 | /// assert_eq!(vec, []); | |
572 | /// ``` | |
573 | /// | |
574 | /// [`clear`]: #method.clear | |
575 | /// [`drain`]: #method.drain | |
85aaf69f SL |
576 | #[stable(feature = "rust1", since = "1.0.0")] |
577 | pub fn truncate(&mut self, len: usize) { | |
1a4d82fc JJ |
578 | unsafe { |
579 | // drop any extra elements | |
580 | while len < self.len { | |
54a0048b SL |
581 | // decrement len before the drop_in_place(), so a panic on Drop |
582 | // doesn't re-drop the just-failed value. | |
1a4d82fc | 583 | self.len -= 1; |
54a0048b SL |
584 | let len = self.len; |
585 | ptr::drop_in_place(self.get_unchecked_mut(len)); | |
1a4d82fc JJ |
586 | } |
587 | } | |
588 | } | |
589 | ||
9346a6ac | 590 | /// Extracts a slice containing the entire vector. |
62682a34 SL |
591 | /// |
592 | /// Equivalent to `&s[..]`. | |
5bcae85e SL |
593 | /// |
594 | /// # Examples | |
595 | /// | |
596 | /// ``` | |
597 | /// use std::io::{self, Write}; | |
598 | /// let buffer = vec![1, 2, 3, 5, 8]; | |
599 | /// io::sink().write(buffer.as_slice()).unwrap(); | |
600 | /// ``` | |
1a4d82fc | 601 | #[inline] |
9cc50fc6 | 602 | #[stable(feature = "vec_as_slice", since = "1.7.0")] |
c34b1796 AL |
603 | pub fn as_slice(&self) -> &[T] { |
604 | self | |
605 | } | |
606 | ||
62682a34 SL |
607 | /// Extracts a mutable slice of the entire vector. |
608 | /// | |
609 | /// Equivalent to `&mut s[..]`. | |
5bcae85e SL |
610 | /// |
611 | /// # Examples | |
612 | /// | |
613 | /// ``` | |
614 | /// use std::io::{self, Read}; | |
615 | /// let mut buffer = vec![0; 3]; | |
616 | /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); | |
617 | /// ``` | |
c34b1796 | 618 | #[inline] |
9cc50fc6 | 619 | #[stable(feature = "vec_as_slice", since = "1.7.0")] |
85aaf69f | 620 | pub fn as_mut_slice(&mut self) -> &mut [T] { |
5bcae85e | 621 | self |
1a4d82fc JJ |
622 | } |
623 | ||
1a4d82fc JJ |
624 | /// Sets the length of a vector. |
625 | /// | |
626 | /// This will explicitly set the size of the vector, without actually | |
627 | /// modifying its buffers, so it is up to the caller to ensure that the | |
628 | /// vector is actually the specified size. | |
629 | /// | |
630 | /// # Examples | |
631 | /// | |
632 | /// ``` | |
5bcae85e SL |
633 | /// use std::ptr; |
634 | /// | |
635 | /// let mut vec = vec!['r', 'u', 's', 't']; | |
636 | /// | |
637 | /// unsafe { | |
638 | /// ptr::drop_in_place(&mut vec[3]); | |
639 | /// vec.set_len(3); | |
640 | /// } | |
641 | /// assert_eq!(vec, ['r', 'u', 's']); | |
642 | /// ``` | |
643 | /// | |
644 | /// In this example, there is a memory leak since the memory locations | |
645 | /// owned by the inner vectors were not freed prior to the `set_len` call: | |
646 | /// | |
647 | /// ``` | |
648 | /// let mut vec = vec![vec![1, 0, 0], | |
649 | /// vec![0, 1, 0], | |
650 | /// vec![0, 0, 1]]; | |
1a4d82fc | 651 | /// unsafe { |
5bcae85e SL |
652 | /// vec.set_len(0); |
653 | /// } | |
654 | /// ``` | |
655 | /// | |
656 | /// In this example, the vector gets expanded from zero to four items | |
657 | /// without any memory allocations occurring, resulting in vector | |
658 | /// values of unallocated memory: | |
659 | /// | |
660 | /// ``` | |
661 | /// let mut vec: Vec<char> = Vec::new(); | |
662 | /// | |
663 | /// unsafe { | |
664 | /// vec.set_len(4); | |
1a4d82fc JJ |
665 | /// } |
666 | /// ``` | |
667 | #[inline] | |
85aaf69f SL |
668 | #[stable(feature = "rust1", since = "1.0.0")] |
669 | pub unsafe fn set_len(&mut self, len: usize) { | |
1a4d82fc JJ |
670 | self.len = len; |
671 | } | |
672 | ||
673 | /// Removes an element from anywhere in the vector and return it, replacing | |
674 | /// it with the last element. | |
675 | /// | |
676 | /// This does not preserve ordering, but is O(1). | |
677 | /// | |
678 | /// # Panics | |
679 | /// | |
680 | /// Panics if `index` is out of bounds. | |
681 | /// | |
682 | /// # Examples | |
683 | /// | |
684 | /// ``` | |
685 | /// let mut v = vec!["foo", "bar", "baz", "qux"]; | |
686 | /// | |
687 | /// assert_eq!(v.swap_remove(1), "bar"); | |
c34b1796 | 688 | /// assert_eq!(v, ["foo", "qux", "baz"]); |
1a4d82fc JJ |
689 | /// |
690 | /// assert_eq!(v.swap_remove(0), "foo"); | |
c34b1796 | 691 | /// assert_eq!(v, ["baz", "qux"]); |
1a4d82fc JJ |
692 | /// ``` |
693 | #[inline] | |
85aaf69f SL |
694 | #[stable(feature = "rust1", since = "1.0.0")] |
695 | pub fn swap_remove(&mut self, index: usize) -> T { | |
1a4d82fc JJ |
696 | let length = self.len(); |
697 | self.swap(index, length - 1); | |
698 | self.pop().unwrap() | |
699 | } | |
700 | ||
701 | /// Inserts an element at position `index` within the vector, shifting all | |
7453a54e | 702 | /// elements after it to the right. |
1a4d82fc JJ |
703 | /// |
704 | /// # Panics | |
705 | /// | |
c30ab7b3 | 706 | /// Panics if `index` is out of bounds. |
1a4d82fc JJ |
707 | /// |
708 | /// # Examples | |
709 | /// | |
710 | /// ``` | |
85aaf69f | 711 | /// let mut vec = vec![1, 2, 3]; |
1a4d82fc | 712 | /// vec.insert(1, 4); |
c34b1796 | 713 | /// assert_eq!(vec, [1, 4, 2, 3]); |
1a4d82fc | 714 | /// vec.insert(4, 5); |
c34b1796 | 715 | /// assert_eq!(vec, [1, 4, 2, 3, 5]); |
1a4d82fc | 716 | /// ``` |
85aaf69f SL |
717 | #[stable(feature = "rust1", since = "1.0.0")] |
718 | pub fn insert(&mut self, index: usize, element: T) { | |
1a4d82fc JJ |
719 | let len = self.len(); |
720 | assert!(index <= len); | |
c1a9b12d | 721 | |
1a4d82fc | 722 | // space for the new element |
92a42be0 SL |
723 | if len == self.buf.cap() { |
724 | self.buf.double(); | |
725 | } | |
1a4d82fc | 726 | |
92a42be0 SL |
727 | unsafe { |
728 | // infallible | |
1a4d82fc JJ |
729 | // The spot to put the new value |
730 | { | |
85aaf69f | 731 | let p = self.as_mut_ptr().offset(index as isize); |
1a4d82fc JJ |
732 | // Shift everything over to make space. (Duplicating the |
733 | // `index`th element into two consecutive places.) | |
c1a9b12d | 734 | ptr::copy(p, p.offset(1), len - index); |
1a4d82fc JJ |
735 | // Write it in, overwriting the first copy of the `index`th |
736 | // element. | |
c1a9b12d | 737 | ptr::write(p, element); |
1a4d82fc JJ |
738 | } |
739 | self.set_len(len + 1); | |
740 | } | |
741 | } | |
742 | ||
743 | /// Removes and returns the element at position `index` within the vector, | |
7453a54e | 744 | /// shifting all elements after it to the left. |
1a4d82fc JJ |
745 | /// |
746 | /// # Panics | |
747 | /// | |
bd371182 | 748 | /// Panics if `index` is out of bounds. |
1a4d82fc JJ |
749 | /// |
750 | /// # Examples | |
751 | /// | |
752 | /// ``` | |
85aaf69f | 753 | /// let mut v = vec![1, 2, 3]; |
1a4d82fc | 754 | /// assert_eq!(v.remove(1), 2); |
c34b1796 | 755 | /// assert_eq!(v, [1, 3]); |
1a4d82fc | 756 | /// ``` |
85aaf69f SL |
757 | #[stable(feature = "rust1", since = "1.0.0")] |
758 | pub fn remove(&mut self, index: usize) -> T { | |
1a4d82fc JJ |
759 | let len = self.len(); |
760 | assert!(index < len); | |
92a42be0 SL |
761 | unsafe { |
762 | // infallible | |
1a4d82fc JJ |
763 | let ret; |
764 | { | |
765 | // the place we are taking from. | |
85aaf69f | 766 | let ptr = self.as_mut_ptr().offset(index as isize); |
1a4d82fc JJ |
767 | // copy it out, unsafely having a copy of the value on |
768 | // the stack and in the vector at the same time. | |
85aaf69f | 769 | ret = ptr::read(ptr); |
1a4d82fc JJ |
770 | |
771 | // Shift everything down to fill in that spot. | |
c1a9b12d | 772 | ptr::copy(ptr.offset(1), ptr, len - index - 1); |
1a4d82fc JJ |
773 | } |
774 | self.set_len(len - 1); | |
775 | ret | |
776 | } | |
777 | } | |
778 | ||
779 | /// Retains only the elements specified by the predicate. | |
780 | /// | |
c30ab7b3 | 781 | /// In other words, remove all elements `e` such that `f(&e)` returns `false`. |
1a4d82fc JJ |
782 | /// This method operates in place and preserves the order of the retained |
783 | /// elements. | |
784 | /// | |
785 | /// # Examples | |
786 | /// | |
787 | /// ``` | |
85aaf69f | 788 | /// let mut vec = vec![1, 2, 3, 4]; |
1a4d82fc | 789 | /// vec.retain(|&x| x%2 == 0); |
c34b1796 | 790 | /// assert_eq!(vec, [2, 4]); |
1a4d82fc | 791 | /// ``` |
85aaf69f | 792 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
793 | pub fn retain<F>(&mut self, mut f: F) |
794 | where F: FnMut(&T) -> bool | |
795 | { | |
1a4d82fc | 796 | let len = self.len(); |
85aaf69f | 797 | let mut del = 0; |
1a4d82fc | 798 | { |
85aaf69f | 799 | let v = &mut **self; |
1a4d82fc | 800 | |
85aaf69f | 801 | for i in 0..len { |
1a4d82fc JJ |
802 | if !f(&v[i]) { |
803 | del += 1; | |
804 | } else if del > 0 { | |
92a42be0 | 805 | v.swap(i - del, i); |
1a4d82fc JJ |
806 | } |
807 | } | |
808 | } | |
809 | if del > 0 { | |
810 | self.truncate(len - del); | |
811 | } | |
812 | } | |
813 | ||
c30ab7b3 SL |
814 | /// Removes consecutive elements in the vector that resolve to the same key. |
815 | /// | |
816 | /// If the vector is sorted, this removes all duplicates. | |
817 | /// | |
818 | /// # Examples | |
819 | /// | |
820 | /// ``` | |
821 | /// #![feature(dedup_by)] | |
822 | /// | |
823 | /// let mut vec = vec![10, 20, 21, 30, 20]; | |
824 | /// | |
825 | /// vec.dedup_by_key(|i| *i / 10); | |
826 | /// | |
827 | /// assert_eq!(vec, [10, 20, 30, 20]); | |
828 | /// ``` | |
829 | #[unstable(feature = "dedup_by", reason = "recently added", issue = "37087")] | |
830 | #[inline] | |
831 | pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq { | |
832 | self.dedup_by(|a, b| key(a) == key(b)) | |
833 | } | |
834 | ||
835 | /// Removes consecutive elements in the vector that resolve to the same key. | |
836 | /// | |
837 | /// If the vector is sorted, this removes all duplicates. | |
838 | /// | |
839 | /// # Examples | |
840 | /// | |
841 | /// ``` | |
842 | /// #![feature(dedup_by)] | |
843 | /// use std::ascii::AsciiExt; | |
844 | /// | |
845 | /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; | |
846 | /// | |
847 | /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); | |
848 | /// | |
849 | /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); | |
850 | /// ``` | |
851 | #[unstable(feature = "dedup_by", reason = "recently added", issue = "37087")] | |
852 | pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool { | |
853 | unsafe { | |
854 | // Although we have a mutable reference to `self`, we cannot make | |
855 | // *arbitrary* changes. The `same_bucket` calls could panic, so we | |
856 | // must ensure that the vector is in a valid state at all time. | |
857 | // | |
858 | // The way that we handle this is by using swaps; we iterate | |
859 | // over all the elements, swapping as we go so that at the end | |
860 | // the elements we wish to keep are in the front, and those we | |
861 | // wish to reject are at the back. We can then truncate the | |
862 | // vector. This operation is still O(n). | |
863 | // | |
864 | // Example: We start in this state, where `r` represents "next | |
865 | // read" and `w` represents "next_write`. | |
866 | // | |
867 | // r | |
868 | // +---+---+---+---+---+---+ | |
869 | // | 0 | 1 | 1 | 2 | 3 | 3 | | |
870 | // +---+---+---+---+---+---+ | |
871 | // w | |
872 | // | |
873 | // Comparing self[r] against self[w-1], this is not a duplicate, so | |
874 | // we swap self[r] and self[w] (no effect as r==w) and then increment both | |
875 | // r and w, leaving us with: | |
876 | // | |
877 | // r | |
878 | // +---+---+---+---+---+---+ | |
879 | // | 0 | 1 | 1 | 2 | 3 | 3 | | |
880 | // +---+---+---+---+---+---+ | |
881 | // w | |
882 | // | |
883 | // Comparing self[r] against self[w-1], this value is a duplicate, | |
884 | // so we increment `r` but leave everything else unchanged: | |
885 | // | |
886 | // r | |
887 | // +---+---+---+---+---+---+ | |
888 | // | 0 | 1 | 1 | 2 | 3 | 3 | | |
889 | // +---+---+---+---+---+---+ | |
890 | // w | |
891 | // | |
892 | // Comparing self[r] against self[w-1], this is not a duplicate, | |
893 | // so swap self[r] and self[w] and advance r and w: | |
894 | // | |
895 | // r | |
896 | // +---+---+---+---+---+---+ | |
897 | // | 0 | 1 | 2 | 1 | 3 | 3 | | |
898 | // +---+---+---+---+---+---+ | |
899 | // w | |
900 | // | |
901 | // Not a duplicate, repeat: | |
902 | // | |
903 | // r | |
904 | // +---+---+---+---+---+---+ | |
905 | // | 0 | 1 | 2 | 3 | 1 | 3 | | |
906 | // +---+---+---+---+---+---+ | |
907 | // w | |
908 | // | |
909 | // Duplicate, advance r. End of vec. Truncate to w. | |
910 | ||
911 | let ln = self.len(); | |
912 | if ln <= 1 { | |
913 | return; | |
914 | } | |
915 | ||
916 | // Avoid bounds checks by using raw pointers. | |
917 | let p = self.as_mut_ptr(); | |
918 | let mut r: usize = 1; | |
919 | let mut w: usize = 1; | |
920 | ||
921 | while r < ln { | |
922 | let p_r = p.offset(r as isize); | |
923 | let p_wm1 = p.offset((w - 1) as isize); | |
924 | if !same_bucket(&mut *p_r, &mut *p_wm1) { | |
925 | if r != w { | |
926 | let p_w = p_wm1.offset(1); | |
927 | mem::swap(&mut *p_r, &mut *p_w); | |
928 | } | |
929 | w += 1; | |
930 | } | |
931 | r += 1; | |
932 | } | |
933 | ||
934 | self.truncate(w); | |
935 | } | |
936 | } | |
937 | ||
1a4d82fc JJ |
938 | /// Appends an element to the back of a collection. |
939 | /// | |
940 | /// # Panics | |
941 | /// | |
85aaf69f | 942 | /// Panics if the number of elements in the vector overflows a `usize`. |
1a4d82fc JJ |
943 | /// |
944 | /// # Examples | |
945 | /// | |
c34b1796 | 946 | /// ``` |
c1a9b12d | 947 | /// let mut vec = vec![1, 2]; |
1a4d82fc | 948 | /// vec.push(3); |
c34b1796 | 949 | /// assert_eq!(vec, [1, 2, 3]); |
1a4d82fc JJ |
950 | /// ``` |
951 | #[inline] | |
85aaf69f | 952 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 953 | pub fn push(&mut self, value: T) { |
c1a9b12d SL |
954 | // This will panic or abort if we would allocate > isize::MAX bytes |
955 | // or if the length increment would overflow for zero-sized types. | |
92a42be0 SL |
956 | if self.len == self.buf.cap() { |
957 | self.buf.double(); | |
958 | } | |
1a4d82fc | 959 | unsafe { |
c1a9b12d SL |
960 | let end = self.as_mut_ptr().offset(self.len as isize); |
961 | ptr::write(end, value); | |
1a4d82fc JJ |
962 | self.len += 1; |
963 | } | |
964 | } | |
965 | ||
c30ab7b3 | 966 | /// Removes the last element from a vector and returns it, or [`None`] if it |
e9174d1e | 967 | /// is empty. |
1a4d82fc | 968 | /// |
c30ab7b3 SL |
969 | /// [`None`]: ../../std/option/enum.Option.html#variant.None |
970 | /// | |
1a4d82fc JJ |
971 | /// # Examples |
972 | /// | |
c34b1796 | 973 | /// ``` |
85aaf69f | 974 | /// let mut vec = vec![1, 2, 3]; |
1a4d82fc | 975 | /// assert_eq!(vec.pop(), Some(3)); |
c34b1796 | 976 | /// assert_eq!(vec, [1, 2]); |
1a4d82fc JJ |
977 | /// ``` |
978 | #[inline] | |
85aaf69f | 979 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
980 | pub fn pop(&mut self) -> Option<T> { |
981 | if self.len == 0 { | |
982 | None | |
983 | } else { | |
984 | unsafe { | |
985 | self.len -= 1; | |
986 | Some(ptr::read(self.get_unchecked(self.len()))) | |
987 | } | |
988 | } | |
989 | } | |
990 | ||
85aaf69f SL |
991 | /// Moves all the elements of `other` into `Self`, leaving `other` empty. |
992 | /// | |
993 | /// # Panics | |
994 | /// | |
995 | /// Panics if the number of elements in the vector overflows a `usize`. | |
996 | /// | |
997 | /// # Examples | |
998 | /// | |
999 | /// ``` | |
1000 | /// let mut vec = vec![1, 2, 3]; | |
1001 | /// let mut vec2 = vec![4, 5, 6]; | |
1002 | /// vec.append(&mut vec2); | |
c34b1796 AL |
1003 | /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); |
1004 | /// assert_eq!(vec2, []); | |
85aaf69f SL |
1005 | /// ``` |
1006 | #[inline] | |
e9174d1e | 1007 | #[stable(feature = "append", since = "1.4.0")] |
85aaf69f | 1008 | pub fn append(&mut self, other: &mut Self) { |
85aaf69f SL |
1009 | self.reserve(other.len()); |
1010 | let len = self.len(); | |
1011 | unsafe { | |
92a42be0 | 1012 | ptr::copy_nonoverlapping(other.as_ptr(), self.get_unchecked_mut(len), other.len()); |
85aaf69f SL |
1013 | } |
1014 | ||
1015 | self.len += other.len(); | |
92a42be0 SL |
1016 | unsafe { |
1017 | other.set_len(0); | |
1018 | } | |
85aaf69f SL |
1019 | } |
1020 | ||
d9579d0f | 1021 | /// Create a draining iterator that removes the specified range in the vector |
9cc50fc6 | 1022 | /// and yields the removed items. |
d9579d0f | 1023 | /// |
9cc50fc6 SL |
1024 | /// Note 1: The element range is removed even if the iterator is not |
1025 | /// consumed until the end. | |
1026 | /// | |
1027 | /// Note 2: It is unspecified how many elements are removed from the vector, | |
d9579d0f AL |
1028 | /// if the `Drain` value is leaked. |
1029 | /// | |
1030 | /// # Panics | |
1031 | /// | |
1032 | /// Panics if the starting point is greater than the end point or if | |
1033 | /// the end point is greater than the length of the vector. | |
1a4d82fc JJ |
1034 | /// |
1035 | /// # Examples | |
1036 | /// | |
1037 | /// ``` | |
d9579d0f | 1038 | /// let mut v = vec![1, 2, 3]; |
9cc50fc6 SL |
1039 | /// let u: Vec<_> = v.drain(1..).collect(); |
1040 | /// assert_eq!(v, &[1]); | |
1041 | /// assert_eq!(u, &[2, 3]); | |
1042 | /// | |
1043 | /// // A full range clears the vector | |
1044 | /// v.drain(..); | |
d9579d0f | 1045 | /// assert_eq!(v, &[]); |
1a4d82fc | 1046 | /// ``` |
92a42be0 SL |
1047 | #[stable(feature = "drain", since = "1.6.0")] |
1048 | pub fn drain<R>(&mut self, range: R) -> Drain<T> | |
1049 | where R: RangeArgument<usize> | |
1050 | { | |
d9579d0f AL |
1051 | // Memory safety |
1052 | // | |
1053 | // When the Drain is first created, it shortens the length of | |
1054 | // the source vector to make sure no uninitalized or moved-from elements | |
1055 | // are accessible at all if the Drain's destructor never gets to run. | |
1056 | // | |
1057 | // Drain will ptr::read out the values to remove. | |
1058 | // When finished, remaining tail of the vec is copied back to cover | |
1059 | // the hole, and the vector length is restored to the new length. | |
1060 | // | |
1061 | let len = self.len(); | |
1062 | let start = *range.start().unwrap_or(&0); | |
1063 | let end = *range.end().unwrap_or(&len); | |
1064 | assert!(start <= end); | |
1065 | assert!(end <= len); | |
1066 | ||
1a4d82fc | 1067 | unsafe { |
d9579d0f AL |
1068 | // set self.vec length's to start, to be safe in case Drain is leaked |
1069 | self.set_len(start); | |
1070 | // Use the borrow in the IterMut to indicate borrowing behavior of the | |
1071 | // whole Drain iterator (like &mut T). | |
92a42be0 SL |
1072 | let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize), |
1073 | end - start); | |
1a4d82fc | 1074 | Drain { |
d9579d0f AL |
1075 | tail_start: end, |
1076 | tail_len: len - end, | |
5bcae85e SL |
1077 | iter: range_slice.iter(), |
1078 | vec: Shared::new(self as *mut _), | |
1a4d82fc JJ |
1079 | } |
1080 | } | |
1081 | } | |
1082 | ||
1083 | /// Clears the vector, removing all values. | |
1084 | /// | |
1085 | /// # Examples | |
1086 | /// | |
1087 | /// ``` | |
85aaf69f | 1088 | /// let mut v = vec![1, 2, 3]; |
1a4d82fc JJ |
1089 | /// |
1090 | /// v.clear(); | |
1091 | /// | |
1092 | /// assert!(v.is_empty()); | |
1093 | /// ``` | |
1094 | #[inline] | |
85aaf69f | 1095 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1096 | pub fn clear(&mut self) { |
1097 | self.truncate(0) | |
1098 | } | |
1099 | ||
1100 | /// Returns the number of elements in the vector. | |
1101 | /// | |
1102 | /// # Examples | |
1103 | /// | |
1104 | /// ``` | |
85aaf69f | 1105 | /// let a = vec![1, 2, 3]; |
1a4d82fc JJ |
1106 | /// assert_eq!(a.len(), 3); |
1107 | /// ``` | |
1108 | #[inline] | |
85aaf69f | 1109 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
1110 | pub fn len(&self) -> usize { |
1111 | self.len | |
1112 | } | |
1a4d82fc JJ |
1113 | |
1114 | /// Returns `true` if the vector contains no elements. | |
1115 | /// | |
1116 | /// # Examples | |
1117 | /// | |
1118 | /// ``` | |
1119 | /// let mut v = Vec::new(); | |
1120 | /// assert!(v.is_empty()); | |
1121 | /// | |
85aaf69f | 1122 | /// v.push(1); |
1a4d82fc JJ |
1123 | /// assert!(!v.is_empty()); |
1124 | /// ``` | |
85aaf69f | 1125 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
1126 | pub fn is_empty(&self) -> bool { |
1127 | self.len() == 0 | |
1128 | } | |
1a4d82fc | 1129 | |
85aaf69f SL |
1130 | /// Splits the collection into two at the given index. |
1131 | /// | |
1132 | /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`, | |
1133 | /// and the returned `Self` contains elements `[at, len)`. | |
1134 | /// | |
1135 | /// Note that the capacity of `self` does not change. | |
1136 | /// | |
1137 | /// # Panics | |
1138 | /// | |
1139 | /// Panics if `at > len`. | |
1140 | /// | |
1141 | /// # Examples | |
1142 | /// | |
1143 | /// ``` | |
1144 | /// let mut vec = vec![1,2,3]; | |
1145 | /// let vec2 = vec.split_off(1); | |
c34b1796 AL |
1146 | /// assert_eq!(vec, [1]); |
1147 | /// assert_eq!(vec2, [2, 3]); | |
85aaf69f SL |
1148 | /// ``` |
1149 | #[inline] | |
e9174d1e | 1150 | #[stable(feature = "split_off", since = "1.4.0")] |
85aaf69f SL |
1151 | pub fn split_off(&mut self, at: usize) -> Self { |
1152 | assert!(at <= self.len(), "`at` out of bounds"); | |
1153 | ||
1154 | let other_len = self.len - at; | |
1155 | let mut other = Vec::with_capacity(other_len); | |
1156 | ||
1157 | // Unsafely `set_len` and copy items to `other`. | |
1158 | unsafe { | |
1159 | self.set_len(at); | |
1160 | other.set_len(other_len); | |
1161 | ||
92a42be0 SL |
1162 | ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize), |
1163 | other.as_mut_ptr(), | |
1164 | other.len()); | |
85aaf69f SL |
1165 | } |
1166 | other | |
1167 | } | |
1a4d82fc JJ |
1168 | } |
1169 | ||
1170 | impl<T: Clone> Vec<T> { | |
1171 | /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`. | |
1172 | /// | |
92a42be0 SL |
1173 | /// If `new_len` is greater than `len()`, the `Vec` is extended by the |
1174 | /// difference, with each additional slot filled with `value`. | |
1175 | /// If `new_len` is less than `len()`, the `Vec` is simply truncated. | |
1a4d82fc JJ |
1176 | /// |
1177 | /// # Examples | |
1178 | /// | |
1179 | /// ``` | |
1180 | /// let mut vec = vec!["hello"]; | |
1181 | /// vec.resize(3, "world"); | |
c34b1796 | 1182 | /// assert_eq!(vec, ["hello", "world", "world"]); |
1a4d82fc | 1183 | /// |
85aaf69f | 1184 | /// let mut vec = vec![1, 2, 3, 4]; |
1a4d82fc | 1185 | /// vec.resize(2, 0); |
c34b1796 | 1186 | /// assert_eq!(vec, [1, 2]); |
1a4d82fc | 1187 | /// ``` |
b039eaaf | 1188 | #[stable(feature = "vec_resize", since = "1.5.0")] |
85aaf69f | 1189 | pub fn resize(&mut self, new_len: usize, value: T) { |
1a4d82fc JJ |
1190 | let len = self.len(); |
1191 | ||
1192 | if new_len > len { | |
c1a9b12d | 1193 | self.extend_with_element(new_len - len, value); |
1a4d82fc JJ |
1194 | } else { |
1195 | self.truncate(new_len); | |
1196 | } | |
1197 | } | |
1198 | ||
c1a9b12d SL |
1199 | /// Extend the vector by `n` additional clones of `value`. |
1200 | fn extend_with_element(&mut self, n: usize, value: T) { | |
1201 | self.reserve(n); | |
1202 | ||
1203 | unsafe { | |
9e0c209e SL |
1204 | let mut ptr = self.as_mut_ptr().offset(self.len() as isize); |
1205 | // Use SetLenOnDrop to work around bug where compiler | |
1206 | // may not realize the store through `ptr` trough self.set_len() | |
1207 | // don't alias. | |
1208 | let mut local_len = SetLenOnDrop::new(&mut self.len); | |
1209 | ||
c1a9b12d | 1210 | // Write all elements except the last one |
9e0c209e | 1211 | for _ in 1..n { |
c1a9b12d SL |
1212 | ptr::write(ptr, value.clone()); |
1213 | ptr = ptr.offset(1); | |
1214 | // Increment the length in every step in case clone() panics | |
9e0c209e | 1215 | local_len.increment_len(1); |
c1a9b12d SL |
1216 | } |
1217 | ||
1218 | if n > 0 { | |
1219 | // We can write the last element directly without cloning needlessly | |
1220 | ptr::write(ptr, value); | |
9e0c209e | 1221 | local_len.increment_len(1); |
c1a9b12d | 1222 | } |
9e0c209e SL |
1223 | |
1224 | // len set by scope guard | |
c1a9b12d SL |
1225 | } |
1226 | } | |
1227 | ||
3157f602 | 1228 | /// Clones and appends all elements in a slice to the `Vec`. |
1a4d82fc JJ |
1229 | /// |
1230 | /// Iterates over the slice `other`, clones each element, and then appends | |
1231 | /// it to this `Vec`. The `other` vector is traversed in-order. | |
1232 | /// | |
92a42be0 SL |
1233 | /// Note that this function is same as `extend` except that it is |
1234 | /// specialized to work with slices instead. If and when Rust gets | |
1235 | /// specialization this function will likely be deprecated (but still | |
1236 | /// available). | |
1237 | /// | |
1a4d82fc JJ |
1238 | /// # Examples |
1239 | /// | |
1240 | /// ``` | |
85aaf69f | 1241 | /// let mut vec = vec![1]; |
92a42be0 | 1242 | /// vec.extend_from_slice(&[2, 3, 4]); |
c34b1796 | 1243 | /// assert_eq!(vec, [1, 2, 3, 4]); |
1a4d82fc | 1244 | /// ``` |
92a42be0 SL |
1245 | #[stable(feature = "vec_extend_from_slice", since = "1.6.0")] |
1246 | pub fn extend_from_slice(&mut self, other: &[T]) { | |
c30ab7b3 | 1247 | self.extend(other.iter().cloned()) |
1a4d82fc JJ |
1248 | } |
1249 | } | |
1250 | ||
9e0c209e SL |
1251 | // Set the length of the vec when the `SetLenOnDrop` value goes out of scope. |
1252 | // | |
1253 | // The idea is: The length field in SetLenOnDrop is a local variable | |
1254 | // that the optimizer will see does not alias with any stores through the Vec's data | |
1255 | // pointer. This is a workaround for alias analysis issue #32155 | |
1256 | struct SetLenOnDrop<'a> { | |
1257 | len: &'a mut usize, | |
1258 | local_len: usize, | |
1259 | } | |
1260 | ||
1261 | impl<'a> SetLenOnDrop<'a> { | |
1262 | #[inline] | |
1263 | fn new(len: &'a mut usize) -> Self { | |
1264 | SetLenOnDrop { local_len: *len, len: len } | |
1265 | } | |
1266 | ||
1267 | #[inline] | |
1268 | fn increment_len(&mut self, increment: usize) { | |
1269 | self.local_len += increment; | |
1270 | } | |
1271 | } | |
1272 | ||
1273 | impl<'a> Drop for SetLenOnDrop<'a> { | |
1274 | #[inline] | |
1275 | fn drop(&mut self) { | |
1276 | *self.len = self.local_len; | |
1277 | } | |
1278 | } | |
1279 | ||
1a4d82fc JJ |
1280 | impl<T: PartialEq> Vec<T> { |
1281 | /// Removes consecutive repeated elements in the vector. | |
1282 | /// | |
1283 | /// If the vector is sorted, this removes all duplicates. | |
1284 | /// | |
1285 | /// # Examples | |
1286 | /// | |
1287 | /// ``` | |
85aaf69f | 1288 | /// let mut vec = vec![1, 2, 2, 3, 2]; |
1a4d82fc JJ |
1289 | /// |
1290 | /// vec.dedup(); | |
1291 | /// | |
c34b1796 | 1292 | /// assert_eq!(vec, [1, 2, 3, 2]); |
1a4d82fc | 1293 | /// ``` |
85aaf69f | 1294 | #[stable(feature = "rust1", since = "1.0.0")] |
c30ab7b3 | 1295 | #[inline] |
1a4d82fc | 1296 | pub fn dedup(&mut self) { |
c30ab7b3 | 1297 | self.dedup_by(|a, b| a == b) |
1a4d82fc JJ |
1298 | } |
1299 | } | |
1300 | ||
1301 | //////////////////////////////////////////////////////////////////////////////// | |
1302 | // Internal methods and functions | |
1303 | //////////////////////////////////////////////////////////////////////////////// | |
1304 | ||
85aaf69f SL |
1305 | #[doc(hidden)] |
1306 | #[stable(feature = "rust1", since = "1.0.0")] | |
1307 | pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> { | |
c1a9b12d SL |
1308 | let mut v = Vec::with_capacity(n); |
1309 | v.extend_with_element(n, elem); | |
1310 | v | |
85aaf69f SL |
1311 | } |
1312 | ||
1a4d82fc JJ |
1313 | //////////////////////////////////////////////////////////////////////////////// |
1314 | // Common trait implementations for Vec | |
1315 | //////////////////////////////////////////////////////////////////////////////// | |
1316 | ||
bd371182 | 1317 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 1318 | impl<T: Clone> Clone for Vec<T> { |
c34b1796 | 1319 | #[cfg(not(test))] |
92a42be0 SL |
1320 | fn clone(&self) -> Vec<T> { |
1321 | <[T]>::to_vec(&**self) | |
1322 | } | |
c34b1796 AL |
1323 | |
1324 | // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is | |
1325 | // required for this method definition, is not available. Instead use the | |
1326 | // `slice::to_vec` function which is only available with cfg(test) | |
1327 | // NB see the slice::hack module in slice.rs for more information | |
1328 | #[cfg(test)] | |
1329 | fn clone(&self) -> Vec<T> { | |
1330 | ::slice::to_vec(&**self) | |
1331 | } | |
1a4d82fc JJ |
1332 | |
1333 | fn clone_from(&mut self, other: &Vec<T>) { | |
1334 | // drop anything in self that will not be overwritten | |
b039eaaf SL |
1335 | self.truncate(other.len()); |
1336 | let len = self.len(); | |
1a4d82fc JJ |
1337 | |
1338 | // reuse the contained values' allocations/resources. | |
b039eaaf | 1339 | self.clone_from_slice(&other[..len]); |
1a4d82fc JJ |
1340 | |
1341 | // self.len <= other.len due to the truncate above, so the | |
1342 | // slice here is always in-bounds. | |
92a42be0 | 1343 | self.extend_from_slice(&other[len..]); |
1a4d82fc JJ |
1344 | } |
1345 | } | |
1346 | ||
85aaf69f | 1347 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 1348 | impl<T: Hash> Hash for Vec<T> { |
1a4d82fc | 1349 | #[inline] |
85aaf69f SL |
1350 | fn hash<H: hash::Hasher>(&self, state: &mut H) { |
1351 | Hash::hash(&**self, state) | |
1a4d82fc JJ |
1352 | } |
1353 | } | |
1354 | ||
85aaf69f SL |
1355 | #[stable(feature = "rust1", since = "1.0.0")] |
1356 | impl<T> Index<usize> for Vec<T> { | |
1a4d82fc JJ |
1357 | type Output = T; |
1358 | ||
1359 | #[inline] | |
c34b1796 | 1360 | fn index(&self, index: usize) -> &T { |
85aaf69f | 1361 | // NB built-in indexing via `&[T]` |
c34b1796 | 1362 | &(**self)[index] |
1a4d82fc JJ |
1363 | } |
1364 | } | |
1365 | ||
85aaf69f SL |
1366 | #[stable(feature = "rust1", since = "1.0.0")] |
1367 | impl<T> IndexMut<usize> for Vec<T> { | |
1a4d82fc | 1368 | #[inline] |
c34b1796 | 1369 | fn index_mut(&mut self, index: usize) -> &mut T { |
85aaf69f | 1370 | // NB built-in indexing via `&mut [T]` |
c34b1796 | 1371 | &mut (**self)[index] |
1a4d82fc JJ |
1372 | } |
1373 | } | |
1374 | ||
1375 | ||
85aaf69f SL |
1376 | #[stable(feature = "rust1", since = "1.0.0")] |
1377 | impl<T> ops::Index<ops::Range<usize>> for Vec<T> { | |
1a4d82fc | 1378 | type Output = [T]; |
c34b1796 | 1379 | |
1a4d82fc | 1380 | #[inline] |
c34b1796 | 1381 | fn index(&self, index: ops::Range<usize>) -> &[T] { |
85aaf69f | 1382 | Index::index(&**self, index) |
1a4d82fc JJ |
1383 | } |
1384 | } | |
85aaf69f SL |
1385 | #[stable(feature = "rust1", since = "1.0.0")] |
1386 | impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> { | |
1a4d82fc | 1387 | type Output = [T]; |
c34b1796 | 1388 | |
1a4d82fc | 1389 | #[inline] |
c34b1796 | 1390 | fn index(&self, index: ops::RangeTo<usize>) -> &[T] { |
85aaf69f | 1391 | Index::index(&**self, index) |
1a4d82fc JJ |
1392 | } |
1393 | } | |
85aaf69f SL |
1394 | #[stable(feature = "rust1", since = "1.0.0")] |
1395 | impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> { | |
1a4d82fc | 1396 | type Output = [T]; |
c34b1796 | 1397 | |
1a4d82fc | 1398 | #[inline] |
c34b1796 | 1399 | fn index(&self, index: ops::RangeFrom<usize>) -> &[T] { |
85aaf69f | 1400 | Index::index(&**self, index) |
1a4d82fc JJ |
1401 | } |
1402 | } | |
85aaf69f SL |
1403 | #[stable(feature = "rust1", since = "1.0.0")] |
1404 | impl<T> ops::Index<ops::RangeFull> for Vec<T> { | |
1a4d82fc | 1405 | type Output = [T]; |
c34b1796 | 1406 | |
1a4d82fc | 1407 | #[inline] |
c34b1796 AL |
1408 | fn index(&self, _index: ops::RangeFull) -> &[T] { |
1409 | self | |
1a4d82fc JJ |
1410 | } |
1411 | } | |
54a0048b SL |
1412 | #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")] |
1413 | impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> { | |
1414 | type Output = [T]; | |
1415 | ||
1416 | #[inline] | |
1417 | fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] { | |
1418 | Index::index(&**self, index) | |
1419 | } | |
1420 | } | |
1421 | #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")] | |
1422 | impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> { | |
1423 | type Output = [T]; | |
1424 | ||
1425 | #[inline] | |
1426 | fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] { | |
1427 | Index::index(&**self, index) | |
1428 | } | |
1429 | } | |
1a4d82fc | 1430 | |
85aaf69f SL |
1431 | #[stable(feature = "rust1", since = "1.0.0")] |
1432 | impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> { | |
1a4d82fc | 1433 | #[inline] |
c34b1796 | 1434 | fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] { |
85aaf69f | 1435 | IndexMut::index_mut(&mut **self, index) |
1a4d82fc JJ |
1436 | } |
1437 | } | |
85aaf69f SL |
1438 | #[stable(feature = "rust1", since = "1.0.0")] |
1439 | impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> { | |
1a4d82fc | 1440 | #[inline] |
c34b1796 | 1441 | fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] { |
85aaf69f | 1442 | IndexMut::index_mut(&mut **self, index) |
1a4d82fc JJ |
1443 | } |
1444 | } | |
85aaf69f SL |
1445 | #[stable(feature = "rust1", since = "1.0.0")] |
1446 | impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> { | |
1a4d82fc | 1447 | #[inline] |
c34b1796 | 1448 | fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] { |
85aaf69f | 1449 | IndexMut::index_mut(&mut **self, index) |
1a4d82fc JJ |
1450 | } |
1451 | } | |
85aaf69f SL |
1452 | #[stable(feature = "rust1", since = "1.0.0")] |
1453 | impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> { | |
1a4d82fc | 1454 | #[inline] |
c34b1796 AL |
1455 | fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] { |
1456 | self | |
1a4d82fc JJ |
1457 | } |
1458 | } | |
54a0048b SL |
1459 | #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")] |
1460 | impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> { | |
1461 | #[inline] | |
1462 | fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] { | |
1463 | IndexMut::index_mut(&mut **self, index) | |
1464 | } | |
1465 | } | |
1466 | #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")] | |
1467 | impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> { | |
1468 | #[inline] | |
1469 | fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] { | |
1470 | IndexMut::index_mut(&mut **self, index) | |
1471 | } | |
1472 | } | |
1a4d82fc | 1473 | |
85aaf69f | 1474 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1475 | impl<T> ops::Deref for Vec<T> { |
1476 | type Target = [T]; | |
1477 | ||
c34b1796 AL |
1478 | fn deref(&self) -> &[T] { |
1479 | unsafe { | |
c1a9b12d | 1480 | let p = self.buf.ptr(); |
e9174d1e | 1481 | assume(!p.is_null()); |
c34b1796 AL |
1482 | slice::from_raw_parts(p, self.len) |
1483 | } | |
1484 | } | |
1a4d82fc JJ |
1485 | } |
1486 | ||
85aaf69f | 1487 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1488 | impl<T> ops::DerefMut for Vec<T> { |
c34b1796 AL |
1489 | fn deref_mut(&mut self) -> &mut [T] { |
1490 | unsafe { | |
c1a9b12d | 1491 | let ptr = self.buf.ptr(); |
c34b1796 AL |
1492 | assume(!ptr.is_null()); |
1493 | slice::from_raw_parts_mut(ptr, self.len) | |
1494 | } | |
1495 | } | |
1a4d82fc JJ |
1496 | } |
1497 | ||
85aaf69f | 1498 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1499 | impl<T> FromIterator<T> for Vec<T> { |
1500 | #[inline] | |
54a0048b | 1501 | fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> { |
62682a34 SL |
1502 | // Unroll the first iteration, as the vector is going to be |
1503 | // expanded on this iteration in every case when the iterable is not | |
1504 | // empty, but the loop in extend_desugared() is not going to see the | |
1505 | // vector being full in the few subsequent loop iterations. | |
92a42be0 | 1506 | // So we get better branch prediction. |
54a0048b | 1507 | let mut iterator = iter.into_iter(); |
62682a34 SL |
1508 | let mut vector = match iterator.next() { |
1509 | None => return Vec::new(), | |
1510 | Some(element) => { | |
1511 | let (lower, _) = iterator.size_hint(); | |
1512 | let mut vector = Vec::with_capacity(lower.saturating_add(1)); | |
1513 | unsafe { | |
1514 | ptr::write(vector.get_unchecked_mut(0), element); | |
1515 | vector.set_len(1); | |
1516 | } | |
1517 | vector | |
85aaf69f | 1518 | } |
62682a34 SL |
1519 | }; |
1520 | vector.extend_desugared(iterator); | |
1a4d82fc JJ |
1521 | vector |
1522 | } | |
1523 | } | |
1524 | ||
85aaf69f SL |
1525 | #[stable(feature = "rust1", since = "1.0.0")] |
1526 | impl<T> IntoIterator for Vec<T> { | |
1527 | type Item = T; | |
1528 | type IntoIter = IntoIter<T>; | |
1529 | ||
9346a6ac AL |
1530 | /// Creates a consuming iterator, that is, one that moves each value out of |
1531 | /// the vector (from start to end). The vector cannot be used after calling | |
1532 | /// this. | |
1533 | /// | |
1534 | /// # Examples | |
1535 | /// | |
1536 | /// ``` | |
1537 | /// let v = vec!["a".to_string(), "b".to_string()]; | |
1538 | /// for s in v.into_iter() { | |
1539 | /// // s has type String, not &String | |
1540 | /// println!("{}", s); | |
1541 | /// } | |
1542 | /// ``` | |
1543 | #[inline] | |
c1a9b12d | 1544 | fn into_iter(mut self) -> IntoIter<T> { |
9346a6ac | 1545 | unsafe { |
5bcae85e SL |
1546 | let begin = self.as_mut_ptr(); |
1547 | assume(!begin.is_null()); | |
9346a6ac | 1548 | let end = if mem::size_of::<T>() == 0 { |
5bcae85e | 1549 | arith_offset(begin as *const i8, self.len() as isize) as *const T |
9346a6ac | 1550 | } else { |
5bcae85e | 1551 | begin.offset(self.len() as isize) as *const T |
9346a6ac | 1552 | }; |
5bcae85e | 1553 | let cap = self.buf.cap(); |
9346a6ac | 1554 | mem::forget(self); |
92a42be0 | 1555 | IntoIter { |
5bcae85e SL |
1556 | buf: Shared::new(begin), |
1557 | cap: cap, | |
92a42be0 SL |
1558 | ptr: begin, |
1559 | end: end, | |
1560 | } | |
9346a6ac | 1561 | } |
85aaf69f SL |
1562 | } |
1563 | } | |
1564 | ||
1565 | #[stable(feature = "rust1", since = "1.0.0")] | |
1566 | impl<'a, T> IntoIterator for &'a Vec<T> { | |
1567 | type Item = &'a T; | |
1568 | type IntoIter = slice::Iter<'a, T>; | |
1569 | ||
1570 | fn into_iter(self) -> slice::Iter<'a, T> { | |
1571 | self.iter() | |
1572 | } | |
1573 | } | |
1574 | ||
1575 | #[stable(feature = "rust1", since = "1.0.0")] | |
1576 | impl<'a, T> IntoIterator for &'a mut Vec<T> { | |
1577 | type Item = &'a mut T; | |
1578 | type IntoIter = slice::IterMut<'a, T>; | |
1579 | ||
1580 | fn into_iter(mut self) -> slice::IterMut<'a, T> { | |
1581 | self.iter_mut() | |
1582 | } | |
1583 | } | |
1584 | ||
bd371182 | 1585 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1586 | impl<T> Extend<T> for Vec<T> { |
1587 | #[inline] | |
54a0048b SL |
1588 | fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { |
1589 | self.extend_desugared(iter.into_iter()) | |
62682a34 SL |
1590 | } |
1591 | } | |
1592 | ||
c30ab7b3 SL |
1593 | trait IsTrustedLen : Iterator { |
1594 | fn trusted_len(&self) -> Option<usize> { None } | |
1595 | } | |
1596 | impl<I> IsTrustedLen for I where I: Iterator { } | |
1597 | ||
1598 | impl<I> IsTrustedLen for I where I: TrustedLen | |
1599 | { | |
1600 | fn trusted_len(&self) -> Option<usize> { | |
1601 | let (low, high) = self.size_hint(); | |
1602 | if let Some(high_value) = high { | |
1603 | debug_assert_eq!(low, high_value, | |
1604 | "TrustedLen iterator's size hint is not exact: {:?}", | |
1605 | (low, high)); | |
1606 | } | |
1607 | high | |
a7813a04 XL |
1608 | } |
1609 | } | |
1610 | ||
62682a34 | 1611 | impl<T> Vec<T> { |
92a42be0 | 1612 | fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) { |
62682a34 SL |
1613 | // This function should be the moral equivalent of: |
1614 | // | |
1615 | // for item in iterator { | |
1616 | // self.push(item); | |
1617 | // } | |
c30ab7b3 SL |
1618 | if let Some(additional) = iterator.trusted_len() { |
1619 | self.reserve(additional); | |
62682a34 | 1620 | unsafe { |
c30ab7b3 SL |
1621 | let mut ptr = self.as_mut_ptr().offset(self.len() as isize); |
1622 | let mut local_len = SetLenOnDrop::new(&mut self.len); | |
1623 | for element in iterator { | |
1624 | ptr::write(ptr, element); | |
1625 | ptr = ptr.offset(1); | |
1626 | // NB can't overflow since we would have had to alloc the address space | |
1627 | local_len.increment_len(1); | |
1628 | } | |
1629 | } | |
1630 | } else { | |
1631 | while let Some(element) = iterator.next() { | |
1632 | let len = self.len(); | |
1633 | if len == self.capacity() { | |
1634 | let (lower, _) = iterator.size_hint(); | |
1635 | self.reserve(lower.saturating_add(1)); | |
1636 | } | |
1637 | unsafe { | |
1638 | ptr::write(self.get_unchecked_mut(len), element); | |
1639 | // NB can't overflow since we would have had to alloc the address space | |
1640 | self.set_len(len + 1); | |
1641 | } | |
62682a34 | 1642 | } |
1a4d82fc JJ |
1643 | } |
1644 | } | |
1645 | } | |
1646 | ||
62682a34 SL |
1647 | #[stable(feature = "extend_ref", since = "1.2.0")] |
1648 | impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> { | |
92a42be0 | 1649 | fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { |
c30ab7b3 | 1650 | self.extend(iter.into_iter().map(|&x| x)) |
62682a34 SL |
1651 | } |
1652 | } | |
1653 | ||
92a42be0 SL |
1654 | macro_rules! __impl_slice_eq1 { |
1655 | ($Lhs: ty, $Rhs: ty) => { | |
1656 | __impl_slice_eq1! { $Lhs, $Rhs, Sized } | |
1657 | }; | |
1658 | ($Lhs: ty, $Rhs: ty, $Bound: ident) => { | |
1659 | #[stable(feature = "rust1", since = "1.0.0")] | |
1660 | impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> { | |
1661 | #[inline] | |
1662 | fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] } | |
1663 | #[inline] | |
1664 | fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] } | |
1665 | } | |
1666 | } | |
1667 | } | |
1668 | ||
c34b1796 AL |
1669 | __impl_slice_eq1! { Vec<A>, Vec<B> } |
1670 | __impl_slice_eq1! { Vec<A>, &'b [B] } | |
1671 | __impl_slice_eq1! { Vec<A>, &'b mut [B] } | |
1672 | __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone } | |
1673 | __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone } | |
1674 | __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone } | |
1675 | ||
1676 | macro_rules! array_impls { | |
1677 | ($($N: expr)+) => { | |
1678 | $( | |
1679 | // NOTE: some less important impls are omitted to reduce code bloat | |
1680 | __impl_slice_eq1! { Vec<A>, [B; $N] } | |
1681 | __impl_slice_eq1! { Vec<A>, &'b [B; $N] } | |
1682 | // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] } | |
1683 | // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone } | |
1684 | // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone } | |
1685 | // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone } | |
1686 | )+ | |
1a4d82fc JJ |
1687 | } |
1688 | } | |
1689 | ||
c34b1796 AL |
1690 | array_impls! { |
1691 | 0 1 2 3 4 5 6 7 8 9 | |
1692 | 10 11 12 13 14 15 16 17 18 19 | |
1693 | 20 21 22 23 24 25 26 27 28 29 | |
1694 | 30 31 32 | |
1a4d82fc JJ |
1695 | } |
1696 | ||
85aaf69f | 1697 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1698 | impl<T: PartialOrd> PartialOrd for Vec<T> { |
1699 | #[inline] | |
1700 | fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> { | |
85aaf69f | 1701 | PartialOrd::partial_cmp(&**self, &**other) |
1a4d82fc JJ |
1702 | } |
1703 | } | |
1704 | ||
85aaf69f | 1705 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1706 | impl<T: Eq> Eq for Vec<T> {} |
1707 | ||
85aaf69f | 1708 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1709 | impl<T: Ord> Ord for Vec<T> { |
1710 | #[inline] | |
1711 | fn cmp(&self, other: &Vec<T>) -> Ordering { | |
85aaf69f | 1712 | Ord::cmp(&**self, &**other) |
1a4d82fc JJ |
1713 | } |
1714 | } | |
1715 | ||
85aaf69f | 1716 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1717 | impl<T> Drop for Vec<T> { |
b039eaaf | 1718 | #[unsafe_destructor_blind_to_params] |
1a4d82fc | 1719 | fn drop(&mut self) { |
9e0c209e SL |
1720 | unsafe { |
1721 | // use drop for [T] | |
1722 | ptr::drop_in_place(&mut self[..]); | |
1a4d82fc | 1723 | } |
c1a9b12d | 1724 | // RawVec handles deallocation |
1a4d82fc JJ |
1725 | } |
1726 | } | |
1727 | ||
85aaf69f | 1728 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1729 | impl<T> Default for Vec<T> { |
9e0c209e | 1730 | /// Creates an empty `Vec<T>`. |
1a4d82fc JJ |
1731 | fn default() -> Vec<T> { |
1732 | Vec::new() | |
1733 | } | |
1734 | } | |
1735 | ||
85aaf69f SL |
1736 | #[stable(feature = "rust1", since = "1.0.0")] |
1737 | impl<T: fmt::Debug> fmt::Debug for Vec<T> { | |
1a4d82fc | 1738 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
85aaf69f | 1739 | fmt::Debug::fmt(&**self, f) |
1a4d82fc JJ |
1740 | } |
1741 | } | |
1742 | ||
c34b1796 AL |
1743 | #[stable(feature = "rust1", since = "1.0.0")] |
1744 | impl<T> AsRef<Vec<T>> for Vec<T> { | |
1745 | fn as_ref(&self) -> &Vec<T> { | |
1746 | self | |
1747 | } | |
1748 | } | |
1749 | ||
b039eaaf SL |
1750 | #[stable(feature = "vec_as_mut", since = "1.5.0")] |
1751 | impl<T> AsMut<Vec<T>> for Vec<T> { | |
1752 | fn as_mut(&mut self) -> &mut Vec<T> { | |
1753 | self | |
1754 | } | |
1755 | } | |
1756 | ||
c34b1796 AL |
1757 | #[stable(feature = "rust1", since = "1.0.0")] |
1758 | impl<T> AsRef<[T]> for Vec<T> { | |
1759 | fn as_ref(&self) -> &[T] { | |
1760 | self | |
1761 | } | |
1762 | } | |
1763 | ||
b039eaaf SL |
1764 | #[stable(feature = "vec_as_mut", since = "1.5.0")] |
1765 | impl<T> AsMut<[T]> for Vec<T> { | |
1766 | fn as_mut(&mut self) -> &mut [T] { | |
1767 | self | |
1768 | } | |
1769 | } | |
1770 | ||
c34b1796 AL |
1771 | #[stable(feature = "rust1", since = "1.0.0")] |
1772 | impl<'a, T: Clone> From<&'a [T]> for Vec<T> { | |
1773 | #[cfg(not(test))] | |
1774 | fn from(s: &'a [T]) -> Vec<T> { | |
1775 | s.to_vec() | |
1776 | } | |
1777 | #[cfg(test)] | |
1778 | fn from(s: &'a [T]) -> Vec<T> { | |
1779 | ::slice::to_vec(s) | |
1780 | } | |
1781 | } | |
1782 | ||
c30ab7b3 SL |
1783 | #[stable(feature = "vec_from_cow_slice", since = "1.14.0")] |
1784 | impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> { | |
1785 | fn from(s: Cow<'a, [T]>) -> Vec<T> { | |
1786 | s.into_owned() | |
1787 | } | |
1788 | } | |
1789 | ||
c34b1796 AL |
1790 | #[stable(feature = "rust1", since = "1.0.0")] |
1791 | impl<'a> From<&'a str> for Vec<u8> { | |
1792 | fn from(s: &'a str) -> Vec<u8> { | |
1793 | From::from(s.as_bytes()) | |
1794 | } | |
1795 | } | |
1796 | ||
1a4d82fc JJ |
1797 | //////////////////////////////////////////////////////////////////////////////// |
1798 | // Clone-on-write | |
1799 | //////////////////////////////////////////////////////////////////////////////// | |
1800 | ||
7453a54e SL |
1801 | #[stable(feature = "cow_from_vec", since = "1.7.0")] |
1802 | impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> { | |
1803 | fn from(s: &'a [T]) -> Cow<'a, [T]> { | |
1804 | Cow::Borrowed(s) | |
1805 | } | |
1806 | } | |
1807 | ||
1808 | #[stable(feature = "cow_from_vec", since = "1.7.0")] | |
1809 | impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> { | |
1810 | fn from(v: Vec<T>) -> Cow<'a, [T]> { | |
1811 | Cow::Owned(v) | |
1812 | } | |
1813 | } | |
1814 | ||
bd371182 | 1815 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 1816 | impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone { |
92a42be0 | 1817 | fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> { |
1a4d82fc JJ |
1818 | Cow::Owned(FromIterator::from_iter(it)) |
1819 | } | |
1820 | } | |
1821 | ||
1a4d82fc JJ |
1822 | //////////////////////////////////////////////////////////////////////////////// |
1823 | // Iterators | |
1824 | //////////////////////////////////////////////////////////////////////////////// | |
1825 | ||
1826 | /// An iterator that moves out of a vector. | |
5bcae85e SL |
1827 | /// |
1828 | /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided | |
1829 | /// by the [`IntoIterator`] trait). | |
1830 | /// | |
1831 | /// [`Vec`]: struct.Vec.html | |
1832 | /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html | |
85aaf69f | 1833 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1834 | pub struct IntoIter<T> { |
5bcae85e SL |
1835 | buf: Shared<T>, |
1836 | cap: usize, | |
1a4d82fc | 1837 | ptr: *const T, |
92a42be0 | 1838 | end: *const T, |
1a4d82fc JJ |
1839 | } |
1840 | ||
c30ab7b3 | 1841 | #[stable(feature = "vec_intoiter_debug", since = "1.13.0")] |
9e0c209e SL |
1842 | impl<T: fmt::Debug> fmt::Debug for IntoIter<T> { |
1843 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
1844 | f.debug_tuple("IntoIter") | |
1845 | .field(&self.as_slice()) | |
1846 | .finish() | |
1847 | } | |
1848 | } | |
1849 | ||
5bcae85e SL |
1850 | impl<T> IntoIter<T> { |
1851 | /// Returns the remaining items of this iterator as a slice. | |
1852 | /// | |
1853 | /// # Examples | |
1854 | /// | |
c30ab7b3 | 1855 | /// ``` |
5bcae85e SL |
1856 | /// # #![feature(vec_into_iter_as_slice)] |
1857 | /// let vec = vec!['a', 'b', 'c']; | |
1858 | /// let mut into_iter = vec.into_iter(); | |
1859 | /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); | |
1860 | /// let _ = into_iter.next().unwrap(); | |
1861 | /// assert_eq!(into_iter.as_slice(), &['b', 'c']); | |
1862 | /// ``` | |
1863 | #[unstable(feature = "vec_into_iter_as_slice", issue = "35601")] | |
1864 | pub fn as_slice(&self) -> &[T] { | |
1865 | unsafe { | |
1866 | slice::from_raw_parts(self.ptr, self.len()) | |
1867 | } | |
1868 | } | |
1869 | ||
1870 | /// Returns the remaining items of this iterator as a mutable slice. | |
1871 | /// | |
1872 | /// # Examples | |
1873 | /// | |
c30ab7b3 | 1874 | /// ``` |
5bcae85e SL |
1875 | /// # #![feature(vec_into_iter_as_slice)] |
1876 | /// let vec = vec!['a', 'b', 'c']; | |
1877 | /// let mut into_iter = vec.into_iter(); | |
1878 | /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); | |
1879 | /// into_iter.as_mut_slice()[2] = 'z'; | |
1880 | /// assert_eq!(into_iter.next().unwrap(), 'a'); | |
1881 | /// assert_eq!(into_iter.next().unwrap(), 'b'); | |
1882 | /// assert_eq!(into_iter.next().unwrap(), 'z'); | |
1883 | /// ``` | |
1884 | #[unstable(feature = "vec_into_iter_as_slice", issue = "35601")] | |
1885 | pub fn as_mut_slice(&self) -> &mut [T] { | |
1886 | unsafe { | |
1887 | slice::from_raw_parts_mut(self.ptr as *mut T, self.len()) | |
1888 | } | |
1889 | } | |
1890 | } | |
1891 | ||
92a42be0 SL |
1892 | #[stable(feature = "rust1", since = "1.0.0")] |
1893 | unsafe impl<T: Send> Send for IntoIter<T> {} | |
1894 | #[stable(feature = "rust1", since = "1.0.0")] | |
1895 | unsafe impl<T: Sync> Sync for IntoIter<T> {} | |
85aaf69f | 1896 | |
85aaf69f | 1897 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1898 | impl<T> Iterator for IntoIter<T> { |
1899 | type Item = T; | |
1900 | ||
1901 | #[inline] | |
85aaf69f | 1902 | fn next(&mut self) -> Option<T> { |
1a4d82fc | 1903 | unsafe { |
5bcae85e | 1904 | if self.ptr as *const _ == self.end { |
1a4d82fc JJ |
1905 | None |
1906 | } else { | |
1907 | if mem::size_of::<T>() == 0 { | |
1908 | // purposefully don't use 'ptr.offset' because for | |
1909 | // vectors with 0-size elements this would return the | |
1910 | // same pointer. | |
5bcae85e | 1911 | self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T; |
1a4d82fc JJ |
1912 | |
1913 | // Use a non-null pointer value | |
85aaf69f | 1914 | Some(ptr::read(EMPTY as *mut T)) |
1a4d82fc JJ |
1915 | } else { |
1916 | let old = self.ptr; | |
1917 | self.ptr = self.ptr.offset(1); | |
1918 | ||
1919 | Some(ptr::read(old)) | |
1920 | } | |
1921 | } | |
1922 | } | |
1923 | } | |
1924 | ||
1925 | #[inline] | |
85aaf69f SL |
1926 | fn size_hint(&self) -> (usize, Option<usize>) { |
1927 | let diff = (self.end as usize) - (self.ptr as usize); | |
1a4d82fc | 1928 | let size = mem::size_of::<T>(); |
92a42be0 SL |
1929 | let exact = diff / |
1930 | (if size == 0 { | |
1931 | 1 | |
1932 | } else { | |
1933 | size | |
1934 | }); | |
1a4d82fc JJ |
1935 | (exact, Some(exact)) |
1936 | } | |
d9579d0f AL |
1937 | |
1938 | #[inline] | |
1939 | fn count(self) -> usize { | |
3157f602 | 1940 | self.len() |
d9579d0f | 1941 | } |
1a4d82fc JJ |
1942 | } |
1943 | ||
85aaf69f | 1944 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1945 | impl<T> DoubleEndedIterator for IntoIter<T> { |
1946 | #[inline] | |
85aaf69f | 1947 | fn next_back(&mut self) -> Option<T> { |
1a4d82fc JJ |
1948 | unsafe { |
1949 | if self.end == self.ptr { | |
1950 | None | |
1951 | } else { | |
1952 | if mem::size_of::<T>() == 0 { | |
1953 | // See above for why 'ptr.offset' isn't used | |
5bcae85e | 1954 | self.end = arith_offset(self.end as *const i8, -1) as *mut T; |
1a4d82fc JJ |
1955 | |
1956 | // Use a non-null pointer value | |
85aaf69f | 1957 | Some(ptr::read(EMPTY as *mut T)) |
1a4d82fc JJ |
1958 | } else { |
1959 | self.end = self.end.offset(-1); | |
1960 | ||
e9174d1e | 1961 | Some(ptr::read(self.end)) |
1a4d82fc JJ |
1962 | } |
1963 | } | |
1964 | } | |
1965 | } | |
1966 | } | |
1967 | ||
85aaf69f | 1968 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1969 | impl<T> ExactSizeIterator for IntoIter<T> {} |
1970 | ||
9e0c209e SL |
1971 | #[unstable(feature = "fused", issue = "35602")] |
1972 | impl<T> FusedIterator for IntoIter<T> {} | |
1973 | ||
c30ab7b3 SL |
1974 | #[unstable(feature = "trusted_len", issue = "37572")] |
1975 | unsafe impl<T> TrustedLen for IntoIter<T> {} | |
1976 | ||
7453a54e SL |
1977 | #[stable(feature = "vec_into_iter_clone", since = "1.8.0")] |
1978 | impl<T: Clone> Clone for IntoIter<T> { | |
1979 | fn clone(&self) -> IntoIter<T> { | |
5bcae85e | 1980 | self.as_slice().to_owned().into_iter() |
7453a54e SL |
1981 | } |
1982 | } | |
1983 | ||
85aaf69f | 1984 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1985 | impl<T> Drop for IntoIter<T> { |
b039eaaf | 1986 | #[unsafe_destructor_blind_to_params] |
1a4d82fc JJ |
1987 | fn drop(&mut self) { |
1988 | // destroy the remaining elements | |
5bcae85e | 1989 | for _x in self.by_ref() {} |
c1a9b12d SL |
1990 | |
1991 | // RawVec handles deallocation | |
5bcae85e | 1992 | let _ = unsafe { RawVec::from_raw_parts(*self.buf, self.cap) }; |
1a4d82fc JJ |
1993 | } |
1994 | } | |
1995 | ||
d9579d0f | 1996 | /// A draining iterator for `Vec<T>`. |
5bcae85e SL |
1997 | /// |
1998 | /// This `struct` is created by the [`drain`] method on [`Vec`]. | |
1999 | /// | |
2000 | /// [`drain`]: struct.Vec.html#method.drain | |
2001 | /// [`Vec`]: struct.Vec.html | |
92a42be0 | 2002 | #[stable(feature = "drain", since = "1.6.0")] |
d9579d0f AL |
2003 | pub struct Drain<'a, T: 'a> { |
2004 | /// Index of tail to preserve | |
2005 | tail_start: usize, | |
2006 | /// Length of tail | |
2007 | tail_len: usize, | |
2008 | /// Current remaining range to remove | |
5bcae85e SL |
2009 | iter: slice::Iter<'a, T>, |
2010 | vec: Shared<Vec<T>>, | |
1a4d82fc JJ |
2011 | } |
2012 | ||
92a42be0 | 2013 | #[stable(feature = "drain", since = "1.6.0")] |
c34b1796 | 2014 | unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {} |
92a42be0 | 2015 | #[stable(feature = "drain", since = "1.6.0")] |
c34b1796 AL |
2016 | unsafe impl<'a, T: Send> Send for Drain<'a, T> {} |
2017 | ||
c30ab7b3 | 2018 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2019 | impl<'a, T> Iterator for Drain<'a, T> { |
2020 | type Item = T; | |
2021 | ||
2022 | #[inline] | |
2023 | fn next(&mut self) -> Option<T> { | |
92a42be0 | 2024 | self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) }) |
1a4d82fc JJ |
2025 | } |
2026 | ||
85aaf69f | 2027 | fn size_hint(&self) -> (usize, Option<usize>) { |
d9579d0f | 2028 | self.iter.size_hint() |
1a4d82fc JJ |
2029 | } |
2030 | } | |
2031 | ||
c30ab7b3 | 2032 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2033 | impl<'a, T> DoubleEndedIterator for Drain<'a, T> { |
2034 | #[inline] | |
2035 | fn next_back(&mut self) -> Option<T> { | |
92a42be0 | 2036 | self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) }) |
1a4d82fc JJ |
2037 | } |
2038 | } | |
2039 | ||
c30ab7b3 | 2040 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2041 | impl<'a, T> Drop for Drain<'a, T> { |
2042 | fn drop(&mut self) { | |
d9579d0f | 2043 | // exhaust self first |
92a42be0 | 2044 | while let Some(_) = self.next() {} |
1a4d82fc | 2045 | |
d9579d0f AL |
2046 | if self.tail_len > 0 { |
2047 | unsafe { | |
5bcae85e | 2048 | let source_vec = &mut **self.vec; |
d9579d0f AL |
2049 | // memmove back untouched tail, update to new length |
2050 | let start = source_vec.len(); | |
2051 | let tail = self.tail_start; | |
2052 | let src = source_vec.as_ptr().offset(tail as isize); | |
2053 | let dst = source_vec.as_mut_ptr().offset(start as isize); | |
2054 | ptr::copy(src, dst, self.tail_len); | |
2055 | source_vec.set_len(start + self.tail_len); | |
2056 | } | |
2057 | } | |
1a4d82fc JJ |
2058 | } |
2059 | } | |
2060 | ||
d9579d0f | 2061 | |
c30ab7b3 | 2062 | #[stable(feature = "drain", since = "1.6.0")] |
d9579d0f | 2063 | impl<'a, T> ExactSizeIterator for Drain<'a, T> {} |
9e0c209e SL |
2064 | |
2065 | #[unstable(feature = "fused", issue = "35602")] | |
2066 | impl<'a, T> FusedIterator for Drain<'a, T> {} |