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