]>
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 | 11 | //! A contiguous growable array type with heap-allocated contents, written |
041b39d2 | 12 | //! `Vec<T>`. |
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 | //! | |
cc61c64b | 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 | |
cc61c64b | 61 | //! [`new`]: ../../std/vec/struct.Vec.html#method.new |
c30ab7b3 SL |
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 | |
0531ce1d | 69 | use core::cmp::{self, Ordering}; |
1a4d82fc JJ |
70 | use core::fmt; |
71 | use core::hash::{self, Hash}; | |
54a0048b | 72 | use core::intrinsics::{arith_offset, assume}; |
c30ab7b3 | 73 | use core::iter::{FromIterator, FusedIterator, TrustedLen}; |
ff7c6d11 | 74 | use core::marker::PhantomData; |
1a4d82fc | 75 | use core::mem; |
0531ce1d | 76 | use core::ops::Bound::{Excluded, Included, Unbounded}; |
83c7162d | 77 | use core::ops::{Index, IndexMut, RangeBounds}; |
1a4d82fc JJ |
78 | use core::ops; |
79 | use core::ptr; | |
2c00a5a8 | 80 | use core::ptr::NonNull; |
85aaf69f | 81 | use core::slice; |
85aaf69f | 82 | |
8faf50e0 | 83 | use collections::CollectionAllocErr; |
041b39d2 XL |
84 | use borrow::ToOwned; |
85 | use borrow::Cow; | |
86 | use boxed::Box; | |
87 | use raw_vec::RawVec; | |
d9579d0f | 88 | |
c30ab7b3 | 89 | /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'. |
1a4d82fc JJ |
90 | /// |
91 | /// # Examples | |
92 | /// | |
93 | /// ``` | |
94 | /// let mut vec = Vec::new(); | |
85aaf69f SL |
95 | /// vec.push(1); |
96 | /// vec.push(2); | |
1a4d82fc JJ |
97 | /// |
98 | /// assert_eq!(vec.len(), 2); | |
99 | /// assert_eq!(vec[0], 1); | |
100 | /// | |
101 | /// assert_eq!(vec.pop(), Some(2)); | |
102 | /// assert_eq!(vec.len(), 1); | |
103 | /// | |
85aaf69f | 104 | /// vec[0] = 7; |
1a4d82fc JJ |
105 | /// assert_eq!(vec[0], 7); |
106 | /// | |
62682a34 | 107 | /// vec.extend([1, 2, 3].iter().cloned()); |
1a4d82fc | 108 | /// |
62682a34 | 109 | /// for x in &vec { |
1a4d82fc JJ |
110 | /// println!("{}", x); |
111 | /// } | |
c34b1796 | 112 | /// assert_eq!(vec, [7, 1, 2, 3]); |
1a4d82fc JJ |
113 | /// ``` |
114 | /// | |
c30ab7b3 | 115 | /// The [`vec!`] macro is provided to make initialization more convenient: |
1a4d82fc JJ |
116 | /// |
117 | /// ``` | |
85aaf69f | 118 | /// let mut vec = vec![1, 2, 3]; |
1a4d82fc | 119 | /// vec.push(4); |
c34b1796 | 120 | /// assert_eq!(vec, [1, 2, 3, 4]); |
1a4d82fc JJ |
121 | /// ``` |
122 | /// | |
c1a9b12d SL |
123 | /// It can also initialize each element of a `Vec<T>` with a given value: |
124 | /// | |
125 | /// ``` | |
126 | /// let vec = vec![0; 5]; | |
127 | /// assert_eq!(vec, [0, 0, 0, 0, 0]); | |
128 | /// ``` | |
129 | /// | |
1a4d82fc JJ |
130 | /// Use a `Vec<T>` as an efficient stack: |
131 | /// | |
132 | /// ``` | |
133 | /// let mut stack = Vec::new(); | |
134 | /// | |
85aaf69f SL |
135 | /// stack.push(1); |
136 | /// stack.push(2); | |
137 | /// stack.push(3); | |
1a4d82fc | 138 | /// |
bd371182 | 139 | /// while let Some(top) = stack.pop() { |
1a4d82fc JJ |
140 | /// // Prints 3, 2, 1 |
141 | /// println!("{}", top); | |
142 | /// } | |
143 | /// ``` | |
144 | /// | |
7453a54e SL |
145 | /// # Indexing |
146 | /// | |
c30ab7b3 SL |
147 | /// The `Vec` type allows to access values by index, because it implements the |
148 | /// [`Index`] trait. An example will be more explicit: | |
7453a54e SL |
149 | /// |
150 | /// ``` | |
c30ab7b3 | 151 | /// let v = vec![0, 2, 4, 6]; |
7453a54e SL |
152 | /// println!("{}", v[1]); // it will display '2' |
153 | /// ``` | |
154 | /// | |
c30ab7b3 | 155 | /// However be careful: if you try to access an index which isn't in the `Vec`, |
7453a54e SL |
156 | /// your software will panic! You cannot do this: |
157 | /// | |
041b39d2 | 158 | /// ```should_panic |
c30ab7b3 | 159 | /// let v = vec![0, 2, 4, 6]; |
7453a54e SL |
160 | /// println!("{}", v[6]); // it will panic! |
161 | /// ``` | |
162 | /// | |
163 | /// In conclusion: always check if the index you want to get really exists | |
164 | /// before doing it. | |
165 | /// | |
166 | /// # Slicing | |
167 | /// | |
c30ab7b3 SL |
168 | /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects. |
169 | /// To get a slice, use `&`. Example: | |
7453a54e SL |
170 | /// |
171 | /// ``` | |
172 | /// fn read_slice(slice: &[usize]) { | |
173 | /// // ... | |
174 | /// } | |
175 | /// | |
c30ab7b3 | 176 | /// let v = vec![0, 1]; |
7453a54e SL |
177 | /// read_slice(&v); |
178 | /// | |
179 | /// // ... and that's all! | |
180 | /// // you can also do it like this: | |
181 | /// let x : &[usize] = &v; | |
182 | /// ``` | |
183 | /// | |
184 | /// In Rust, it's more common to pass slices as arguments rather than vectors | |
c30ab7b3 SL |
185 | /// when you just want to provide a read access. The same goes for [`String`] and |
186 | /// [`&str`]. | |
7453a54e | 187 | /// |
1a4d82fc JJ |
188 | /// # Capacity and reallocation |
189 | /// | |
c34b1796 AL |
190 | /// The capacity of a vector is the amount of space allocated for any future |
191 | /// elements that will be added onto the vector. This is not to be confused with | |
192 | /// the *length* of a vector, which specifies the number of actual elements | |
193 | /// within the vector. If a vector's length exceeds its capacity, its capacity | |
194 | /// will automatically be increased, but its elements will have to be | |
1a4d82fc JJ |
195 | /// reallocated. |
196 | /// | |
c34b1796 AL |
197 | /// For example, a vector with capacity 10 and length 0 would be an empty vector |
198 | /// with space for 10 more elements. Pushing 10 or fewer elements onto the | |
199 | /// vector will not change its capacity or cause reallocation to occur. However, | |
200 | /// if the vector's length is increased to 11, it will have to reallocate, which | |
c30ab7b3 | 201 | /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`] |
c34b1796 | 202 | /// whenever possible to specify how big the vector is expected to get. |
b039eaaf SL |
203 | /// |
204 | /// # Guarantees | |
205 | /// | |
c30ab7b3 | 206 | /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees |
b039eaaf SL |
207 | /// about its design. This ensures that it's as low-overhead as possible in |
208 | /// the general case, and can be correctly manipulated in primitive ways | |
209 | /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`. | |
210 | /// If additional type parameters are added (e.g. to support custom allocators), | |
211 | /// overriding their defaults may change the behavior. | |
212 | /// | |
c30ab7b3 | 213 | /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length) |
b039eaaf SL |
214 | /// triplet. No more, no less. The order of these fields is completely |
215 | /// unspecified, and you should use the appropriate methods to modify these. | |
216 | /// The pointer will never be null, so this type is null-pointer-optimized. | |
217 | /// | |
218 | /// However, the pointer may not actually point to allocated memory. In particular, | |
cc61c64b XL |
219 | /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`], |
220 | /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`] | |
c30ab7b3 SL |
221 | /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized |
222 | /// types inside a `Vec`, it will not allocate space for them. *Note that in this case | |
cc61c64b | 223 | /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only |
041b39d2 | 224 | /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation |
ff7c6d11 XL |
225 | /// details are very subtle — if you intend to allocate memory using a `Vec` |
226 | /// and use it for something else (either to pass to unsafe code, or to build your | |
227 | /// own memory-backed collection), be sure to deallocate this memory by using | |
228 | /// `from_raw_parts` to recover the `Vec` and then dropping it. | |
b039eaaf | 229 | /// |
c30ab7b3 | 230 | /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap |
b039eaaf | 231 | /// (as defined by the allocator Rust is configured to use by default), and its |
0531ce1d XL |
232 | /// pointer points to [`len`] initialized, contiguous elements in order (what |
233 | /// you would see if you coerced it to a slice), followed by [`capacity`]` - | |
234 | /// `[`len`] logically uninitialized, contiguous elements. | |
b039eaaf | 235 | /// |
c30ab7b3 | 236 | /// `Vec` will never perform a "small optimization" where elements are actually |
b039eaaf SL |
237 | /// stored on the stack for two reasons: |
238 | /// | |
239 | /// * It would make it more difficult for unsafe code to correctly manipulate | |
c30ab7b3 SL |
240 | /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were |
241 | /// only moved, and it would be more difficult to determine if a `Vec` had | |
b039eaaf SL |
242 | /// actually allocated memory. |
243 | /// | |
244 | /// * It would penalize the general case, incurring an additional branch | |
245 | /// on every access. | |
246 | /// | |
c30ab7b3 SL |
247 | /// `Vec` will never automatically shrink itself, even if completely empty. This |
248 | /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec` | |
cc61c64b | 249 | /// and then filling it back up to the same [`len`] should incur no calls to |
c30ab7b3 | 250 | /// the allocator. If you wish to free up unused memory, use |
cc61c64b | 251 | /// [`shrink_to_fit`][`shrink_to_fit`]. |
b039eaaf | 252 | /// |
c30ab7b3 SL |
253 | /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is |
254 | /// sufficient. [`push`] and [`insert`] *will* (re)allocate if | |
cc61c64b | 255 | /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely |
c30ab7b3 SL |
256 | /// accurate, and can be relied on. It can even be used to manually free the memory |
257 | /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even | |
258 | /// when not necessary. | |
b039eaaf | 259 | /// |
c30ab7b3 SL |
260 | /// `Vec` does not guarantee any particular growth strategy when reallocating |
261 | /// when full, nor when [`reserve`] is called. The current strategy is basic | |
b039eaaf | 262 | /// and it may prove desirable to use a non-constant growth factor. Whatever |
c30ab7b3 | 263 | /// strategy is used will of course guarantee `O(1)` amortized [`push`]. |
b039eaaf | 264 | /// |
c30ab7b3 SL |
265 | /// `vec![x; n]`, `vec![a, b, c, d]`, and |
266 | /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec` | |
cc61c64b | 267 | /// with exactly the requested capacity. If [`len`]` == `[`capacity`], |
c30ab7b3 SL |
268 | /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to |
269 | /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements. | |
b039eaaf | 270 | /// |
c30ab7b3 | 271 | /// `Vec` will not specifically overwrite any data that is removed from it, |
b039eaaf SL |
272 | /// but also won't specifically preserve it. Its uninitialized memory is |
273 | /// scratch space that it may use however it wants. It will generally just do | |
274 | /// whatever is most efficient or otherwise easy to implement. Do not rely on | |
c30ab7b3 SL |
275 | /// removed data to be erased for security purposes. Even if you drop a `Vec`, its |
276 | /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory | |
b039eaaf | 277 | /// first, that may not actually happen because the optimizer does not consider |
7cac9316 XL |
278 | /// this a side-effect that must be preserved. There is one case which we will |
279 | /// not break, however: using `unsafe` code to write to the excess capacity, | |
280 | /// and then increasing the length to match, is always valid. | |
b039eaaf | 281 | /// |
0531ce1d XL |
282 | /// `Vec` does not currently guarantee the order in which elements are dropped. |
283 | /// The order has changed in the past and may change again. | |
b039eaaf | 284 | /// |
c30ab7b3 SL |
285 | /// [`vec!`]: ../../std/macro.vec.html |
286 | /// [`Index`]: ../../std/ops/trait.Index.html | |
287 | /// [`String`]: ../../std/string/struct.String.html | |
288 | /// [`&str`]: ../../std/primitive.str.html | |
289 | /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity | |
cc61c64b XL |
290 | /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new |
291 | /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit | |
292 | /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity | |
293 | /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html | |
294 | /// [`len`]: ../../std/vec/struct.Vec.html#method.len | |
c30ab7b3 SL |
295 | /// [`push`]: ../../std/vec/struct.Vec.html#method.push |
296 | /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert | |
297 | /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve | |
298 | /// [owned slice]: ../../std/boxed/struct.Box.html | |
85aaf69f | 299 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 300 | pub struct Vec<T> { |
c1a9b12d | 301 | buf: RawVec<T>, |
85aaf69f | 302 | len: usize, |
1a4d82fc JJ |
303 | } |
304 | ||
1a4d82fc JJ |
305 | //////////////////////////////////////////////////////////////////////////////// |
306 | // Inherent methods | |
307 | //////////////////////////////////////////////////////////////////////////////// | |
308 | ||
309 | impl<T> Vec<T> { | |
310 | /// Constructs a new, empty `Vec<T>`. | |
311 | /// | |
312 | /// The vector will not allocate until elements are pushed onto it. | |
313 | /// | |
314 | /// # Examples | |
315 | /// | |
316 | /// ``` | |
92a42be0 | 317 | /// # #![allow(unused_mut)] |
85aaf69f | 318 | /// let mut vec: Vec<i32> = Vec::new(); |
1a4d82fc JJ |
319 | /// ``` |
320 | #[inline] | |
85aaf69f | 321 | #[stable(feature = "rust1", since = "1.0.0")] |
83c7162d XL |
322 | #[rustc_const_unstable(feature = "const_vec_new")] |
323 | pub const fn new() -> Vec<T> { | |
92a42be0 SL |
324 | Vec { |
325 | buf: RawVec::new(), | |
326 | len: 0, | |
327 | } | |
1a4d82fc JJ |
328 | } |
329 | ||
330 | /// Constructs a new, empty `Vec<T>` with the specified capacity. | |
331 | /// | |
e9174d1e SL |
332 | /// The vector will be able to hold exactly `capacity` elements without |
333 | /// reallocating. If `capacity` is 0, the vector will not allocate. | |
1a4d82fc | 334 | /// |
0531ce1d XL |
335 | /// It is important to note that although the returned vector has the |
336 | /// *capacity* specified, the vector will have a zero *length*. For an | |
337 | /// explanation of the difference between length and capacity, see | |
338 | /// *[Capacity and reallocation]*. | |
c30ab7b3 SL |
339 | /// |
340 | /// [Capacity and reallocation]: #capacity-and-reallocation | |
1a4d82fc JJ |
341 | /// |
342 | /// # Examples | |
343 | /// | |
344 | /// ``` | |
9346a6ac | 345 | /// let mut vec = Vec::with_capacity(10); |
1a4d82fc JJ |
346 | /// |
347 | /// // The vector contains no items, even though it has capacity for more | |
348 | /// assert_eq!(vec.len(), 0); | |
349 | /// | |
350 | /// // These are all done without reallocating... | |
85aaf69f | 351 | /// for i in 0..10 { |
1a4d82fc JJ |
352 | /// vec.push(i); |
353 | /// } | |
354 | /// | |
355 | /// // ...but this may make the vector reallocate | |
356 | /// vec.push(11); | |
357 | /// ``` | |
358 | #[inline] | |
85aaf69f SL |
359 | #[stable(feature = "rust1", since = "1.0.0")] |
360 | pub fn with_capacity(capacity: usize) -> Vec<T> { | |
92a42be0 SL |
361 | Vec { |
362 | buf: RawVec::with_capacity(capacity), | |
363 | len: 0, | |
364 | } | |
1a4d82fc JJ |
365 | } |
366 | ||
367 | /// Creates a `Vec<T>` directly from the raw components of another vector. | |
368 | /// | |
b039eaaf | 369 | /// # Safety |
c1a9b12d SL |
370 | /// |
371 | /// This is highly unsafe, due to the number of invariants that aren't | |
372 | /// checked: | |
373 | /// | |
c30ab7b3 | 374 | /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>` |
c1a9b12d | 375 | /// (at least, it's highly likely to be incorrect if it wasn't). |
ea8adc8c | 376 | /// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with. |
5bcae85e | 377 | /// * `length` needs to be less than or equal to `capacity`. |
c1a9b12d SL |
378 | /// * `capacity` needs to be the capacity that the pointer was allocated with. |
379 | /// | |
380 | /// Violating these may cause problems like corrupting the allocator's | |
3b2f2976 | 381 | /// internal data structures. For example it is **not** safe |
32a655c1 | 382 | /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`. |
1a4d82fc | 383 | /// |
5bcae85e SL |
384 | /// The ownership of `ptr` is effectively transferred to the |
385 | /// `Vec<T>` which may then deallocate, reallocate or change the | |
386 | /// contents of memory pointed to by the pointer at will. Ensure | |
387 | /// that nothing else uses the pointer after calling this | |
388 | /// function. | |
389 | /// | |
c30ab7b3 SL |
390 | /// [`String`]: ../../std/string/struct.String.html |
391 | /// | |
1a4d82fc JJ |
392 | /// # Examples |
393 | /// | |
394 | /// ``` | |
395 | /// use std::ptr; | |
396 | /// use std::mem; | |
397 | /// | |
398 | /// fn main() { | |
85aaf69f | 399 | /// let mut v = vec![1, 2, 3]; |
1a4d82fc JJ |
400 | /// |
401 | /// // Pull out the various important pieces of information about `v` | |
402 | /// let p = v.as_mut_ptr(); | |
403 | /// let len = v.len(); | |
404 | /// let cap = v.capacity(); | |
405 | /// | |
406 | /// unsafe { | |
407 | /// // Cast `v` into the void: no destructor run, so we are in | |
408 | /// // complete control of the allocation to which `p` points. | |
409 | /// mem::forget(v); | |
410 | /// | |
411 | /// // Overwrite memory with 4, 5, 6 | |
85aaf69f | 412 | /// for i in 0..len as isize { |
1a4d82fc JJ |
413 | /// ptr::write(p.offset(i), 4 + i); |
414 | /// } | |
415 | /// | |
416 | /// // Put everything back together into a Vec | |
417 | /// let rebuilt = Vec::from_raw_parts(p, len, cap); | |
c34b1796 | 418 | /// assert_eq!(rebuilt, [4, 5, 6]); |
1a4d82fc JJ |
419 | /// } |
420 | /// } | |
421 | /// ``` | |
85aaf69f | 422 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 423 | pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> { |
85aaf69f | 424 | Vec { |
c1a9b12d | 425 | buf: RawVec::from_raw_parts(ptr, capacity), |
85aaf69f | 426 | len: length, |
85aaf69f | 427 | } |
1a4d82fc JJ |
428 | } |
429 | ||
1a4d82fc JJ |
430 | /// Returns the number of elements the vector can hold without |
431 | /// reallocating. | |
432 | /// | |
433 | /// # Examples | |
434 | /// | |
435 | /// ``` | |
85aaf69f | 436 | /// let vec: Vec<i32> = Vec::with_capacity(10); |
1a4d82fc JJ |
437 | /// assert_eq!(vec.capacity(), 10); |
438 | /// ``` | |
439 | #[inline] | |
85aaf69f SL |
440 | #[stable(feature = "rust1", since = "1.0.0")] |
441 | pub fn capacity(&self) -> usize { | |
c1a9b12d | 442 | self.buf.cap() |
1a4d82fc JJ |
443 | } |
444 | ||
c34b1796 AL |
445 | /// Reserves capacity for at least `additional` more elements to be inserted |
446 | /// in the given `Vec<T>`. The collection may reserve more space to avoid | |
8bb4bdeb XL |
447 | /// frequent reallocations. After calling `reserve`, capacity will be |
448 | /// greater than or equal to `self.len() + additional`. Does nothing if | |
449 | /// capacity is already sufficient. | |
1a4d82fc JJ |
450 | /// |
451 | /// # Panics | |
452 | /// | |
85aaf69f | 453 | /// Panics if the new capacity overflows `usize`. |
1a4d82fc JJ |
454 | /// |
455 | /// # Examples | |
456 | /// | |
457 | /// ``` | |
85aaf69f | 458 | /// let mut vec = vec![1]; |
1a4d82fc JJ |
459 | /// vec.reserve(10); |
460 | /// assert!(vec.capacity() >= 11); | |
461 | /// ``` | |
85aaf69f SL |
462 | #[stable(feature = "rust1", since = "1.0.0")] |
463 | pub fn reserve(&mut self, additional: usize) { | |
c1a9b12d | 464 | self.buf.reserve(self.len, additional); |
1a4d82fc JJ |
465 | } |
466 | ||
467 | /// Reserves the minimum capacity for exactly `additional` more elements to | |
8bb4bdeb XL |
468 | /// be inserted in the given `Vec<T>`. After calling `reserve_exact`, |
469 | /// capacity will be greater than or equal to `self.len() + additional`. | |
470 | /// Does nothing if the capacity is already sufficient. | |
1a4d82fc JJ |
471 | /// |
472 | /// Note that the allocator may give the collection more space than it | |
473 | /// requests. Therefore capacity can not be relied upon to be precisely | |
474 | /// minimal. Prefer `reserve` if future insertions are expected. | |
475 | /// | |
476 | /// # Panics | |
477 | /// | |
85aaf69f | 478 | /// Panics if the new capacity overflows `usize`. |
1a4d82fc JJ |
479 | /// |
480 | /// # Examples | |
481 | /// | |
482 | /// ``` | |
85aaf69f | 483 | /// let mut vec = vec![1]; |
1a4d82fc JJ |
484 | /// vec.reserve_exact(10); |
485 | /// assert!(vec.capacity() >= 11); | |
486 | /// ``` | |
85aaf69f SL |
487 | #[stable(feature = "rust1", since = "1.0.0")] |
488 | pub fn reserve_exact(&mut self, additional: usize) { | |
c1a9b12d | 489 | self.buf.reserve_exact(self.len, additional); |
1a4d82fc JJ |
490 | } |
491 | ||
0531ce1d XL |
492 | /// Tries to reserve capacity for at least `additional` more elements to be inserted |
493 | /// in the given `Vec<T>`. The collection may reserve more space to avoid | |
494 | /// frequent reallocations. After calling `reserve`, capacity will be | |
495 | /// greater than or equal to `self.len() + additional`. Does nothing if | |
496 | /// capacity is already sufficient. | |
497 | /// | |
498 | /// # Errors | |
499 | /// | |
500 | /// If the capacity overflows, or the allocator reports a failure, then an error | |
501 | /// is returned. | |
502 | /// | |
503 | /// # Examples | |
504 | /// | |
505 | /// ``` | |
506 | /// #![feature(try_reserve)] | |
507 | /// use std::collections::CollectionAllocErr; | |
508 | /// | |
509 | /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> { | |
510 | /// let mut output = Vec::new(); | |
511 | /// | |
512 | /// // Pre-reserve the memory, exiting if we can't | |
513 | /// output.try_reserve(data.len())?; | |
514 | /// | |
515 | /// // Now we know this can't OOM in the middle of our complex work | |
516 | /// output.extend(data.iter().map(|&val| { | |
517 | /// val * 2 + 5 // very complicated | |
518 | /// })); | |
519 | /// | |
520 | /// Ok(output) | |
521 | /// } | |
522 | /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?"); | |
523 | /// ``` | |
524 | #[unstable(feature = "try_reserve", reason = "new API", issue="48043")] | |
525 | pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { | |
526 | self.buf.try_reserve(self.len, additional) | |
527 | } | |
528 | ||
529 | /// Tries to reserves the minimum capacity for exactly `additional` more elements to | |
530 | /// be inserted in the given `Vec<T>`. After calling `reserve_exact`, | |
531 | /// capacity will be greater than or equal to `self.len() + additional`. | |
532 | /// Does nothing if the capacity is already sufficient. | |
533 | /// | |
534 | /// Note that the allocator may give the collection more space than it | |
535 | /// requests. Therefore capacity can not be relied upon to be precisely | |
536 | /// minimal. Prefer `reserve` if future insertions are expected. | |
537 | /// | |
538 | /// # Errors | |
539 | /// | |
540 | /// If the capacity overflows, or the allocator reports a failure, then an error | |
541 | /// is returned. | |
542 | /// | |
543 | /// # Examples | |
544 | /// | |
545 | /// ``` | |
546 | /// #![feature(try_reserve)] | |
547 | /// use std::collections::CollectionAllocErr; | |
548 | /// | |
549 | /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> { | |
550 | /// let mut output = Vec::new(); | |
551 | /// | |
552 | /// // Pre-reserve the memory, exiting if we can't | |
553 | /// output.try_reserve(data.len())?; | |
554 | /// | |
555 | /// // Now we know this can't OOM in the middle of our complex work | |
556 | /// output.extend(data.iter().map(|&val| { | |
557 | /// val * 2 + 5 // very complicated | |
558 | /// })); | |
559 | /// | |
560 | /// Ok(output) | |
561 | /// } | |
562 | /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?"); | |
563 | /// ``` | |
564 | #[unstable(feature = "try_reserve", reason = "new API", issue="48043")] | |
565 | pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { | |
566 | self.buf.try_reserve_exact(self.len, additional) | |
567 | } | |
568 | ||
1a4d82fc JJ |
569 | /// Shrinks the capacity of the vector as much as possible. |
570 | /// | |
571 | /// It will drop down as close as possible to the length but the allocator | |
572 | /// may still inform the vector that there is space for a few more elements. | |
573 | /// | |
574 | /// # Examples | |
575 | /// | |
576 | /// ``` | |
85aaf69f | 577 | /// let mut vec = Vec::with_capacity(10); |
62682a34 | 578 | /// vec.extend([1, 2, 3].iter().cloned()); |
1a4d82fc JJ |
579 | /// assert_eq!(vec.capacity(), 10); |
580 | /// vec.shrink_to_fit(); | |
581 | /// assert!(vec.capacity() >= 3); | |
582 | /// ``` | |
85aaf69f | 583 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 584 | pub fn shrink_to_fit(&mut self) { |
83c7162d XL |
585 | if self.capacity() != self.len { |
586 | self.buf.shrink_to_fit(self.len); | |
587 | } | |
1a4d82fc JJ |
588 | } |
589 | ||
0531ce1d XL |
590 | /// Shrinks the capacity of the vector with a lower bound. |
591 | /// | |
592 | /// The capacity will remain at least as large as both the length | |
593 | /// and the supplied value. | |
594 | /// | |
595 | /// Panics if the current capacity is smaller than the supplied | |
596 | /// minimum capacity. | |
597 | /// | |
598 | /// # Examples | |
599 | /// | |
600 | /// ``` | |
601 | /// #![feature(shrink_to)] | |
602 | /// let mut vec = Vec::with_capacity(10); | |
603 | /// vec.extend([1, 2, 3].iter().cloned()); | |
604 | /// assert_eq!(vec.capacity(), 10); | |
605 | /// vec.shrink_to(4); | |
606 | /// assert!(vec.capacity() >= 4); | |
607 | /// vec.shrink_to(0); | |
608 | /// assert!(vec.capacity() >= 3); | |
609 | /// ``` | |
610 | #[unstable(feature = "shrink_to", reason = "new API", issue="0")] | |
611 | pub fn shrink_to(&mut self, min_capacity: usize) { | |
612 | self.buf.shrink_to_fit(cmp::max(self.len, min_capacity)); | |
613 | } | |
614 | ||
c30ab7b3 | 615 | /// Converts the vector into [`Box<[T]>`][owned slice]. |
1a4d82fc | 616 | /// |
ea8adc8c | 617 | /// Note that this will drop any excess capacity. |
c30ab7b3 SL |
618 | /// |
619 | /// [owned slice]: ../../std/boxed/struct.Box.html | |
5bcae85e SL |
620 | /// |
621 | /// # Examples | |
622 | /// | |
623 | /// ``` | |
624 | /// let v = vec![1, 2, 3]; | |
625 | /// | |
626 | /// let slice = v.into_boxed_slice(); | |
627 | /// ``` | |
628 | /// | |
629 | /// Any excess capacity is removed: | |
630 | /// | |
631 | /// ``` | |
632 | /// let mut vec = Vec::with_capacity(10); | |
633 | /// vec.extend([1, 2, 3].iter().cloned()); | |
634 | /// | |
635 | /// assert_eq!(vec.capacity(), 10); | |
636 | /// let slice = vec.into_boxed_slice(); | |
637 | /// assert_eq!(slice.into_vec().capacity(), 3); | |
638 | /// ``` | |
c34b1796 | 639 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 640 | pub fn into_boxed_slice(mut self) -> Box<[T]> { |
1a4d82fc | 641 | unsafe { |
c1a9b12d SL |
642 | self.shrink_to_fit(); |
643 | let buf = ptr::read(&self.buf); | |
1a4d82fc | 644 | mem::forget(self); |
c1a9b12d | 645 | buf.into_box() |
1a4d82fc JJ |
646 | } |
647 | } | |
648 | ||
5bcae85e SL |
649 | /// Shortens the vector, keeping the first `len` elements and dropping |
650 | /// the rest. | |
1a4d82fc JJ |
651 | /// |
652 | /// If `len` is greater than the vector's current length, this has no | |
653 | /// effect. | |
654 | /// | |
5bcae85e SL |
655 | /// The [`drain`] method can emulate `truncate`, but causes the excess |
656 | /// elements to be returned instead of dropped. | |
657 | /// | |
8bb4bdeb XL |
658 | /// Note that this method has no effect on the allocated capacity |
659 | /// of the vector. | |
660 | /// | |
1a4d82fc JJ |
661 | /// # Examples |
662 | /// | |
5bcae85e SL |
663 | /// Truncating a five element vector to two elements: |
664 | /// | |
1a4d82fc | 665 | /// ``` |
92a42be0 | 666 | /// let mut vec = vec![1, 2, 3, 4, 5]; |
1a4d82fc | 667 | /// vec.truncate(2); |
c34b1796 | 668 | /// assert_eq!(vec, [1, 2]); |
1a4d82fc | 669 | /// ``` |
5bcae85e SL |
670 | /// |
671 | /// No truncation occurs when `len` is greater than the vector's current | |
672 | /// length: | |
673 | /// | |
674 | /// ``` | |
675 | /// let mut vec = vec![1, 2, 3]; | |
676 | /// vec.truncate(8); | |
677 | /// assert_eq!(vec, [1, 2, 3]); | |
678 | /// ``` | |
679 | /// | |
680 | /// Truncating when `len == 0` is equivalent to calling the [`clear`] | |
681 | /// method. | |
682 | /// | |
683 | /// ``` | |
684 | /// let mut vec = vec![1, 2, 3]; | |
685 | /// vec.truncate(0); | |
686 | /// assert_eq!(vec, []); | |
687 | /// ``` | |
688 | /// | |
689 | /// [`clear`]: #method.clear | |
690 | /// [`drain`]: #method.drain | |
85aaf69f SL |
691 | #[stable(feature = "rust1", since = "1.0.0")] |
692 | pub fn truncate(&mut self, len: usize) { | |
b7449926 | 693 | let current_len = self.len; |
1a4d82fc | 694 | unsafe { |
b7449926 XL |
695 | let mut ptr = self.as_mut_ptr().add(self.len); |
696 | // Set the final length at the end, keeping in mind that | |
697 | // dropping an element might panic. Works around a missed | |
698 | // optimization, as seen in the following issue: | |
699 | // https://github.com/rust-lang/rust/issues/51802 | |
700 | let mut local_len = SetLenOnDrop::new(&mut self.len); | |
701 | ||
1a4d82fc | 702 | // drop any extra elements |
b7449926 XL |
703 | for _ in len..current_len { |
704 | local_len.decrement_len(1); | |
705 | ptr = ptr.offset(-1); | |
706 | ptr::drop_in_place(ptr); | |
1a4d82fc JJ |
707 | } |
708 | } | |
709 | } | |
710 | ||
9346a6ac | 711 | /// Extracts a slice containing the entire vector. |
62682a34 SL |
712 | /// |
713 | /// Equivalent to `&s[..]`. | |
5bcae85e SL |
714 | /// |
715 | /// # Examples | |
716 | /// | |
717 | /// ``` | |
718 | /// use std::io::{self, Write}; | |
719 | /// let buffer = vec![1, 2, 3, 5, 8]; | |
720 | /// io::sink().write(buffer.as_slice()).unwrap(); | |
721 | /// ``` | |
1a4d82fc | 722 | #[inline] |
9cc50fc6 | 723 | #[stable(feature = "vec_as_slice", since = "1.7.0")] |
c34b1796 AL |
724 | pub fn as_slice(&self) -> &[T] { |
725 | self | |
726 | } | |
727 | ||
62682a34 SL |
728 | /// Extracts a mutable slice of the entire vector. |
729 | /// | |
730 | /// Equivalent to `&mut s[..]`. | |
5bcae85e SL |
731 | /// |
732 | /// # Examples | |
733 | /// | |
734 | /// ``` | |
735 | /// use std::io::{self, Read}; | |
736 | /// let mut buffer = vec![0; 3]; | |
737 | /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); | |
738 | /// ``` | |
c34b1796 | 739 | #[inline] |
9cc50fc6 | 740 | #[stable(feature = "vec_as_slice", since = "1.7.0")] |
85aaf69f | 741 | pub fn as_mut_slice(&mut self) -> &mut [T] { |
5bcae85e | 742 | self |
1a4d82fc JJ |
743 | } |
744 | ||
1a4d82fc JJ |
745 | /// Sets the length of a vector. |
746 | /// | |
747 | /// This will explicitly set the size of the vector, without actually | |
748 | /// modifying its buffers, so it is up to the caller to ensure that the | |
749 | /// vector is actually the specified size. | |
750 | /// | |
751 | /// # Examples | |
752 | /// | |
753 | /// ``` | |
5bcae85e SL |
754 | /// use std::ptr; |
755 | /// | |
756 | /// let mut vec = vec!['r', 'u', 's', 't']; | |
757 | /// | |
758 | /// unsafe { | |
759 | /// ptr::drop_in_place(&mut vec[3]); | |
760 | /// vec.set_len(3); | |
761 | /// } | |
762 | /// assert_eq!(vec, ['r', 'u', 's']); | |
763 | /// ``` | |
764 | /// | |
765 | /// In this example, there is a memory leak since the memory locations | |
766 | /// owned by the inner vectors were not freed prior to the `set_len` call: | |
767 | /// | |
768 | /// ``` | |
769 | /// let mut vec = vec![vec![1, 0, 0], | |
770 | /// vec![0, 1, 0], | |
771 | /// vec![0, 0, 1]]; | |
1a4d82fc | 772 | /// unsafe { |
5bcae85e SL |
773 | /// vec.set_len(0); |
774 | /// } | |
775 | /// ``` | |
776 | /// | |
777 | /// In this example, the vector gets expanded from zero to four items | |
778 | /// without any memory allocations occurring, resulting in vector | |
779 | /// values of unallocated memory: | |
780 | /// | |
781 | /// ``` | |
782 | /// let mut vec: Vec<char> = Vec::new(); | |
783 | /// | |
784 | /// unsafe { | |
785 | /// vec.set_len(4); | |
1a4d82fc JJ |
786 | /// } |
787 | /// ``` | |
788 | #[inline] | |
85aaf69f SL |
789 | #[stable(feature = "rust1", since = "1.0.0")] |
790 | pub unsafe fn set_len(&mut self, len: usize) { | |
1a4d82fc JJ |
791 | self.len = len; |
792 | } | |
793 | ||
cc61c64b XL |
794 | /// Removes an element from the vector and returns it. |
795 | /// | |
796 | /// The removed element is replaced by the last element of the vector. | |
1a4d82fc JJ |
797 | /// |
798 | /// This does not preserve ordering, but is O(1). | |
799 | /// | |
800 | /// # Panics | |
801 | /// | |
802 | /// Panics if `index` is out of bounds. | |
803 | /// | |
804 | /// # Examples | |
805 | /// | |
806 | /// ``` | |
807 | /// let mut v = vec!["foo", "bar", "baz", "qux"]; | |
808 | /// | |
809 | /// assert_eq!(v.swap_remove(1), "bar"); | |
c34b1796 | 810 | /// assert_eq!(v, ["foo", "qux", "baz"]); |
1a4d82fc JJ |
811 | /// |
812 | /// assert_eq!(v.swap_remove(0), "foo"); | |
c34b1796 | 813 | /// assert_eq!(v, ["baz", "qux"]); |
1a4d82fc JJ |
814 | /// ``` |
815 | #[inline] | |
85aaf69f SL |
816 | #[stable(feature = "rust1", since = "1.0.0")] |
817 | pub fn swap_remove(&mut self, index: usize) -> T { | |
8faf50e0 XL |
818 | unsafe { |
819 | // We replace self[index] with the last element. Note that if the | |
820 | // bounds check on hole succeeds there must be a last element (which | |
821 | // can be self[index] itself). | |
822 | let hole: *mut T = &mut self[index]; | |
823 | let last = ptr::read(self.get_unchecked(self.len - 1)); | |
824 | self.len -= 1; | |
825 | ptr::replace(hole, last) | |
826 | } | |
1a4d82fc JJ |
827 | } |
828 | ||
829 | /// Inserts an element at position `index` within the vector, shifting all | |
7453a54e | 830 | /// elements after it to the right. |
1a4d82fc JJ |
831 | /// |
832 | /// # Panics | |
833 | /// | |
2c00a5a8 | 834 | /// Panics if `index > len`. |
1a4d82fc JJ |
835 | /// |
836 | /// # Examples | |
837 | /// | |
838 | /// ``` | |
85aaf69f | 839 | /// let mut vec = vec![1, 2, 3]; |
1a4d82fc | 840 | /// vec.insert(1, 4); |
c34b1796 | 841 | /// assert_eq!(vec, [1, 4, 2, 3]); |
1a4d82fc | 842 | /// vec.insert(4, 5); |
c34b1796 | 843 | /// assert_eq!(vec, [1, 4, 2, 3, 5]); |
1a4d82fc | 844 | /// ``` |
85aaf69f SL |
845 | #[stable(feature = "rust1", since = "1.0.0")] |
846 | pub fn insert(&mut self, index: usize, element: T) { | |
1a4d82fc JJ |
847 | let len = self.len(); |
848 | assert!(index <= len); | |
c1a9b12d | 849 | |
1a4d82fc | 850 | // space for the new element |
92a42be0 | 851 | if len == self.buf.cap() { |
94b46f34 | 852 | self.reserve(1); |
92a42be0 | 853 | } |
1a4d82fc | 854 | |
92a42be0 SL |
855 | unsafe { |
856 | // infallible | |
1a4d82fc JJ |
857 | // The spot to put the new value |
858 | { | |
b7449926 | 859 | let p = self.as_mut_ptr().add(index); |
1a4d82fc JJ |
860 | // Shift everything over to make space. (Duplicating the |
861 | // `index`th element into two consecutive places.) | |
c1a9b12d | 862 | ptr::copy(p, p.offset(1), len - index); |
1a4d82fc JJ |
863 | // Write it in, overwriting the first copy of the `index`th |
864 | // element. | |
c1a9b12d | 865 | ptr::write(p, element); |
1a4d82fc JJ |
866 | } |
867 | self.set_len(len + 1); | |
868 | } | |
869 | } | |
870 | ||
871 | /// Removes and returns the element at position `index` within the vector, | |
7453a54e | 872 | /// shifting all elements after it to the left. |
1a4d82fc JJ |
873 | /// |
874 | /// # Panics | |
875 | /// | |
bd371182 | 876 | /// Panics if `index` is out of bounds. |
1a4d82fc JJ |
877 | /// |
878 | /// # Examples | |
879 | /// | |
880 | /// ``` | |
85aaf69f | 881 | /// let mut v = vec![1, 2, 3]; |
1a4d82fc | 882 | /// assert_eq!(v.remove(1), 2); |
c34b1796 | 883 | /// assert_eq!(v, [1, 3]); |
1a4d82fc | 884 | /// ``` |
85aaf69f SL |
885 | #[stable(feature = "rust1", since = "1.0.0")] |
886 | pub fn remove(&mut self, index: usize) -> T { | |
1a4d82fc JJ |
887 | let len = self.len(); |
888 | assert!(index < len); | |
92a42be0 SL |
889 | unsafe { |
890 | // infallible | |
1a4d82fc JJ |
891 | let ret; |
892 | { | |
893 | // the place we are taking from. | |
b7449926 | 894 | let ptr = self.as_mut_ptr().add(index); |
1a4d82fc JJ |
895 | // copy it out, unsafely having a copy of the value on |
896 | // the stack and in the vector at the same time. | |
85aaf69f | 897 | ret = ptr::read(ptr); |
1a4d82fc JJ |
898 | |
899 | // Shift everything down to fill in that spot. | |
c1a9b12d | 900 | ptr::copy(ptr.offset(1), ptr, len - index - 1); |
1a4d82fc JJ |
901 | } |
902 | self.set_len(len - 1); | |
903 | ret | |
904 | } | |
905 | } | |
906 | ||
907 | /// Retains only the elements specified by the predicate. | |
908 | /// | |
c30ab7b3 | 909 | /// In other words, remove all elements `e` such that `f(&e)` returns `false`. |
1a4d82fc JJ |
910 | /// This method operates in place and preserves the order of the retained |
911 | /// elements. | |
912 | /// | |
913 | /// # Examples | |
914 | /// | |
915 | /// ``` | |
85aaf69f | 916 | /// let mut vec = vec![1, 2, 3, 4]; |
1a4d82fc | 917 | /// vec.retain(|&x| x%2 == 0); |
c34b1796 | 918 | /// assert_eq!(vec, [2, 4]); |
1a4d82fc | 919 | /// ``` |
85aaf69f | 920 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
921 | pub fn retain<F>(&mut self, mut f: F) |
922 | where F: FnMut(&T) -> bool | |
923 | { | |
0531ce1d | 924 | self.drain_filter(|x| !f(x)); |
1a4d82fc JJ |
925 | } |
926 | ||
041b39d2 XL |
927 | /// Removes all but the first of consecutive elements in the vector that resolve to the same |
928 | /// key. | |
c30ab7b3 SL |
929 | /// |
930 | /// If the vector is sorted, this removes all duplicates. | |
931 | /// | |
932 | /// # Examples | |
933 | /// | |
934 | /// ``` | |
c30ab7b3 SL |
935 | /// let mut vec = vec![10, 20, 21, 30, 20]; |
936 | /// | |
937 | /// vec.dedup_by_key(|i| *i / 10); | |
938 | /// | |
939 | /// assert_eq!(vec, [10, 20, 30, 20]); | |
940 | /// ``` | |
32a655c1 | 941 | #[stable(feature = "dedup_by", since = "1.16.0")] |
c30ab7b3 SL |
942 | #[inline] |
943 | pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq { | |
944 | self.dedup_by(|a, b| key(a) == key(b)) | |
945 | } | |
946 | ||
041b39d2 XL |
947 | /// Removes all but the first of consecutive elements in the vector satisfying a given equality |
948 | /// relation. | |
cc61c64b XL |
949 | /// |
950 | /// The `same_bucket` function is passed references to two elements from the vector, and | |
041b39d2 XL |
951 | /// returns `true` if the elements compare equal, or `false` if they do not. The elements are |
952 | /// passed in opposite order from their order in the vector, so if `same_bucket(a, b)` returns | |
953 | /// `true`, `a` is removed. | |
c30ab7b3 SL |
954 | /// |
955 | /// If the vector is sorted, this removes all duplicates. | |
956 | /// | |
957 | /// # Examples | |
958 | /// | |
959 | /// ``` | |
c30ab7b3 SL |
960 | /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; |
961 | /// | |
962 | /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); | |
963 | /// | |
964 | /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); | |
965 | /// ``` | |
32a655c1 | 966 | #[stable(feature = "dedup_by", since = "1.16.0")] |
c30ab7b3 SL |
967 | pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool { |
968 | unsafe { | |
969 | // Although we have a mutable reference to `self`, we cannot make | |
970 | // *arbitrary* changes. The `same_bucket` calls could panic, so we | |
971 | // must ensure that the vector is in a valid state at all time. | |
972 | // | |
973 | // The way that we handle this is by using swaps; we iterate | |
974 | // over all the elements, swapping as we go so that at the end | |
975 | // the elements we wish to keep are in the front, and those we | |
976 | // wish to reject are at the back. We can then truncate the | |
977 | // vector. This operation is still O(n). | |
978 | // | |
979 | // Example: We start in this state, where `r` represents "next | |
980 | // read" and `w` represents "next_write`. | |
981 | // | |
982 | // r | |
983 | // +---+---+---+---+---+---+ | |
984 | // | 0 | 1 | 1 | 2 | 3 | 3 | | |
985 | // +---+---+---+---+---+---+ | |
986 | // w | |
987 | // | |
988 | // Comparing self[r] against self[w-1], this is not a duplicate, so | |
989 | // we swap self[r] and self[w] (no effect as r==w) and then increment both | |
990 | // r and w, leaving us with: | |
991 | // | |
992 | // r | |
993 | // +---+---+---+---+---+---+ | |
994 | // | 0 | 1 | 1 | 2 | 3 | 3 | | |
995 | // +---+---+---+---+---+---+ | |
996 | // w | |
997 | // | |
998 | // Comparing self[r] against self[w-1], this value is a duplicate, | |
999 | // so we increment `r` but leave everything else unchanged: | |
1000 | // | |
1001 | // r | |
1002 | // +---+---+---+---+---+---+ | |
1003 | // | 0 | 1 | 1 | 2 | 3 | 3 | | |
1004 | // +---+---+---+---+---+---+ | |
1005 | // w | |
1006 | // | |
1007 | // Comparing self[r] against self[w-1], this is not a duplicate, | |
1008 | // so swap self[r] and self[w] and advance r and w: | |
1009 | // | |
1010 | // r | |
1011 | // +---+---+---+---+---+---+ | |
1012 | // | 0 | 1 | 2 | 1 | 3 | 3 | | |
1013 | // +---+---+---+---+---+---+ | |
1014 | // w | |
1015 | // | |
1016 | // Not a duplicate, repeat: | |
1017 | // | |
1018 | // r | |
1019 | // +---+---+---+---+---+---+ | |
1020 | // | 0 | 1 | 2 | 3 | 1 | 3 | | |
1021 | // +---+---+---+---+---+---+ | |
1022 | // w | |
1023 | // | |
1024 | // Duplicate, advance r. End of vec. Truncate to w. | |
1025 | ||
1026 | let ln = self.len(); | |
1027 | if ln <= 1 { | |
1028 | return; | |
1029 | } | |
1030 | ||
1031 | // Avoid bounds checks by using raw pointers. | |
1032 | let p = self.as_mut_ptr(); | |
1033 | let mut r: usize = 1; | |
1034 | let mut w: usize = 1; | |
1035 | ||
1036 | while r < ln { | |
b7449926 XL |
1037 | let p_r = p.add(r); |
1038 | let p_wm1 = p.add(w - 1); | |
c30ab7b3 SL |
1039 | if !same_bucket(&mut *p_r, &mut *p_wm1) { |
1040 | if r != w { | |
1041 | let p_w = p_wm1.offset(1); | |
1042 | mem::swap(&mut *p_r, &mut *p_w); | |
1043 | } | |
1044 | w += 1; | |
1045 | } | |
1046 | r += 1; | |
1047 | } | |
1048 | ||
1049 | self.truncate(w); | |
1050 | } | |
1051 | } | |
1052 | ||
1a4d82fc JJ |
1053 | /// Appends an element to the back of a collection. |
1054 | /// | |
1055 | /// # Panics | |
1056 | /// | |
85aaf69f | 1057 | /// Panics if the number of elements in the vector overflows a `usize`. |
1a4d82fc JJ |
1058 | /// |
1059 | /// # Examples | |
1060 | /// | |
c34b1796 | 1061 | /// ``` |
c1a9b12d | 1062 | /// let mut vec = vec![1, 2]; |
1a4d82fc | 1063 | /// vec.push(3); |
c34b1796 | 1064 | /// assert_eq!(vec, [1, 2, 3]); |
1a4d82fc JJ |
1065 | /// ``` |
1066 | #[inline] | |
85aaf69f | 1067 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1068 | pub fn push(&mut self, value: T) { |
c1a9b12d SL |
1069 | // This will panic or abort if we would allocate > isize::MAX bytes |
1070 | // or if the length increment would overflow for zero-sized types. | |
92a42be0 | 1071 | if self.len == self.buf.cap() { |
94b46f34 | 1072 | self.reserve(1); |
92a42be0 | 1073 | } |
1a4d82fc | 1074 | unsafe { |
b7449926 | 1075 | let end = self.as_mut_ptr().add(self.len); |
c1a9b12d | 1076 | ptr::write(end, value); |
1a4d82fc JJ |
1077 | self.len += 1; |
1078 | } | |
1079 | } | |
1080 | ||
c30ab7b3 | 1081 | /// Removes the last element from a vector and returns it, or [`None`] if it |
e9174d1e | 1082 | /// is empty. |
1a4d82fc | 1083 | /// |
c30ab7b3 SL |
1084 | /// [`None`]: ../../std/option/enum.Option.html#variant.None |
1085 | /// | |
1a4d82fc JJ |
1086 | /// # Examples |
1087 | /// | |
c34b1796 | 1088 | /// ``` |
85aaf69f | 1089 | /// let mut vec = vec![1, 2, 3]; |
1a4d82fc | 1090 | /// assert_eq!(vec.pop(), Some(3)); |
c34b1796 | 1091 | /// assert_eq!(vec, [1, 2]); |
1a4d82fc JJ |
1092 | /// ``` |
1093 | #[inline] | |
85aaf69f | 1094 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1095 | pub fn pop(&mut self) -> Option<T> { |
1096 | if self.len == 0 { | |
1097 | None | |
1098 | } else { | |
1099 | unsafe { | |
1100 | self.len -= 1; | |
1101 | Some(ptr::read(self.get_unchecked(self.len()))) | |
1102 | } | |
1103 | } | |
1104 | } | |
1105 | ||
85aaf69f SL |
1106 | /// Moves all the elements of `other` into `Self`, leaving `other` empty. |
1107 | /// | |
1108 | /// # Panics | |
1109 | /// | |
1110 | /// Panics if the number of elements in the vector overflows a `usize`. | |
1111 | /// | |
1112 | /// # Examples | |
1113 | /// | |
1114 | /// ``` | |
1115 | /// let mut vec = vec![1, 2, 3]; | |
1116 | /// let mut vec2 = vec![4, 5, 6]; | |
1117 | /// vec.append(&mut vec2); | |
c34b1796 AL |
1118 | /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); |
1119 | /// assert_eq!(vec2, []); | |
85aaf69f SL |
1120 | /// ``` |
1121 | #[inline] | |
e9174d1e | 1122 | #[stable(feature = "append", since = "1.4.0")] |
85aaf69f | 1123 | pub fn append(&mut self, other: &mut Self) { |
92a42be0 | 1124 | unsafe { |
cc61c64b | 1125 | self.append_elements(other.as_slice() as _); |
92a42be0 SL |
1126 | other.set_len(0); |
1127 | } | |
85aaf69f SL |
1128 | } |
1129 | ||
cc61c64b XL |
1130 | /// Appends elements to `Self` from other buffer. |
1131 | #[inline] | |
1132 | unsafe fn append_elements(&mut self, other: *const [T]) { | |
1133 | let count = (*other).len(); | |
1134 | self.reserve(count); | |
1135 | let len = self.len(); | |
1136 | ptr::copy_nonoverlapping(other as *const T, self.get_unchecked_mut(len), count); | |
1137 | self.len += count; | |
1138 | } | |
1139 | ||
7cac9316 | 1140 | /// Creates a draining iterator that removes the specified range in the vector |
9cc50fc6 | 1141 | /// and yields the removed items. |
d9579d0f | 1142 | /// |
32a655c1 SL |
1143 | /// Note 1: The element range is removed even if the iterator is only |
1144 | /// partially consumed or not consumed at all. | |
9cc50fc6 | 1145 | /// |
7cac9316 | 1146 | /// Note 2: It is unspecified how many elements are removed from the vector |
d9579d0f AL |
1147 | /// if the `Drain` value is leaked. |
1148 | /// | |
1149 | /// # Panics | |
1150 | /// | |
1151 | /// Panics if the starting point is greater than the end point or if | |
1152 | /// the end point is greater than the length of the vector. | |
1a4d82fc JJ |
1153 | /// |
1154 | /// # Examples | |
1155 | /// | |
1156 | /// ``` | |
d9579d0f | 1157 | /// let mut v = vec![1, 2, 3]; |
9cc50fc6 SL |
1158 | /// let u: Vec<_> = v.drain(1..).collect(); |
1159 | /// assert_eq!(v, &[1]); | |
1160 | /// assert_eq!(u, &[2, 3]); | |
1161 | /// | |
1162 | /// // A full range clears the vector | |
1163 | /// v.drain(..); | |
d9579d0f | 1164 | /// assert_eq!(v, &[]); |
1a4d82fc | 1165 | /// ``` |
92a42be0 SL |
1166 | #[stable(feature = "drain", since = "1.6.0")] |
1167 | pub fn drain<R>(&mut self, range: R) -> Drain<T> | |
0531ce1d | 1168 | where R: RangeBounds<usize> |
92a42be0 | 1169 | { |
d9579d0f AL |
1170 | // Memory safety |
1171 | // | |
1172 | // When the Drain is first created, it shortens the length of | |
ff7c6d11 | 1173 | // the source vector to make sure no uninitialized or moved-from elements |
d9579d0f AL |
1174 | // are accessible at all if the Drain's destructor never gets to run. |
1175 | // | |
1176 | // Drain will ptr::read out the values to remove. | |
1177 | // When finished, remaining tail of the vec is copied back to cover | |
1178 | // the hole, and the vector length is restored to the new length. | |
1179 | // | |
1180 | let len = self.len(); | |
94b46f34 | 1181 | let start = match range.start_bound() { |
32a655c1 SL |
1182 | Included(&n) => n, |
1183 | Excluded(&n) => n + 1, | |
1184 | Unbounded => 0, | |
1185 | }; | |
94b46f34 | 1186 | let end = match range.end_bound() { |
32a655c1 SL |
1187 | Included(&n) => n + 1, |
1188 | Excluded(&n) => n, | |
1189 | Unbounded => len, | |
1190 | }; | |
d9579d0f AL |
1191 | assert!(start <= end); |
1192 | assert!(end <= len); | |
1193 | ||
1a4d82fc | 1194 | unsafe { |
d9579d0f AL |
1195 | // set self.vec length's to start, to be safe in case Drain is leaked |
1196 | self.set_len(start); | |
1197 | // Use the borrow in the IterMut to indicate borrowing behavior of the | |
1198 | // whole Drain iterator (like &mut T). | |
b7449926 | 1199 | let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), |
92a42be0 | 1200 | end - start); |
1a4d82fc | 1201 | Drain { |
d9579d0f AL |
1202 | tail_start: end, |
1203 | tail_len: len - end, | |
5bcae85e | 1204 | iter: range_slice.iter(), |
2c00a5a8 | 1205 | vec: NonNull::from(self), |
1a4d82fc JJ |
1206 | } |
1207 | } | |
1208 | } | |
1209 | ||
1210 | /// Clears the vector, removing all values. | |
1211 | /// | |
8bb4bdeb XL |
1212 | /// Note that this method has no effect on the allocated capacity |
1213 | /// of the vector. | |
1214 | /// | |
1a4d82fc JJ |
1215 | /// # Examples |
1216 | /// | |
1217 | /// ``` | |
85aaf69f | 1218 | /// let mut v = vec![1, 2, 3]; |
1a4d82fc JJ |
1219 | /// |
1220 | /// v.clear(); | |
1221 | /// | |
1222 | /// assert!(v.is_empty()); | |
1223 | /// ``` | |
1224 | #[inline] | |
85aaf69f | 1225 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1226 | pub fn clear(&mut self) { |
1227 | self.truncate(0) | |
1228 | } | |
1229 | ||
7cac9316 XL |
1230 | /// Returns the number of elements in the vector, also referred to |
1231 | /// as its 'length'. | |
1a4d82fc JJ |
1232 | /// |
1233 | /// # Examples | |
1234 | /// | |
1235 | /// ``` | |
85aaf69f | 1236 | /// let a = vec![1, 2, 3]; |
1a4d82fc JJ |
1237 | /// assert_eq!(a.len(), 3); |
1238 | /// ``` | |
1239 | #[inline] | |
85aaf69f | 1240 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
1241 | pub fn len(&self) -> usize { |
1242 | self.len | |
1243 | } | |
1a4d82fc JJ |
1244 | |
1245 | /// Returns `true` if the vector contains no elements. | |
1246 | /// | |
1247 | /// # Examples | |
1248 | /// | |
1249 | /// ``` | |
1250 | /// let mut v = Vec::new(); | |
1251 | /// assert!(v.is_empty()); | |
1252 | /// | |
85aaf69f | 1253 | /// v.push(1); |
1a4d82fc JJ |
1254 | /// assert!(!v.is_empty()); |
1255 | /// ``` | |
85aaf69f | 1256 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
1257 | pub fn is_empty(&self) -> bool { |
1258 | self.len() == 0 | |
1259 | } | |
1a4d82fc | 1260 | |
85aaf69f SL |
1261 | /// Splits the collection into two at the given index. |
1262 | /// | |
1263 | /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`, | |
1264 | /// and the returned `Self` contains elements `[at, len)`. | |
1265 | /// | |
1266 | /// Note that the capacity of `self` does not change. | |
1267 | /// | |
1268 | /// # Panics | |
1269 | /// | |
1270 | /// Panics if `at > len`. | |
1271 | /// | |
1272 | /// # Examples | |
1273 | /// | |
1274 | /// ``` | |
1275 | /// let mut vec = vec![1,2,3]; | |
1276 | /// let vec2 = vec.split_off(1); | |
c34b1796 AL |
1277 | /// assert_eq!(vec, [1]); |
1278 | /// assert_eq!(vec2, [2, 3]); | |
85aaf69f SL |
1279 | /// ``` |
1280 | #[inline] | |
e9174d1e | 1281 | #[stable(feature = "split_off", since = "1.4.0")] |
85aaf69f SL |
1282 | pub fn split_off(&mut self, at: usize) -> Self { |
1283 | assert!(at <= self.len(), "`at` out of bounds"); | |
1284 | ||
1285 | let other_len = self.len - at; | |
1286 | let mut other = Vec::with_capacity(other_len); | |
1287 | ||
1288 | // Unsafely `set_len` and copy items to `other`. | |
1289 | unsafe { | |
1290 | self.set_len(at); | |
1291 | other.set_len(other_len); | |
1292 | ||
b7449926 | 1293 | ptr::copy_nonoverlapping(self.as_ptr().add(at), |
92a42be0 SL |
1294 | other.as_mut_ptr(), |
1295 | other.len()); | |
85aaf69f SL |
1296 | } |
1297 | other | |
1298 | } | |
83c7162d XL |
1299 | |
1300 | /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. | |
1301 | /// | |
1302 | /// If `new_len` is greater than `len`, the `Vec` is extended by the | |
1303 | /// difference, with each additional slot filled with the result of | |
1304 | /// calling the closure `f`. The return values from `f` will end up | |
1305 | /// in the `Vec` in the order they have been generated. | |
1306 | /// | |
1307 | /// If `new_len` is less than `len`, the `Vec` is simply truncated. | |
1308 | /// | |
1309 | /// This method uses a closure to create new values on every push. If | |
1310 | /// you'd rather [`Clone`] a given value, use [`resize`]. If you want | |
1311 | /// to use the [`Default`] trait to generate values, you can pass | |
1312 | /// [`Default::default()`] as the second argument.. | |
1313 | /// | |
1314 | /// # Examples | |
1315 | /// | |
1316 | /// ``` | |
1317 | /// #![feature(vec_resize_with)] | |
1318 | /// | |
1319 | /// let mut vec = vec![1, 2, 3]; | |
1320 | /// vec.resize_with(5, Default::default); | |
1321 | /// assert_eq!(vec, [1, 2, 3, 0, 0]); | |
1322 | /// | |
1323 | /// let mut vec = vec![]; | |
1324 | /// let mut p = 1; | |
1325 | /// vec.resize_with(4, || { p *= 2; p }); | |
1326 | /// assert_eq!(vec, [2, 4, 8, 16]); | |
1327 | /// ``` | |
1328 | /// | |
1329 | /// [`resize`]: #method.resize | |
1330 | /// [`Clone`]: ../../std/clone/trait.Clone.html | |
1331 | #[unstable(feature = "vec_resize_with", issue = "41758")] | |
1332 | pub fn resize_with<F>(&mut self, new_len: usize, f: F) | |
1333 | where F: FnMut() -> T | |
1334 | { | |
1335 | let len = self.len(); | |
1336 | if new_len > len { | |
1337 | self.extend_with(new_len - len, ExtendFunc(f)); | |
1338 | } else { | |
1339 | self.truncate(new_len); | |
1340 | } | |
1341 | } | |
1a4d82fc JJ |
1342 | } |
1343 | ||
1344 | impl<T: Clone> Vec<T> { | |
7cac9316 | 1345 | /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. |
1a4d82fc | 1346 | /// |
7cac9316 | 1347 | /// If `new_len` is greater than `len`, the `Vec` is extended by the |
92a42be0 | 1348 | /// difference, with each additional slot filled with `value`. |
7cac9316 XL |
1349 | /// If `new_len` is less than `len`, the `Vec` is simply truncated. |
1350 | /// | |
0531ce1d | 1351 | /// This method requires [`Clone`] to be able clone the passed value. If |
83c7162d XL |
1352 | /// you need more flexibility (or want to rely on [`Default`] instead of |
1353 | /// [`Clone`]), use [`resize_with`]. | |
1a4d82fc JJ |
1354 | /// |
1355 | /// # Examples | |
1356 | /// | |
1357 | /// ``` | |
1358 | /// let mut vec = vec!["hello"]; | |
1359 | /// vec.resize(3, "world"); | |
c34b1796 | 1360 | /// assert_eq!(vec, ["hello", "world", "world"]); |
1a4d82fc | 1361 | /// |
85aaf69f | 1362 | /// let mut vec = vec![1, 2, 3, 4]; |
1a4d82fc | 1363 | /// vec.resize(2, 0); |
c34b1796 | 1364 | /// assert_eq!(vec, [1, 2]); |
1a4d82fc | 1365 | /// ``` |
7cac9316 | 1366 | /// |
0531ce1d XL |
1367 | /// [`Clone`]: ../../std/clone/trait.Clone.html |
1368 | /// [`Default`]: ../../std/default/trait.Default.html | |
83c7162d | 1369 | /// [`resize_with`]: #method.resize_with |
b039eaaf | 1370 | #[stable(feature = "vec_resize", since = "1.5.0")] |
85aaf69f | 1371 | pub fn resize(&mut self, new_len: usize, value: T) { |
1a4d82fc JJ |
1372 | let len = self.len(); |
1373 | ||
1374 | if new_len > len { | |
7cac9316 | 1375 | self.extend_with(new_len - len, ExtendElement(value)) |
1a4d82fc JJ |
1376 | } else { |
1377 | self.truncate(new_len); | |
1378 | } | |
1379 | } | |
1380 | ||
7cac9316 XL |
1381 | /// Clones and appends all elements in a slice to the `Vec`. |
1382 | /// | |
1383 | /// Iterates over the slice `other`, clones each element, and then appends | |
1384 | /// it to this `Vec`. The `other` vector is traversed in-order. | |
1385 | /// | |
0531ce1d | 1386 | /// Note that this function is same as [`extend`] except that it is |
7cac9316 XL |
1387 | /// specialized to work with slices instead. If and when Rust gets |
1388 | /// specialization this function will likely be deprecated (but still | |
1389 | /// available). | |
1390 | /// | |
1391 | /// # Examples | |
1392 | /// | |
1393 | /// ``` | |
1394 | /// let mut vec = vec![1]; | |
1395 | /// vec.extend_from_slice(&[2, 3, 4]); | |
1396 | /// assert_eq!(vec, [1, 2, 3, 4]); | |
1397 | /// ``` | |
0531ce1d XL |
1398 | /// |
1399 | /// [`extend`]: #method.extend | |
7cac9316 XL |
1400 | #[stable(feature = "vec_extend_from_slice", since = "1.6.0")] |
1401 | pub fn extend_from_slice(&mut self, other: &[T]) { | |
1402 | self.spec_extend(other.iter()) | |
1403 | } | |
1404 | } | |
1405 | ||
1406 | impl<T: Default> Vec<T> { | |
1407 | /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. | |
1408 | /// | |
1409 | /// If `new_len` is greater than `len`, the `Vec` is extended by the | |
0531ce1d | 1410 | /// difference, with each additional slot filled with [`Default::default()`]. |
7cac9316 XL |
1411 | /// If `new_len` is less than `len`, the `Vec` is simply truncated. |
1412 | /// | |
0531ce1d XL |
1413 | /// This method uses [`Default`] to create new values on every push. If |
1414 | /// you'd rather [`Clone`] a given value, use [`resize`]. | |
7cac9316 XL |
1415 | /// |
1416 | /// # Examples | |
1417 | /// | |
1418 | /// ``` | |
1419 | /// #![feature(vec_resize_default)] | |
1420 | /// | |
1421 | /// let mut vec = vec![1, 2, 3]; | |
1422 | /// vec.resize_default(5); | |
1423 | /// assert_eq!(vec, [1, 2, 3, 0, 0]); | |
1424 | /// | |
1425 | /// let mut vec = vec![1, 2, 3, 4]; | |
1426 | /// vec.resize_default(2); | |
1427 | /// assert_eq!(vec, [1, 2]); | |
1428 | /// ``` | |
1429 | /// | |
1430 | /// [`resize`]: #method.resize | |
0531ce1d XL |
1431 | /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default |
1432 | /// [`Default`]: ../../std/default/trait.Default.html | |
1433 | /// [`Clone`]: ../../std/clone/trait.Clone.html | |
7cac9316 XL |
1434 | #[unstable(feature = "vec_resize_default", issue = "41758")] |
1435 | pub fn resize_default(&mut self, new_len: usize) { | |
1436 | let len = self.len(); | |
1437 | ||
1438 | if new_len > len { | |
1439 | self.extend_with(new_len - len, ExtendDefault); | |
1440 | } else { | |
1441 | self.truncate(new_len); | |
1442 | } | |
1443 | } | |
1444 | } | |
1445 | ||
1446 | // This code generalises `extend_with_{element,default}`. | |
1447 | trait ExtendWith<T> { | |
83c7162d | 1448 | fn next(&mut self) -> T; |
7cac9316 XL |
1449 | fn last(self) -> T; |
1450 | } | |
1451 | ||
1452 | struct ExtendElement<T>(T); | |
1453 | impl<T: Clone> ExtendWith<T> for ExtendElement<T> { | |
83c7162d | 1454 | fn next(&mut self) -> T { self.0.clone() } |
7cac9316 XL |
1455 | fn last(self) -> T { self.0 } |
1456 | } | |
1457 | ||
1458 | struct ExtendDefault; | |
1459 | impl<T: Default> ExtendWith<T> for ExtendDefault { | |
83c7162d | 1460 | fn next(&mut self) -> T { Default::default() } |
7cac9316 XL |
1461 | fn last(self) -> T { Default::default() } |
1462 | } | |
83c7162d XL |
1463 | |
1464 | struct ExtendFunc<F>(F); | |
1465 | impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> { | |
1466 | fn next(&mut self) -> T { (self.0)() } | |
1467 | fn last(mut self) -> T { (self.0)() } | |
1468 | } | |
1469 | ||
7cac9316 XL |
1470 | impl<T> Vec<T> { |
1471 | /// Extend the vector by `n` values, using the given generator. | |
83c7162d | 1472 | fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) { |
c1a9b12d SL |
1473 | self.reserve(n); |
1474 | ||
1475 | unsafe { | |
b7449926 | 1476 | let mut ptr = self.as_mut_ptr().add(self.len()); |
9e0c209e | 1477 | // Use SetLenOnDrop to work around bug where compiler |
8bb4bdeb | 1478 | // may not realize the store through `ptr` through self.set_len() |
9e0c209e SL |
1479 | // don't alias. |
1480 | let mut local_len = SetLenOnDrop::new(&mut self.len); | |
1481 | ||
c1a9b12d | 1482 | // Write all elements except the last one |
9e0c209e | 1483 | for _ in 1..n { |
7cac9316 | 1484 | ptr::write(ptr, value.next()); |
c1a9b12d | 1485 | ptr = ptr.offset(1); |
7cac9316 | 1486 | // Increment the length in every step in case next() panics |
9e0c209e | 1487 | local_len.increment_len(1); |
c1a9b12d SL |
1488 | } |
1489 | ||
1490 | if n > 0 { | |
1491 | // We can write the last element directly without cloning needlessly | |
7cac9316 | 1492 | ptr::write(ptr, value.last()); |
9e0c209e | 1493 | local_len.increment_len(1); |
c1a9b12d | 1494 | } |
9e0c209e SL |
1495 | |
1496 | // len set by scope guard | |
c1a9b12d SL |
1497 | } |
1498 | } | |
1a4d82fc JJ |
1499 | } |
1500 | ||
9e0c209e SL |
1501 | // Set the length of the vec when the `SetLenOnDrop` value goes out of scope. |
1502 | // | |
1503 | // The idea is: The length field in SetLenOnDrop is a local variable | |
1504 | // that the optimizer will see does not alias with any stores through the Vec's data | |
1505 | // pointer. This is a workaround for alias analysis issue #32155 | |
1506 | struct SetLenOnDrop<'a> { | |
1507 | len: &'a mut usize, | |
1508 | local_len: usize, | |
1509 | } | |
1510 | ||
1511 | impl<'a> SetLenOnDrop<'a> { | |
1512 | #[inline] | |
1513 | fn new(len: &'a mut usize) -> Self { | |
1514 | SetLenOnDrop { local_len: *len, len: len } | |
1515 | } | |
1516 | ||
1517 | #[inline] | |
1518 | fn increment_len(&mut self, increment: usize) { | |
1519 | self.local_len += increment; | |
1520 | } | |
b7449926 XL |
1521 | |
1522 | #[inline] | |
1523 | fn decrement_len(&mut self, decrement: usize) { | |
1524 | self.local_len -= decrement; | |
1525 | } | |
9e0c209e SL |
1526 | } |
1527 | ||
1528 | impl<'a> Drop for SetLenOnDrop<'a> { | |
1529 | #[inline] | |
1530 | fn drop(&mut self) { | |
1531 | *self.len = self.local_len; | |
1532 | } | |
1533 | } | |
1534 | ||
1a4d82fc JJ |
1535 | impl<T: PartialEq> Vec<T> { |
1536 | /// Removes consecutive repeated elements in the vector. | |
1537 | /// | |
1538 | /// If the vector is sorted, this removes all duplicates. | |
1539 | /// | |
1540 | /// # Examples | |
1541 | /// | |
1542 | /// ``` | |
85aaf69f | 1543 | /// let mut vec = vec![1, 2, 2, 3, 2]; |
1a4d82fc JJ |
1544 | /// |
1545 | /// vec.dedup(); | |
1546 | /// | |
c34b1796 | 1547 | /// assert_eq!(vec, [1, 2, 3, 2]); |
1a4d82fc | 1548 | /// ``` |
85aaf69f | 1549 | #[stable(feature = "rust1", since = "1.0.0")] |
c30ab7b3 | 1550 | #[inline] |
1a4d82fc | 1551 | pub fn dedup(&mut self) { |
c30ab7b3 | 1552 | self.dedup_by(|a, b| a == b) |
1a4d82fc | 1553 | } |
8bb4bdeb XL |
1554 | |
1555 | /// Removes the first instance of `item` from the vector if the item exists. | |
1556 | /// | |
1557 | /// # Examples | |
1558 | /// | |
1559 | /// ``` | |
cc61c64b | 1560 | /// # #![feature(vec_remove_item)] |
8bb4bdeb XL |
1561 | /// let mut vec = vec![1, 2, 3, 1]; |
1562 | /// | |
1563 | /// vec.remove_item(&1); | |
1564 | /// | |
1565 | /// assert_eq!(vec, vec![2, 3, 1]); | |
1566 | /// ``` | |
1567 | #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")] | |
1568 | pub fn remove_item(&mut self, item: &T) -> Option<T> { | |
ff7c6d11 | 1569 | let pos = self.iter().position(|x| *x == *item)?; |
8bb4bdeb XL |
1570 | Some(self.remove(pos)) |
1571 | } | |
1a4d82fc JJ |
1572 | } |
1573 | ||
1574 | //////////////////////////////////////////////////////////////////////////////// | |
1575 | // Internal methods and functions | |
1576 | //////////////////////////////////////////////////////////////////////////////// | |
1577 | ||
85aaf69f SL |
1578 | #[doc(hidden)] |
1579 | #[stable(feature = "rust1", since = "1.0.0")] | |
1580 | pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> { | |
cc61c64b XL |
1581 | <T as SpecFromElem>::from_elem(elem, n) |
1582 | } | |
1583 | ||
1584 | // Specialization trait used for Vec::from_elem | |
1585 | trait SpecFromElem: Sized { | |
1586 | fn from_elem(elem: Self, n: usize) -> Vec<Self>; | |
1587 | } | |
1588 | ||
1589 | impl<T: Clone> SpecFromElem for T { | |
1590 | default fn from_elem(elem: Self, n: usize) -> Vec<Self> { | |
1591 | let mut v = Vec::with_capacity(n); | |
7cac9316 | 1592 | v.extend_with(n, ExtendElement(elem)); |
cc61c64b XL |
1593 | v |
1594 | } | |
85aaf69f SL |
1595 | } |
1596 | ||
cc61c64b XL |
1597 | impl SpecFromElem for u8 { |
1598 | #[inline] | |
1599 | fn from_elem(elem: u8, n: usize) -> Vec<u8> { | |
1600 | if elem == 0 { | |
1601 | return Vec { | |
1602 | buf: RawVec::with_capacity_zeroed(n), | |
1603 | len: n, | |
1604 | } | |
1605 | } | |
1606 | unsafe { | |
1607 | let mut v = Vec::with_capacity(n); | |
1608 | ptr::write_bytes(v.as_mut_ptr(), elem, n); | |
1609 | v.set_len(n); | |
1610 | v | |
1611 | } | |
1612 | } | |
1613 | } | |
1614 | ||
83c7162d XL |
1615 | impl<T: Clone + IsZero> SpecFromElem for T { |
1616 | #[inline] | |
1617 | fn from_elem(elem: T, n: usize) -> Vec<T> { | |
1618 | if elem.is_zero() { | |
1619 | return Vec { | |
1620 | buf: RawVec::with_capacity_zeroed(n), | |
1621 | len: n, | |
1622 | } | |
1623 | } | |
1624 | let mut v = Vec::with_capacity(n); | |
1625 | v.extend_with(n, ExtendElement(elem)); | |
1626 | v | |
1627 | } | |
1628 | } | |
1629 | ||
1630 | unsafe trait IsZero { | |
1631 | /// Whether this value is zero | |
1632 | fn is_zero(&self) -> bool; | |
1633 | } | |
1634 | ||
1635 | macro_rules! impl_is_zero { | |
cc61c64b | 1636 | ($t: ty, $is_zero: expr) => { |
83c7162d | 1637 | unsafe impl IsZero for $t { |
cc61c64b | 1638 | #[inline] |
83c7162d XL |
1639 | fn is_zero(&self) -> bool { |
1640 | $is_zero(*self) | |
cc61c64b XL |
1641 | } |
1642 | } | |
83c7162d | 1643 | } |
cc61c64b XL |
1644 | } |
1645 | ||
83c7162d XL |
1646 | impl_is_zero!(i8, |x| x == 0); |
1647 | impl_is_zero!(i16, |x| x == 0); | |
1648 | impl_is_zero!(i32, |x| x == 0); | |
1649 | impl_is_zero!(i64, |x| x == 0); | |
1650 | impl_is_zero!(i128, |x| x == 0); | |
1651 | impl_is_zero!(isize, |x| x == 0); | |
1652 | ||
1653 | impl_is_zero!(u16, |x| x == 0); | |
1654 | impl_is_zero!(u32, |x| x == 0); | |
1655 | impl_is_zero!(u64, |x| x == 0); | |
1656 | impl_is_zero!(u128, |x| x == 0); | |
1657 | impl_is_zero!(usize, |x| x == 0); | |
cc61c64b | 1658 | |
83c7162d XL |
1659 | impl_is_zero!(char, |x| x == '\0'); |
1660 | ||
1661 | impl_is_zero!(f32, |x: f32| x.to_bits() == 0); | |
1662 | impl_is_zero!(f64, |x: f64| x.to_bits() == 0); | |
1663 | ||
1664 | unsafe impl<T: ?Sized> IsZero for *const T { | |
1665 | #[inline] | |
1666 | fn is_zero(&self) -> bool { | |
1667 | (*self).is_null() | |
1668 | } | |
1669 | } | |
1670 | ||
1671 | unsafe impl<T: ?Sized> IsZero for *mut T { | |
1672 | #[inline] | |
1673 | fn is_zero(&self) -> bool { | |
1674 | (*self).is_null() | |
1675 | } | |
1676 | } | |
cc61c64b | 1677 | |
cc61c64b | 1678 | |
1a4d82fc JJ |
1679 | //////////////////////////////////////////////////////////////////////////////// |
1680 | // Common trait implementations for Vec | |
1681 | //////////////////////////////////////////////////////////////////////////////// | |
1682 | ||
bd371182 | 1683 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 1684 | impl<T: Clone> Clone for Vec<T> { |
c34b1796 | 1685 | #[cfg(not(test))] |
92a42be0 SL |
1686 | fn clone(&self) -> Vec<T> { |
1687 | <[T]>::to_vec(&**self) | |
1688 | } | |
c34b1796 AL |
1689 | |
1690 | // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is | |
1691 | // required for this method definition, is not available. Instead use the | |
1692 | // `slice::to_vec` function which is only available with cfg(test) | |
1693 | // NB see the slice::hack module in slice.rs for more information | |
1694 | #[cfg(test)] | |
1695 | fn clone(&self) -> Vec<T> { | |
1696 | ::slice::to_vec(&**self) | |
1697 | } | |
1a4d82fc JJ |
1698 | |
1699 | fn clone_from(&mut self, other: &Vec<T>) { | |
cc61c64b | 1700 | other.as_slice().clone_into(self); |
1a4d82fc JJ |
1701 | } |
1702 | } | |
1703 | ||
85aaf69f | 1704 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 1705 | impl<T: Hash> Hash for Vec<T> { |
1a4d82fc | 1706 | #[inline] |
85aaf69f SL |
1707 | fn hash<H: hash::Hasher>(&self, state: &mut H) { |
1708 | Hash::hash(&**self, state) | |
1a4d82fc JJ |
1709 | } |
1710 | } | |
1711 | ||
85aaf69f | 1712 | #[stable(feature = "rust1", since = "1.0.0")] |
8faf50e0 XL |
1713 | #[rustc_on_unimplemented( |
1714 | message="vector indices are of type `usize` or ranges of `usize`", | |
1715 | label="vector indices are of type `usize` or ranges of `usize`", | |
1716 | )] | |
0531ce1d XL |
1717 | impl<T, I> Index<I> for Vec<T> |
1718 | where | |
1719 | I: ::core::slice::SliceIndex<[T]>, | |
1720 | { | |
1721 | type Output = I::Output; | |
54a0048b SL |
1722 | |
1723 | #[inline] | |
0531ce1d | 1724 | fn index(&self, index: I) -> &Self::Output { |
54a0048b SL |
1725 | Index::index(&**self, index) |
1726 | } | |
1727 | } | |
1a4d82fc | 1728 | |
85aaf69f | 1729 | #[stable(feature = "rust1", since = "1.0.0")] |
8faf50e0 XL |
1730 | #[rustc_on_unimplemented( |
1731 | message="vector indices are of type `usize` or ranges of `usize`", | |
1732 | label="vector indices are of type `usize` or ranges of `usize`", | |
1733 | )] | |
0531ce1d XL |
1734 | impl<T, I> IndexMut<I> for Vec<T> |
1735 | where | |
1736 | I: ::core::slice::SliceIndex<[T]>, | |
1737 | { | |
54a0048b | 1738 | #[inline] |
0531ce1d | 1739 | fn index_mut(&mut self, index: I) -> &mut Self::Output { |
54a0048b SL |
1740 | IndexMut::index_mut(&mut **self, index) |
1741 | } | |
1742 | } | |
1a4d82fc | 1743 | |
85aaf69f | 1744 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1745 | impl<T> ops::Deref for Vec<T> { |
1746 | type Target = [T]; | |
1747 | ||
c34b1796 AL |
1748 | fn deref(&self) -> &[T] { |
1749 | unsafe { | |
c1a9b12d | 1750 | let p = self.buf.ptr(); |
e9174d1e | 1751 | assume(!p.is_null()); |
c34b1796 AL |
1752 | slice::from_raw_parts(p, self.len) |
1753 | } | |
1754 | } | |
1a4d82fc JJ |
1755 | } |
1756 | ||
85aaf69f | 1757 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1758 | impl<T> ops::DerefMut for Vec<T> { |
c34b1796 AL |
1759 | fn deref_mut(&mut self) -> &mut [T] { |
1760 | unsafe { | |
c1a9b12d | 1761 | let ptr = self.buf.ptr(); |
c34b1796 AL |
1762 | assume(!ptr.is_null()); |
1763 | slice::from_raw_parts_mut(ptr, self.len) | |
1764 | } | |
1765 | } | |
1a4d82fc JJ |
1766 | } |
1767 | ||
85aaf69f | 1768 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1769 | impl<T> FromIterator<T> for Vec<T> { |
1770 | #[inline] | |
54a0048b | 1771 | fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> { |
cc61c64b | 1772 | <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter()) |
1a4d82fc JJ |
1773 | } |
1774 | } | |
1775 | ||
85aaf69f SL |
1776 | #[stable(feature = "rust1", since = "1.0.0")] |
1777 | impl<T> IntoIterator for Vec<T> { | |
1778 | type Item = T; | |
1779 | type IntoIter = IntoIter<T>; | |
1780 | ||
9346a6ac AL |
1781 | /// Creates a consuming iterator, that is, one that moves each value out of |
1782 | /// the vector (from start to end). The vector cannot be used after calling | |
1783 | /// this. | |
1784 | /// | |
1785 | /// # Examples | |
1786 | /// | |
1787 | /// ``` | |
1788 | /// let v = vec!["a".to_string(), "b".to_string()]; | |
1789 | /// for s in v.into_iter() { | |
1790 | /// // s has type String, not &String | |
1791 | /// println!("{}", s); | |
1792 | /// } | |
1793 | /// ``` | |
1794 | #[inline] | |
c1a9b12d | 1795 | fn into_iter(mut self) -> IntoIter<T> { |
9346a6ac | 1796 | unsafe { |
5bcae85e SL |
1797 | let begin = self.as_mut_ptr(); |
1798 | assume(!begin.is_null()); | |
9346a6ac | 1799 | let end = if mem::size_of::<T>() == 0 { |
5bcae85e | 1800 | arith_offset(begin as *const i8, self.len() as isize) as *const T |
9346a6ac | 1801 | } else { |
b7449926 | 1802 | begin.add(self.len()) as *const T |
9346a6ac | 1803 | }; |
5bcae85e | 1804 | let cap = self.buf.cap(); |
9346a6ac | 1805 | mem::forget(self); |
92a42be0 | 1806 | IntoIter { |
2c00a5a8 | 1807 | buf: NonNull::new_unchecked(begin), |
ff7c6d11 | 1808 | phantom: PhantomData, |
3b2f2976 | 1809 | cap, |
92a42be0 | 1810 | ptr: begin, |
3b2f2976 | 1811 | end, |
92a42be0 | 1812 | } |
9346a6ac | 1813 | } |
85aaf69f SL |
1814 | } |
1815 | } | |
1816 | ||
1817 | #[stable(feature = "rust1", since = "1.0.0")] | |
1818 | impl<'a, T> IntoIterator for &'a Vec<T> { | |
1819 | type Item = &'a T; | |
1820 | type IntoIter = slice::Iter<'a, T>; | |
1821 | ||
1822 | fn into_iter(self) -> slice::Iter<'a, T> { | |
1823 | self.iter() | |
1824 | } | |
1825 | } | |
1826 | ||
1827 | #[stable(feature = "rust1", since = "1.0.0")] | |
1828 | impl<'a, T> IntoIterator for &'a mut Vec<T> { | |
1829 | type Item = &'a mut T; | |
1830 | type IntoIter = slice::IterMut<'a, T>; | |
1831 | ||
3b2f2976 | 1832 | fn into_iter(self) -> slice::IterMut<'a, T> { |
85aaf69f SL |
1833 | self.iter_mut() |
1834 | } | |
1835 | } | |
1836 | ||
bd371182 | 1837 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1838 | impl<T> Extend<T> for Vec<T> { |
1839 | #[inline] | |
54a0048b | 1840 | fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { |
cc61c64b | 1841 | <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter()) |
62682a34 SL |
1842 | } |
1843 | } | |
1844 | ||
476ff2be SL |
1845 | // Specialization trait used for Vec::from_iter and Vec::extend |
1846 | trait SpecExtend<T, I> { | |
1847 | fn from_iter(iter: I) -> Self; | |
1848 | fn spec_extend(&mut self, iter: I); | |
c30ab7b3 | 1849 | } |
c30ab7b3 | 1850 | |
476ff2be SL |
1851 | impl<T, I> SpecExtend<T, I> for Vec<T> |
1852 | where I: Iterator<Item=T>, | |
c30ab7b3 | 1853 | { |
476ff2be SL |
1854 | default fn from_iter(mut iterator: I) -> Self { |
1855 | // Unroll the first iteration, as the vector is going to be | |
1856 | // expanded on this iteration in every case when the iterable is not | |
1857 | // empty, but the loop in extend_desugared() is not going to see the | |
1858 | // vector being full in the few subsequent loop iterations. | |
1859 | // So we get better branch prediction. | |
1860 | let mut vector = match iterator.next() { | |
1861 | None => return Vec::new(), | |
1862 | Some(element) => { | |
1863 | let (lower, _) = iterator.size_hint(); | |
1864 | let mut vector = Vec::with_capacity(lower.saturating_add(1)); | |
1865 | unsafe { | |
1866 | ptr::write(vector.get_unchecked_mut(0), element); | |
1867 | vector.set_len(1); | |
1868 | } | |
1869 | vector | |
1870 | } | |
1871 | }; | |
cc61c64b | 1872 | <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator); |
476ff2be SL |
1873 | vector |
1874 | } | |
1875 | ||
1876 | default fn spec_extend(&mut self, iter: I) { | |
1877 | self.extend_desugared(iter) | |
1878 | } | |
1879 | } | |
1880 | ||
1881 | impl<T, I> SpecExtend<T, I> for Vec<T> | |
1882 | where I: TrustedLen<Item=T>, | |
1883 | { | |
cc61c64b | 1884 | default fn from_iter(iterator: I) -> Self { |
476ff2be SL |
1885 | let mut vector = Vec::new(); |
1886 | vector.spec_extend(iterator); | |
1887 | vector | |
1888 | } | |
1889 | ||
cc61c64b | 1890 | default fn spec_extend(&mut self, iterator: I) { |
476ff2be SL |
1891 | // This is the case for a TrustedLen iterator. |
1892 | let (low, high) = iterator.size_hint(); | |
c30ab7b3 SL |
1893 | if let Some(high_value) = high { |
1894 | debug_assert_eq!(low, high_value, | |
1895 | "TrustedLen iterator's size hint is not exact: {:?}", | |
1896 | (low, high)); | |
1897 | } | |
476ff2be | 1898 | if let Some(additional) = high { |
c30ab7b3 | 1899 | self.reserve(additional); |
62682a34 | 1900 | unsafe { |
b7449926 | 1901 | let mut ptr = self.as_mut_ptr().add(self.len()); |
c30ab7b3 SL |
1902 | let mut local_len = SetLenOnDrop::new(&mut self.len); |
1903 | for element in iterator { | |
1904 | ptr::write(ptr, element); | |
1905 | ptr = ptr.offset(1); | |
1906 | // NB can't overflow since we would have had to alloc the address space | |
1907 | local_len.increment_len(1); | |
1908 | } | |
1909 | } | |
1910 | } else { | |
476ff2be SL |
1911 | self.extend_desugared(iterator) |
1912 | } | |
1913 | } | |
1914 | } | |
1915 | ||
cc61c64b XL |
1916 | impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> { |
1917 | fn from_iter(iterator: IntoIter<T>) -> Self { | |
1918 | // A common case is passing a vector into a function which immediately | |
1919 | // re-collects into a vector. We can short circuit this if the IntoIter | |
1920 | // has not been advanced at all. | |
7cac9316 | 1921 | if iterator.buf.as_ptr() as *const _ == iterator.ptr { |
cc61c64b | 1922 | unsafe { |
7cac9316 | 1923 | let vec = Vec::from_raw_parts(iterator.buf.as_ptr(), |
cc61c64b XL |
1924 | iterator.len(), |
1925 | iterator.cap); | |
1926 | mem::forget(iterator); | |
1927 | vec | |
1928 | } | |
1929 | } else { | |
1930 | let mut vector = Vec::new(); | |
1931 | vector.spec_extend(iterator); | |
1932 | vector | |
1933 | } | |
1934 | } | |
1935 | ||
1936 | fn spec_extend(&mut self, mut iterator: IntoIter<T>) { | |
1937 | unsafe { | |
1938 | self.append_elements(iterator.as_slice() as _); | |
1939 | } | |
1940 | iterator.ptr = iterator.end; | |
1941 | } | |
1942 | } | |
1943 | ||
476ff2be SL |
1944 | impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T> |
1945 | where I: Iterator<Item=&'a T>, | |
1946 | T: Clone, | |
1947 | { | |
1948 | default fn from_iter(iterator: I) -> Self { | |
1949 | SpecExtend::from_iter(iterator.cloned()) | |
1950 | } | |
1951 | ||
1952 | default fn spec_extend(&mut self, iterator: I) { | |
1953 | self.spec_extend(iterator.cloned()) | |
1954 | } | |
1955 | } | |
1956 | ||
1957 | impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T> | |
1958 | where T: Copy, | |
1959 | { | |
1960 | fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) { | |
1961 | let slice = iterator.as_slice(); | |
1962 | self.reserve(slice.len()); | |
1963 | unsafe { | |
1964 | let len = self.len(); | |
1965 | self.set_len(len + slice.len()); | |
1966 | self.get_unchecked_mut(len..).copy_from_slice(slice); | |
1967 | } | |
1968 | } | |
1969 | } | |
1970 | ||
1971 | impl<T> Vec<T> { | |
1972 | fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) { | |
1973 | // This is the case for a general iterator. | |
1974 | // | |
1975 | // This function should be the moral equivalent of: | |
1976 | // | |
1977 | // for item in iterator { | |
1978 | // self.push(item); | |
1979 | // } | |
1980 | while let Some(element) = iterator.next() { | |
1981 | let len = self.len(); | |
1982 | if len == self.capacity() { | |
1983 | let (lower, _) = iterator.size_hint(); | |
1984 | self.reserve(lower.saturating_add(1)); | |
1985 | } | |
1986 | unsafe { | |
1987 | ptr::write(self.get_unchecked_mut(len), element); | |
1988 | // NB can't overflow since we would have had to alloc the address space | |
1989 | self.set_len(len + 1); | |
62682a34 | 1990 | } |
1a4d82fc JJ |
1991 | } |
1992 | } | |
7cac9316 XL |
1993 | |
1994 | /// Creates a splicing iterator that replaces the specified range in the vector | |
1995 | /// with the given `replace_with` iterator and yields the removed items. | |
1996 | /// `replace_with` does not need to be the same length as `range`. | |
1997 | /// | |
1998 | /// Note 1: The element range is removed even if the iterator is not | |
1999 | /// consumed until the end. | |
2000 | /// | |
2001 | /// Note 2: It is unspecified how many elements are removed from the vector, | |
2002 | /// if the `Splice` value is leaked. | |
2003 | /// | |
2004 | /// Note 3: The input iterator `replace_with` is only consumed | |
2005 | /// when the `Splice` value is dropped. | |
2006 | /// | |
2007 | /// Note 4: This is optimal if: | |
2008 | /// | |
2009 | /// * The tail (elements in the vector after `range`) is empty, | |
2010 | /// * or `replace_with` yields fewer elements than `range`’s length | |
2011 | /// * or the lower bound of its `size_hint()` is exact. | |
2012 | /// | |
2013 | /// Otherwise, a temporary vector is allocated and the tail is moved twice. | |
2014 | /// | |
2015 | /// # Panics | |
2016 | /// | |
2017 | /// Panics if the starting point is greater than the end point or if | |
2018 | /// the end point is greater than the length of the vector. | |
2019 | /// | |
2020 | /// # Examples | |
2021 | /// | |
2022 | /// ``` | |
7cac9316 XL |
2023 | /// let mut v = vec![1, 2, 3]; |
2024 | /// let new = [7, 8]; | |
2025 | /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect(); | |
2026 | /// assert_eq!(v, &[7, 8, 3]); | |
2027 | /// assert_eq!(u, &[1, 2]); | |
2028 | /// ``` | |
2029 | #[inline] | |
3b2f2976 | 2030 | #[stable(feature = "vec_splice", since = "1.21.0")] |
7cac9316 | 2031 | pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<I::IntoIter> |
0531ce1d | 2032 | where R: RangeBounds<usize>, I: IntoIterator<Item=T> |
7cac9316 XL |
2033 | { |
2034 | Splice { | |
2035 | drain: self.drain(range), | |
2036 | replace_with: replace_with.into_iter(), | |
2037 | } | |
2038 | } | |
2039 | ||
3b2f2976 XL |
2040 | /// Creates an iterator which uses a closure to determine if an element should be removed. |
2041 | /// | |
2042 | /// If the closure returns true, then the element is removed and yielded. | |
0531ce1d XL |
2043 | /// If the closure returns false, the element will remain in the vector and will not be yielded |
2044 | /// by the iterator. | |
3b2f2976 XL |
2045 | /// |
2046 | /// Using this method is equivalent to the following code: | |
2047 | /// | |
2048 | /// ``` | |
ea8adc8c XL |
2049 | /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 }; |
2050 | /// # let mut vec = vec![1, 2, 3, 4, 5, 6]; | |
3b2f2976 XL |
2051 | /// let mut i = 0; |
2052 | /// while i != vec.len() { | |
2053 | /// if some_predicate(&mut vec[i]) { | |
2054 | /// let val = vec.remove(i); | |
2055 | /// // your code here | |
ea8adc8c XL |
2056 | /// } else { |
2057 | /// i += 1; | |
3b2f2976 | 2058 | /// } |
3b2f2976 | 2059 | /// } |
ea8adc8c XL |
2060 | /// |
2061 | /// # assert_eq!(vec, vec![1, 4, 5]); | |
3b2f2976 XL |
2062 | /// ``` |
2063 | /// | |
2064 | /// But `drain_filter` is easier to use. `drain_filter` is also more efficient, | |
2065 | /// because it can backshift the elements of the array in bulk. | |
2066 | /// | |
2067 | /// Note that `drain_filter` also lets you mutate every element in the filter closure, | |
2068 | /// regardless of whether you choose to keep or remove it. | |
2069 | /// | |
2070 | /// | |
2071 | /// # Examples | |
2072 | /// | |
2073 | /// Splitting an array into evens and odds, reusing the original allocation: | |
2074 | /// | |
2075 | /// ``` | |
2076 | /// #![feature(drain_filter)] | |
2077 | /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]; | |
2078 | /// | |
2079 | /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>(); | |
2080 | /// let odds = numbers; | |
2081 | /// | |
2082 | /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); | |
2083 | /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); | |
2084 | /// ``` | |
2085 | #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] | |
2086 | pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<T, F> | |
2087 | where F: FnMut(&mut T) -> bool, | |
2088 | { | |
2089 | let old_len = self.len(); | |
2090 | ||
2091 | // Guard against us getting leaked (leak amplification) | |
2092 | unsafe { self.set_len(0); } | |
2093 | ||
2094 | DrainFilter { | |
2095 | vec: self, | |
2096 | idx: 0, | |
2097 | del: 0, | |
2098 | old_len, | |
2099 | pred: filter, | |
2100 | } | |
2101 | } | |
1a4d82fc JJ |
2102 | } |
2103 | ||
3b2f2976 XL |
2104 | /// Extend implementation that copies elements out of references before pushing them onto the Vec. |
2105 | /// | |
2106 | /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to | |
2107 | /// append the entire slice at once. | |
2108 | /// | |
2109 | /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice | |
62682a34 SL |
2110 | #[stable(feature = "extend_ref", since = "1.2.0")] |
2111 | impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> { | |
92a42be0 | 2112 | fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { |
476ff2be | 2113 | self.spec_extend(iter.into_iter()) |
62682a34 SL |
2114 | } |
2115 | } | |
2116 | ||
92a42be0 SL |
2117 | macro_rules! __impl_slice_eq1 { |
2118 | ($Lhs: ty, $Rhs: ty) => { | |
2119 | __impl_slice_eq1! { $Lhs, $Rhs, Sized } | |
2120 | }; | |
2121 | ($Lhs: ty, $Rhs: ty, $Bound: ident) => { | |
2122 | #[stable(feature = "rust1", since = "1.0.0")] | |
2123 | impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> { | |
2124 | #[inline] | |
2125 | fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] } | |
2126 | #[inline] | |
2127 | fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] } | |
2128 | } | |
2129 | } | |
2130 | } | |
2131 | ||
c34b1796 AL |
2132 | __impl_slice_eq1! { Vec<A>, Vec<B> } |
2133 | __impl_slice_eq1! { Vec<A>, &'b [B] } | |
2134 | __impl_slice_eq1! { Vec<A>, &'b mut [B] } | |
2135 | __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone } | |
2136 | __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone } | |
2137 | __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone } | |
2138 | ||
2139 | macro_rules! array_impls { | |
2140 | ($($N: expr)+) => { | |
2141 | $( | |
2142 | // NOTE: some less important impls are omitted to reduce code bloat | |
2143 | __impl_slice_eq1! { Vec<A>, [B; $N] } | |
2144 | __impl_slice_eq1! { Vec<A>, &'b [B; $N] } | |
2145 | // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] } | |
2146 | // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone } | |
2147 | // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone } | |
2148 | // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone } | |
2149 | )+ | |
1a4d82fc JJ |
2150 | } |
2151 | } | |
2152 | ||
c34b1796 AL |
2153 | array_impls! { |
2154 | 0 1 2 3 4 5 6 7 8 9 | |
2155 | 10 11 12 13 14 15 16 17 18 19 | |
2156 | 20 21 22 23 24 25 26 27 28 29 | |
2157 | 30 31 32 | |
1a4d82fc JJ |
2158 | } |
2159 | ||
8bb4bdeb | 2160 | /// Implements comparison of vectors, lexicographically. |
85aaf69f | 2161 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2162 | impl<T: PartialOrd> PartialOrd for Vec<T> { |
2163 | #[inline] | |
2164 | fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> { | |
85aaf69f | 2165 | PartialOrd::partial_cmp(&**self, &**other) |
1a4d82fc JJ |
2166 | } |
2167 | } | |
2168 | ||
85aaf69f | 2169 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2170 | impl<T: Eq> Eq for Vec<T> {} |
2171 | ||
8bb4bdeb | 2172 | /// Implements ordering of vectors, lexicographically. |
85aaf69f | 2173 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2174 | impl<T: Ord> Ord for Vec<T> { |
2175 | #[inline] | |
2176 | fn cmp(&self, other: &Vec<T>) -> Ordering { | |
85aaf69f | 2177 | Ord::cmp(&**self, &**other) |
1a4d82fc JJ |
2178 | } |
2179 | } | |
2180 | ||
85aaf69f | 2181 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 2182 | unsafe impl<#[may_dangle] T> Drop for Vec<T> { |
1a4d82fc | 2183 | fn drop(&mut self) { |
9e0c209e SL |
2184 | unsafe { |
2185 | // use drop for [T] | |
2186 | ptr::drop_in_place(&mut self[..]); | |
1a4d82fc | 2187 | } |
c1a9b12d | 2188 | // RawVec handles deallocation |
1a4d82fc JJ |
2189 | } |
2190 | } | |
2191 | ||
85aaf69f | 2192 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2193 | impl<T> Default for Vec<T> { |
9e0c209e | 2194 | /// Creates an empty `Vec<T>`. |
1a4d82fc JJ |
2195 | fn default() -> Vec<T> { |
2196 | Vec::new() | |
2197 | } | |
2198 | } | |
2199 | ||
85aaf69f SL |
2200 | #[stable(feature = "rust1", since = "1.0.0")] |
2201 | impl<T: fmt::Debug> fmt::Debug for Vec<T> { | |
1a4d82fc | 2202 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
85aaf69f | 2203 | fmt::Debug::fmt(&**self, f) |
1a4d82fc JJ |
2204 | } |
2205 | } | |
2206 | ||
c34b1796 AL |
2207 | #[stable(feature = "rust1", since = "1.0.0")] |
2208 | impl<T> AsRef<Vec<T>> for Vec<T> { | |
2209 | fn as_ref(&self) -> &Vec<T> { | |
2210 | self | |
2211 | } | |
2212 | } | |
2213 | ||
b039eaaf SL |
2214 | #[stable(feature = "vec_as_mut", since = "1.5.0")] |
2215 | impl<T> AsMut<Vec<T>> for Vec<T> { | |
2216 | fn as_mut(&mut self) -> &mut Vec<T> { | |
2217 | self | |
2218 | } | |
2219 | } | |
2220 | ||
c34b1796 AL |
2221 | #[stable(feature = "rust1", since = "1.0.0")] |
2222 | impl<T> AsRef<[T]> for Vec<T> { | |
2223 | fn as_ref(&self) -> &[T] { | |
2224 | self | |
2225 | } | |
2226 | } | |
2227 | ||
b039eaaf SL |
2228 | #[stable(feature = "vec_as_mut", since = "1.5.0")] |
2229 | impl<T> AsMut<[T]> for Vec<T> { | |
2230 | fn as_mut(&mut self) -> &mut [T] { | |
2231 | self | |
2232 | } | |
2233 | } | |
2234 | ||
c34b1796 AL |
2235 | #[stable(feature = "rust1", since = "1.0.0")] |
2236 | impl<'a, T: Clone> From<&'a [T]> for Vec<T> { | |
2237 | #[cfg(not(test))] | |
2238 | fn from(s: &'a [T]) -> Vec<T> { | |
2239 | s.to_vec() | |
2240 | } | |
2241 | #[cfg(test)] | |
2242 | fn from(s: &'a [T]) -> Vec<T> { | |
2243 | ::slice::to_vec(s) | |
2244 | } | |
2245 | } | |
2246 | ||
7cac9316 XL |
2247 | #[stable(feature = "vec_from_mut", since = "1.19.0")] |
2248 | impl<'a, T: Clone> From<&'a mut [T]> for Vec<T> { | |
2249 | #[cfg(not(test))] | |
2250 | fn from(s: &'a mut [T]) -> Vec<T> { | |
2251 | s.to_vec() | |
2252 | } | |
2253 | #[cfg(test)] | |
2254 | fn from(s: &'a mut [T]) -> Vec<T> { | |
2255 | ::slice::to_vec(s) | |
2256 | } | |
2257 | } | |
2258 | ||
c30ab7b3 SL |
2259 | #[stable(feature = "vec_from_cow_slice", since = "1.14.0")] |
2260 | impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> { | |
2261 | fn from(s: Cow<'a, [T]>) -> Vec<T> { | |
2262 | s.into_owned() | |
2263 | } | |
2264 | } | |
2265 | ||
cc61c64b XL |
2266 | // note: test pulls in libstd, which causes errors here |
2267 | #[cfg(not(test))] | |
7cac9316 | 2268 | #[stable(feature = "vec_from_box", since = "1.18.0")] |
cc61c64b XL |
2269 | impl<T> From<Box<[T]>> for Vec<T> { |
2270 | fn from(s: Box<[T]>) -> Vec<T> { | |
2271 | s.into_vec() | |
2272 | } | |
2273 | } | |
2274 | ||
041b39d2 XL |
2275 | // note: test pulls in libstd, which causes errors here |
2276 | #[cfg(not(test))] | |
2277 | #[stable(feature = "box_from_vec", since = "1.20.0")] | |
2278 | impl<T> From<Vec<T>> for Box<[T]> { | |
2279 | fn from(v: Vec<T>) -> Box<[T]> { | |
2280 | v.into_boxed_slice() | |
cc61c64b XL |
2281 | } |
2282 | } | |
2283 | ||
c34b1796 AL |
2284 | #[stable(feature = "rust1", since = "1.0.0")] |
2285 | impl<'a> From<&'a str> for Vec<u8> { | |
2286 | fn from(s: &'a str) -> Vec<u8> { | |
2287 | From::from(s.as_bytes()) | |
2288 | } | |
2289 | } | |
2290 | ||
1a4d82fc JJ |
2291 | //////////////////////////////////////////////////////////////////////////////// |
2292 | // Clone-on-write | |
2293 | //////////////////////////////////////////////////////////////////////////////// | |
2294 | ||
7cac9316 | 2295 | #[stable(feature = "cow_from_vec", since = "1.8.0")] |
7453a54e SL |
2296 | impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> { |
2297 | fn from(s: &'a [T]) -> Cow<'a, [T]> { | |
2298 | Cow::Borrowed(s) | |
2299 | } | |
2300 | } | |
2301 | ||
7cac9316 | 2302 | #[stable(feature = "cow_from_vec", since = "1.8.0")] |
7453a54e SL |
2303 | impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> { |
2304 | fn from(v: Vec<T>) -> Cow<'a, [T]> { | |
2305 | Cow::Owned(v) | |
2306 | } | |
2307 | } | |
2308 | ||
94b46f34 XL |
2309 | #[stable(feature = "cow_from_vec_ref", since = "1.28.0")] |
2310 | impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> { | |
2311 | fn from(v: &'a Vec<T>) -> Cow<'a, [T]> { | |
2312 | Cow::Borrowed(v.as_slice()) | |
2313 | } | |
2314 | } | |
2315 | ||
bd371182 | 2316 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 2317 | impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone { |
92a42be0 | 2318 | fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> { |
1a4d82fc JJ |
2319 | Cow::Owned(FromIterator::from_iter(it)) |
2320 | } | |
2321 | } | |
2322 | ||
1a4d82fc JJ |
2323 | //////////////////////////////////////////////////////////////////////////////// |
2324 | // Iterators | |
2325 | //////////////////////////////////////////////////////////////////////////////// | |
2326 | ||
2327 | /// An iterator that moves out of a vector. | |
5bcae85e SL |
2328 | /// |
2329 | /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided | |
2330 | /// by the [`IntoIterator`] trait). | |
2331 | /// | |
2332 | /// [`Vec`]: struct.Vec.html | |
2333 | /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html | |
85aaf69f | 2334 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2335 | pub struct IntoIter<T> { |
2c00a5a8 | 2336 | buf: NonNull<T>, |
ff7c6d11 | 2337 | phantom: PhantomData<T>, |
5bcae85e | 2338 | cap: usize, |
1a4d82fc | 2339 | ptr: *const T, |
92a42be0 | 2340 | end: *const T, |
1a4d82fc JJ |
2341 | } |
2342 | ||
c30ab7b3 | 2343 | #[stable(feature = "vec_intoiter_debug", since = "1.13.0")] |
9e0c209e SL |
2344 | impl<T: fmt::Debug> fmt::Debug for IntoIter<T> { |
2345 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
2346 | f.debug_tuple("IntoIter") | |
2347 | .field(&self.as_slice()) | |
2348 | .finish() | |
2349 | } | |
2350 | } | |
2351 | ||
5bcae85e SL |
2352 | impl<T> IntoIter<T> { |
2353 | /// Returns the remaining items of this iterator as a slice. | |
2354 | /// | |
2355 | /// # Examples | |
2356 | /// | |
c30ab7b3 | 2357 | /// ``` |
5bcae85e SL |
2358 | /// let vec = vec!['a', 'b', 'c']; |
2359 | /// let mut into_iter = vec.into_iter(); | |
2360 | /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); | |
2361 | /// let _ = into_iter.next().unwrap(); | |
2362 | /// assert_eq!(into_iter.as_slice(), &['b', 'c']); | |
2363 | /// ``` | |
476ff2be | 2364 | #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] |
5bcae85e SL |
2365 | pub fn as_slice(&self) -> &[T] { |
2366 | unsafe { | |
2367 | slice::from_raw_parts(self.ptr, self.len()) | |
2368 | } | |
2369 | } | |
2370 | ||
2371 | /// Returns the remaining items of this iterator as a mutable slice. | |
2372 | /// | |
2373 | /// # Examples | |
2374 | /// | |
c30ab7b3 | 2375 | /// ``` |
5bcae85e SL |
2376 | /// let vec = vec!['a', 'b', 'c']; |
2377 | /// let mut into_iter = vec.into_iter(); | |
2378 | /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); | |
2379 | /// into_iter.as_mut_slice()[2] = 'z'; | |
2380 | /// assert_eq!(into_iter.next().unwrap(), 'a'); | |
2381 | /// assert_eq!(into_iter.next().unwrap(), 'b'); | |
2382 | /// assert_eq!(into_iter.next().unwrap(), 'z'); | |
2383 | /// ``` | |
476ff2be | 2384 | #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] |
e81b0574 | 2385 | pub fn as_mut_slice(&mut self) -> &mut [T] { |
5bcae85e SL |
2386 | unsafe { |
2387 | slice::from_raw_parts_mut(self.ptr as *mut T, self.len()) | |
2388 | } | |
2389 | } | |
2390 | } | |
2391 | ||
92a42be0 SL |
2392 | #[stable(feature = "rust1", since = "1.0.0")] |
2393 | unsafe impl<T: Send> Send for IntoIter<T> {} | |
2394 | #[stable(feature = "rust1", since = "1.0.0")] | |
2395 | unsafe impl<T: Sync> Sync for IntoIter<T> {} | |
85aaf69f | 2396 | |
85aaf69f | 2397 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2398 | impl<T> Iterator for IntoIter<T> { |
2399 | type Item = T; | |
2400 | ||
2401 | #[inline] | |
85aaf69f | 2402 | fn next(&mut self) -> Option<T> { |
1a4d82fc | 2403 | unsafe { |
5bcae85e | 2404 | if self.ptr as *const _ == self.end { |
1a4d82fc JJ |
2405 | None |
2406 | } else { | |
2407 | if mem::size_of::<T>() == 0 { | |
2408 | // purposefully don't use 'ptr.offset' because for | |
2409 | // vectors with 0-size elements this would return the | |
2410 | // same pointer. | |
5bcae85e | 2411 | self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T; |
1a4d82fc | 2412 | |
b7449926 XL |
2413 | // Make up a value of this ZST. |
2414 | Some(mem::zeroed()) | |
1a4d82fc JJ |
2415 | } else { |
2416 | let old = self.ptr; | |
2417 | self.ptr = self.ptr.offset(1); | |
2418 | ||
2419 | Some(ptr::read(old)) | |
2420 | } | |
2421 | } | |
2422 | } | |
2423 | } | |
2424 | ||
2425 | #[inline] | |
85aaf69f | 2426 | fn size_hint(&self) -> (usize, Option<usize>) { |
83c7162d XL |
2427 | let exact = if mem::size_of::<T>() == 0 { |
2428 | (self.end as usize).wrapping_sub(self.ptr as usize) | |
2429 | } else { | |
2430 | unsafe { self.end.offset_from(self.ptr) as usize } | |
cc61c64b | 2431 | }; |
1a4d82fc JJ |
2432 | (exact, Some(exact)) |
2433 | } | |
d9579d0f AL |
2434 | |
2435 | #[inline] | |
2436 | fn count(self) -> usize { | |
3157f602 | 2437 | self.len() |
d9579d0f | 2438 | } |
1a4d82fc JJ |
2439 | } |
2440 | ||
85aaf69f | 2441 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2442 | impl<T> DoubleEndedIterator for IntoIter<T> { |
2443 | #[inline] | |
85aaf69f | 2444 | fn next_back(&mut self) -> Option<T> { |
1a4d82fc JJ |
2445 | unsafe { |
2446 | if self.end == self.ptr { | |
2447 | None | |
2448 | } else { | |
2449 | if mem::size_of::<T>() == 0 { | |
2450 | // See above for why 'ptr.offset' isn't used | |
5bcae85e | 2451 | self.end = arith_offset(self.end as *const i8, -1) as *mut T; |
1a4d82fc | 2452 | |
b7449926 XL |
2453 | // Make up a value of this ZST. |
2454 | Some(mem::zeroed()) | |
1a4d82fc JJ |
2455 | } else { |
2456 | self.end = self.end.offset(-1); | |
2457 | ||
e9174d1e | 2458 | Some(ptr::read(self.end)) |
1a4d82fc JJ |
2459 | } |
2460 | } | |
2461 | } | |
2462 | } | |
2463 | } | |
2464 | ||
85aaf69f | 2465 | #[stable(feature = "rust1", since = "1.0.0")] |
476ff2be SL |
2466 | impl<T> ExactSizeIterator for IntoIter<T> { |
2467 | fn is_empty(&self) -> bool { | |
2468 | self.ptr == self.end | |
2469 | } | |
2470 | } | |
1a4d82fc | 2471 | |
0531ce1d | 2472 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
2473 | impl<T> FusedIterator for IntoIter<T> {} |
2474 | ||
c30ab7b3 SL |
2475 | #[unstable(feature = "trusted_len", issue = "37572")] |
2476 | unsafe impl<T> TrustedLen for IntoIter<T> {} | |
2477 | ||
7453a54e SL |
2478 | #[stable(feature = "vec_into_iter_clone", since = "1.8.0")] |
2479 | impl<T: Clone> Clone for IntoIter<T> { | |
2480 | fn clone(&self) -> IntoIter<T> { | |
5bcae85e | 2481 | self.as_slice().to_owned().into_iter() |
7453a54e SL |
2482 | } |
2483 | } | |
2484 | ||
85aaf69f | 2485 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 2486 | unsafe impl<#[may_dangle] T> Drop for IntoIter<T> { |
1a4d82fc JJ |
2487 | fn drop(&mut self) { |
2488 | // destroy the remaining elements | |
5bcae85e | 2489 | for _x in self.by_ref() {} |
c1a9b12d SL |
2490 | |
2491 | // RawVec handles deallocation | |
7cac9316 | 2492 | let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) }; |
1a4d82fc JJ |
2493 | } |
2494 | } | |
2495 | ||
d9579d0f | 2496 | /// A draining iterator for `Vec<T>`. |
5bcae85e SL |
2497 | /// |
2498 | /// This `struct` is created by the [`drain`] method on [`Vec`]. | |
2499 | /// | |
2500 | /// [`drain`]: struct.Vec.html#method.drain | |
2501 | /// [`Vec`]: struct.Vec.html | |
92a42be0 | 2502 | #[stable(feature = "drain", since = "1.6.0")] |
d9579d0f AL |
2503 | pub struct Drain<'a, T: 'a> { |
2504 | /// Index of tail to preserve | |
2505 | tail_start: usize, | |
2506 | /// Length of tail | |
2507 | tail_len: usize, | |
2508 | /// Current remaining range to remove | |
5bcae85e | 2509 | iter: slice::Iter<'a, T>, |
2c00a5a8 | 2510 | vec: NonNull<Vec<T>>, |
1a4d82fc JJ |
2511 | } |
2512 | ||
8bb4bdeb XL |
2513 | #[stable(feature = "collection_debug", since = "1.17.0")] |
2514 | impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> { | |
2515 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
2516 | f.debug_tuple("Drain") | |
2517 | .field(&self.iter.as_slice()) | |
2518 | .finish() | |
2519 | } | |
2520 | } | |
2521 | ||
92a42be0 | 2522 | #[stable(feature = "drain", since = "1.6.0")] |
c34b1796 | 2523 | unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {} |
92a42be0 | 2524 | #[stable(feature = "drain", since = "1.6.0")] |
c34b1796 AL |
2525 | unsafe impl<'a, T: Send> Send for Drain<'a, T> {} |
2526 | ||
c30ab7b3 | 2527 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2528 | impl<'a, T> Iterator for Drain<'a, T> { |
2529 | type Item = T; | |
2530 | ||
2531 | #[inline] | |
2532 | fn next(&mut self) -> Option<T> { | |
92a42be0 | 2533 | self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) }) |
1a4d82fc JJ |
2534 | } |
2535 | ||
85aaf69f | 2536 | fn size_hint(&self) -> (usize, Option<usize>) { |
d9579d0f | 2537 | self.iter.size_hint() |
1a4d82fc JJ |
2538 | } |
2539 | } | |
2540 | ||
c30ab7b3 | 2541 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2542 | impl<'a, T> DoubleEndedIterator for Drain<'a, T> { |
2543 | #[inline] | |
2544 | fn next_back(&mut self) -> Option<T> { | |
92a42be0 | 2545 | self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) }) |
1a4d82fc JJ |
2546 | } |
2547 | } | |
2548 | ||
c30ab7b3 | 2549 | #[stable(feature = "drain", since = "1.6.0")] |
1a4d82fc JJ |
2550 | impl<'a, T> Drop for Drain<'a, T> { |
2551 | fn drop(&mut self) { | |
d9579d0f | 2552 | // exhaust self first |
83c7162d | 2553 | self.for_each(drop); |
1a4d82fc | 2554 | |
d9579d0f AL |
2555 | if self.tail_len > 0 { |
2556 | unsafe { | |
7cac9316 | 2557 | let source_vec = self.vec.as_mut(); |
d9579d0f AL |
2558 | // memmove back untouched tail, update to new length |
2559 | let start = source_vec.len(); | |
2560 | let tail = self.tail_start; | |
83c7162d | 2561 | if tail != start { |
b7449926 XL |
2562 | let src = source_vec.as_ptr().add(tail); |
2563 | let dst = source_vec.as_mut_ptr().add(start); | |
83c7162d XL |
2564 | ptr::copy(src, dst, self.tail_len); |
2565 | } | |
d9579d0f AL |
2566 | source_vec.set_len(start + self.tail_len); |
2567 | } | |
2568 | } | |
1a4d82fc JJ |
2569 | } |
2570 | } | |
2571 | ||
d9579d0f | 2572 | |
c30ab7b3 | 2573 | #[stable(feature = "drain", since = "1.6.0")] |
476ff2be SL |
2574 | impl<'a, T> ExactSizeIterator for Drain<'a, T> { |
2575 | fn is_empty(&self) -> bool { | |
2576 | self.iter.is_empty() | |
2577 | } | |
2578 | } | |
9e0c209e | 2579 | |
0531ce1d | 2580 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e | 2581 | impl<'a, T> FusedIterator for Drain<'a, T> {} |
32a655c1 | 2582 | |
7cac9316 XL |
2583 | /// A splicing iterator for `Vec`. |
2584 | /// | |
2585 | /// This struct is created by the [`splice()`] method on [`Vec`]. See its | |
2586 | /// documentation for more. | |
2587 | /// | |
2588 | /// [`splice()`]: struct.Vec.html#method.splice | |
2589 | /// [`Vec`]: struct.Vec.html | |
2590 | #[derive(Debug)] | |
3b2f2976 | 2591 | #[stable(feature = "vec_splice", since = "1.21.0")] |
7cac9316 XL |
2592 | pub struct Splice<'a, I: Iterator + 'a> { |
2593 | drain: Drain<'a, I::Item>, | |
2594 | replace_with: I, | |
2595 | } | |
2596 | ||
3b2f2976 | 2597 | #[stable(feature = "vec_splice", since = "1.21.0")] |
7cac9316 XL |
2598 | impl<'a, I: Iterator> Iterator for Splice<'a, I> { |
2599 | type Item = I::Item; | |
2600 | ||
2601 | fn next(&mut self) -> Option<Self::Item> { | |
2602 | self.drain.next() | |
2603 | } | |
2604 | ||
2605 | fn size_hint(&self) -> (usize, Option<usize>) { | |
2606 | self.drain.size_hint() | |
2607 | } | |
2608 | } | |
2609 | ||
3b2f2976 | 2610 | #[stable(feature = "vec_splice", since = "1.21.0")] |
7cac9316 XL |
2611 | impl<'a, I: Iterator> DoubleEndedIterator for Splice<'a, I> { |
2612 | fn next_back(&mut self) -> Option<Self::Item> { | |
2613 | self.drain.next_back() | |
2614 | } | |
2615 | } | |
2616 | ||
3b2f2976 | 2617 | #[stable(feature = "vec_splice", since = "1.21.0")] |
7cac9316 XL |
2618 | impl<'a, I: Iterator> ExactSizeIterator for Splice<'a, I> {} |
2619 | ||
2620 | ||
3b2f2976 | 2621 | #[stable(feature = "vec_splice", since = "1.21.0")] |
7cac9316 XL |
2622 | impl<'a, I: Iterator> Drop for Splice<'a, I> { |
2623 | fn drop(&mut self) { | |
83c7162d | 2624 | self.drain.by_ref().for_each(drop); |
7cac9316 XL |
2625 | |
2626 | unsafe { | |
2627 | if self.drain.tail_len == 0 { | |
2628 | self.drain.vec.as_mut().extend(self.replace_with.by_ref()); | |
2629 | return | |
2630 | } | |
2631 | ||
2632 | // First fill the range left by drain(). | |
2633 | if !self.drain.fill(&mut self.replace_with) { | |
2634 | return | |
2635 | } | |
2636 | ||
2637 | // There may be more elements. Use the lower bound as an estimate. | |
2638 | // FIXME: Is the upper bound a better guess? Or something else? | |
2639 | let (lower_bound, _upper_bound) = self.replace_with.size_hint(); | |
2640 | if lower_bound > 0 { | |
2641 | self.drain.move_tail(lower_bound); | |
2642 | if !self.drain.fill(&mut self.replace_with) { | |
2643 | return | |
2644 | } | |
2645 | } | |
2646 | ||
2647 | // Collect any remaining elements. | |
2648 | // This is a zero-length vector which does not allocate if `lower_bound` was exact. | |
2649 | let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter(); | |
2650 | // Now we have an exact count. | |
2651 | if collected.len() > 0 { | |
2652 | self.drain.move_tail(collected.len()); | |
2653 | let filled = self.drain.fill(&mut collected); | |
2654 | debug_assert!(filled); | |
2655 | debug_assert_eq!(collected.len(), 0); | |
2656 | } | |
2657 | } | |
2658 | // Let `Drain::drop` move the tail back if necessary and restore `vec.len`. | |
2659 | } | |
2660 | } | |
2661 | ||
2662 | /// Private helper methods for `Splice::drop` | |
2663 | impl<'a, T> Drain<'a, T> { | |
2664 | /// The range from `self.vec.len` to `self.tail_start` contains elements | |
2665 | /// that have been moved out. | |
2666 | /// Fill that range as much as possible with new elements from the `replace_with` iterator. | |
2667 | /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.) | |
2668 | unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool { | |
2669 | let vec = self.vec.as_mut(); | |
2670 | let range_start = vec.len; | |
2671 | let range_end = self.tail_start; | |
2672 | let range_slice = slice::from_raw_parts_mut( | |
b7449926 | 2673 | vec.as_mut_ptr().add(range_start), |
7cac9316 XL |
2674 | range_end - range_start); |
2675 | ||
2676 | for place in range_slice { | |
2677 | if let Some(new_item) = replace_with.next() { | |
2678 | ptr::write(place, new_item); | |
2679 | vec.len += 1; | |
2680 | } else { | |
2681 | return false | |
2682 | } | |
2683 | } | |
2684 | true | |
2685 | } | |
2686 | ||
2687 | /// Make room for inserting more elements before the tail. | |
2688 | unsafe fn move_tail(&mut self, extra_capacity: usize) { | |
2689 | let vec = self.vec.as_mut(); | |
2690 | let used_capacity = self.tail_start + self.tail_len; | |
2691 | vec.buf.reserve(used_capacity, extra_capacity); | |
2692 | ||
2693 | let new_tail_start = self.tail_start + extra_capacity; | |
b7449926 XL |
2694 | let src = vec.as_ptr().add(self.tail_start); |
2695 | let dst = vec.as_mut_ptr().add(new_tail_start); | |
7cac9316 XL |
2696 | ptr::copy(src, dst, self.tail_len); |
2697 | self.tail_start = new_tail_start; | |
2698 | } | |
2699 | } | |
3b2f2976 XL |
2700 | |
2701 | /// An iterator produced by calling `drain_filter` on Vec. | |
2702 | #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] | |
2703 | #[derive(Debug)] | |
2704 | pub struct DrainFilter<'a, T: 'a, F> | |
2705 | where F: FnMut(&mut T) -> bool, | |
2706 | { | |
2707 | vec: &'a mut Vec<T>, | |
2708 | idx: usize, | |
2709 | del: usize, | |
2710 | old_len: usize, | |
2711 | pred: F, | |
2712 | } | |
2713 | ||
2714 | #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] | |
2715 | impl<'a, T, F> Iterator for DrainFilter<'a, T, F> | |
2716 | where F: FnMut(&mut T) -> bool, | |
2717 | { | |
2718 | type Item = T; | |
2719 | ||
2720 | fn next(&mut self) -> Option<T> { | |
2721 | unsafe { | |
2722 | while self.idx != self.old_len { | |
2723 | let i = self.idx; | |
2724 | self.idx += 1; | |
2725 | let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len); | |
2726 | if (self.pred)(&mut v[i]) { | |
2727 | self.del += 1; | |
2728 | return Some(ptr::read(&v[i])); | |
2729 | } else if self.del > 0 { | |
ea8adc8c XL |
2730 | let del = self.del; |
2731 | let src: *const T = &v[i]; | |
2732 | let dst: *mut T = &mut v[i - del]; | |
2733 | // This is safe because self.vec has length 0 | |
2734 | // thus its elements will not have Drop::drop | |
2735 | // called on them in the event of a panic. | |
2736 | ptr::copy_nonoverlapping(src, dst, 1); | |
3b2f2976 XL |
2737 | } |
2738 | } | |
2739 | None | |
2740 | } | |
2741 | } | |
2742 | ||
2743 | fn size_hint(&self) -> (usize, Option<usize>) { | |
2744 | (0, Some(self.old_len - self.idx)) | |
2745 | } | |
2746 | } | |
2747 | ||
2748 | #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] | |
2749 | impl<'a, T, F> Drop for DrainFilter<'a, T, F> | |
2750 | where F: FnMut(&mut T) -> bool, | |
2751 | { | |
2752 | fn drop(&mut self) { | |
83c7162d | 2753 | self.for_each(drop); |
3b2f2976 XL |
2754 | unsafe { |
2755 | self.vec.set_len(self.old_len - self.del); | |
2756 | } | |
2757 | } | |
2758 | } |