1 | //! A contiguous growable array type with heap-allocated contents, written |
2 | //! `Vec<T>`. |
3 | //! |
4 | //! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and |
5 | //! *O*(1) pop (from the end). |
6 | //! |
7 | //! Vectors ensure they never allocate more than `isize::MAX` bytes. |
8 | //! |
9 | //! # Examples |
10 | //! |
11 | //! You can explicitly create a [`Vec`] with [`Vec::new`]: |
12 | //! |
13 | //! ``` |
14 | //! let v: Vec<i32> = Vec::new(); |
15 | //! ``` |
16 | //! |
17 | //! ...or by using the [`vec!`] macro: |
18 | //! |
19 | //! ``` |
20 | //! let v: Vec<i32> = vec![]; |
21 | //! |
22 | //! let v = vec![1, 2, 3, 4, 5]; |
23 | //! |
24 | //! let v = vec![0; 10]; // ten zeroes |
25 | //! ``` |
26 | //! |
27 | //! You can [`push`] values onto the end of a vector (which will grow the vector |
28 | //! as needed): |
29 | //! |
30 | //! ``` |
31 | //! let mut v = vec![1, 2]; |
32 | //! |
33 | //! v.push(3); |
34 | //! ``` |
35 | //! |
36 | //! Popping values works in much the same way: |
37 | //! |
38 | //! ``` |
39 | //! let mut v = vec![1, 2]; |
40 | //! |
41 | //! let two = v.pop(); |
42 | //! ``` |
43 | //! |
44 | //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits): |
45 | //! |
46 | //! ``` |
47 | //! let mut v = vec![1, 2, 3]; |
48 | //! let three = v[2]; |
49 | //! v[1] = v[1] + 5; |
50 | //! ``` |
51 | //! |
52 | //! [`push`]: Vec::push |
53 | |
54 | #![stable (feature = "rust1" , since = "1.0.0" )] |
55 | |
56 | #[cfg (not(no_global_oom_handling))] |
57 | use core::cmp; |
58 | use core::cmp::Ordering; |
59 | use core::fmt; |
60 | use core::hash::{Hash, Hasher}; |
61 | #[cfg (not(no_global_oom_handling))] |
62 | use core::iter; |
63 | use core::marker::PhantomData; |
64 | use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties}; |
65 | use core::ops::{self, Index, IndexMut, Range, RangeBounds}; |
66 | use core::ptr::{self, NonNull}; |
67 | use core::slice::{self, SliceIndex}; |
68 | |
69 | use crate::alloc::{Allocator, Global}; |
70 | use crate::borrow::{Cow, ToOwned}; |
71 | use crate::boxed::Box; |
72 | use crate::collections::TryReserveError; |
73 | use crate::raw_vec::RawVec; |
74 | |
75 | #[unstable (feature = "extract_if" , reason = "recently added" , issue = "43244" )] |
76 | pub use self::extract_if::ExtractIf; |
77 | |
78 | mod extract_if; |
79 | |
80 | #[cfg (not(no_global_oom_handling))] |
81 | #[stable (feature = "vec_splice" , since = "1.21.0" )] |
82 | pub use self::splice::Splice; |
83 | |
84 | #[cfg (not(no_global_oom_handling))] |
85 | mod splice; |
86 | |
87 | #[stable (feature = "drain" , since = "1.6.0" )] |
88 | pub use self::drain::Drain; |
89 | |
90 | mod drain; |
91 | |
92 | #[cfg (not(no_global_oom_handling))] |
93 | mod cow; |
94 | |
95 | #[cfg (not(no_global_oom_handling))] |
96 | pub(crate) use self::in_place_collect::AsVecIntoIter; |
97 | #[stable (feature = "rust1" , since = "1.0.0" )] |
98 | pub use self::into_iter::IntoIter; |
99 | |
100 | mod into_iter; |
101 | |
102 | #[cfg (not(no_global_oom_handling))] |
103 | use self::is_zero::IsZero; |
104 | |
105 | #[cfg (not(no_global_oom_handling))] |
106 | mod is_zero; |
107 | |
108 | #[cfg (not(no_global_oom_handling))] |
109 | mod in_place_collect; |
110 | |
111 | mod partial_eq; |
112 | |
113 | #[cfg (not(no_global_oom_handling))] |
114 | use self::spec_from_elem::SpecFromElem; |
115 | |
116 | #[cfg (not(no_global_oom_handling))] |
117 | mod spec_from_elem; |
118 | |
119 | #[cfg (not(no_global_oom_handling))] |
120 | use self::set_len_on_drop::SetLenOnDrop; |
121 | |
122 | #[cfg (not(no_global_oom_handling))] |
123 | mod set_len_on_drop; |
124 | |
125 | #[cfg (not(no_global_oom_handling))] |
126 | use self::in_place_drop::{InPlaceDrop, InPlaceDstDataSrcBufDrop}; |
127 | |
128 | #[cfg (not(no_global_oom_handling))] |
129 | mod in_place_drop; |
130 | |
131 | #[cfg (not(no_global_oom_handling))] |
132 | use self::spec_from_iter_nested::SpecFromIterNested; |
133 | |
134 | #[cfg (not(no_global_oom_handling))] |
135 | mod spec_from_iter_nested; |
136 | |
137 | #[cfg (not(no_global_oom_handling))] |
138 | use self::spec_from_iter::SpecFromIter; |
139 | |
140 | #[cfg (not(no_global_oom_handling))] |
141 | mod spec_from_iter; |
142 | |
143 | #[cfg (not(no_global_oom_handling))] |
144 | use self::spec_extend::SpecExtend; |
145 | |
146 | #[cfg (not(no_global_oom_handling))] |
147 | mod spec_extend; |
148 | |
149 | /// A contiguous growable array type, written as `Vec<T>`, short for 'vector'. |
150 | /// |
151 | /// # Examples |
152 | /// |
153 | /// ``` |
154 | /// let mut vec = Vec::new(); |
155 | /// vec.push(1); |
156 | /// vec.push(2); |
157 | /// |
158 | /// assert_eq!(vec.len(), 2); |
159 | /// assert_eq!(vec[0], 1); |
160 | /// |
161 | /// assert_eq!(vec.pop(), Some(2)); |
162 | /// assert_eq!(vec.len(), 1); |
163 | /// |
164 | /// vec[0] = 7; |
165 | /// assert_eq!(vec[0], 7); |
166 | /// |
167 | /// vec.extend([1, 2, 3]); |
168 | /// |
169 | /// for x in &vec { |
170 | /// println!("{x}" ); |
171 | /// } |
172 | /// assert_eq!(vec, [7, 1, 2, 3]); |
173 | /// ``` |
174 | /// |
175 | /// The [`vec!`] macro is provided for convenient initialization: |
176 | /// |
177 | /// ``` |
178 | /// let mut vec1 = vec![1, 2, 3]; |
179 | /// vec1.push(4); |
180 | /// let vec2 = Vec::from([1, 2, 3, 4]); |
181 | /// assert_eq!(vec1, vec2); |
182 | /// ``` |
183 | /// |
184 | /// It can also initialize each element of a `Vec<T>` with a given value. |
185 | /// This may be more efficient than performing allocation and initialization |
186 | /// in separate steps, especially when initializing a vector of zeros: |
187 | /// |
188 | /// ``` |
189 | /// let vec = vec![0; 5]; |
190 | /// assert_eq!(vec, [0, 0, 0, 0, 0]); |
191 | /// |
192 | /// // The following is equivalent, but potentially slower: |
193 | /// let mut vec = Vec::with_capacity(5); |
194 | /// vec.resize(5, 0); |
195 | /// assert_eq!(vec, [0, 0, 0, 0, 0]); |
196 | /// ``` |
197 | /// |
198 | /// For more information, see |
199 | /// [Capacity and Reallocation](#capacity-and-reallocation). |
200 | /// |
201 | /// Use a `Vec<T>` as an efficient stack: |
202 | /// |
203 | /// ``` |
204 | /// let mut stack = Vec::new(); |
205 | /// |
206 | /// stack.push(1); |
207 | /// stack.push(2); |
208 | /// stack.push(3); |
209 | /// |
210 | /// while let Some(top) = stack.pop() { |
211 | /// // Prints 3, 2, 1 |
212 | /// println!("{top}" ); |
213 | /// } |
214 | /// ``` |
215 | /// |
216 | /// # Indexing |
217 | /// |
218 | /// The `Vec` type allows access to values by index, because it implements the |
219 | /// [`Index`] trait. An example will be more explicit: |
220 | /// |
221 | /// ``` |
222 | /// let v = vec![0, 2, 4, 6]; |
223 | /// println!("{}" , v[1]); // it will display '2' |
224 | /// ``` |
225 | /// |
226 | /// However be careful: if you try to access an index which isn't in the `Vec`, |
227 | /// your software will panic! You cannot do this: |
228 | /// |
229 | /// ```should_panic |
230 | /// let v = vec![0, 2, 4, 6]; |
231 | /// println!("{}" , v[6]); // it will panic! |
232 | /// ``` |
233 | /// |
234 | /// Use [`get`] and [`get_mut`] if you want to check whether the index is in |
235 | /// the `Vec`. |
236 | /// |
237 | /// # Slicing |
238 | /// |
239 | /// A `Vec` can be mutable. On the other hand, slices are read-only objects. |
240 | /// To get a [slice][prim@slice], use [`&`]. Example: |
241 | /// |
242 | /// ``` |
243 | /// fn read_slice(slice: &[usize]) { |
244 | /// // ... |
245 | /// } |
246 | /// |
247 | /// let v = vec![0, 1]; |
248 | /// read_slice(&v); |
249 | /// |
250 | /// // ... and that's all! |
251 | /// // you can also do it like this: |
252 | /// let u: &[usize] = &v; |
253 | /// // or like this: |
254 | /// let u: &[_] = &v; |
255 | /// ``` |
256 | /// |
257 | /// In Rust, it's more common to pass slices as arguments rather than vectors |
258 | /// when you just want to provide read access. The same goes for [`String`] and |
259 | /// [`&str`]. |
260 | /// |
261 | /// # Capacity and reallocation |
262 | /// |
263 | /// The capacity of a vector is the amount of space allocated for any future |
264 | /// elements that will be added onto the vector. This is not to be confused with |
265 | /// the *length* of a vector, which specifies the number of actual elements |
266 | /// within the vector. If a vector's length exceeds its capacity, its capacity |
267 | /// will automatically be increased, but its elements will have to be |
268 | /// reallocated. |
269 | /// |
270 | /// For example, a vector with capacity 10 and length 0 would be an empty vector |
271 | /// with space for 10 more elements. Pushing 10 or fewer elements onto the |
272 | /// vector will not change its capacity or cause reallocation to occur. However, |
273 | /// if the vector's length is increased to 11, it will have to reallocate, which |
274 | /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`] |
275 | /// whenever possible to specify how big the vector is expected to get. |
276 | /// |
277 | /// # Guarantees |
278 | /// |
279 | /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees |
280 | /// about its design. This ensures that it's as low-overhead as possible in |
281 | /// the general case, and can be correctly manipulated in primitive ways |
282 | /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`. |
283 | /// If additional type parameters are added (e.g., to support custom allocators), |
284 | /// overriding their defaults may change the behavior. |
285 | /// |
286 | /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length) |
287 | /// triplet. No more, no less. The order of these fields is completely |
288 | /// unspecified, and you should use the appropriate methods to modify these. |
289 | /// The pointer will never be null, so this type is null-pointer-optimized. |
290 | /// |
291 | /// However, the pointer might not actually point to allocated memory. In particular, |
292 | /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`], |
293 | /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`] |
294 | /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized |
295 | /// types inside a `Vec`, it will not allocate space for them. *Note that in this case |
296 | /// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only |
297 | /// if <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation |
298 | /// details are very subtle --- if you intend to allocate memory using a `Vec` |
299 | /// and use it for something else (either to pass to unsafe code, or to build your |
300 | /// own memory-backed collection), be sure to deallocate this memory by using |
301 | /// `from_raw_parts` to recover the `Vec` and then dropping it. |
302 | /// |
303 | /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap |
304 | /// (as defined by the allocator Rust is configured to use by default), and its |
305 | /// pointer points to [`len`] initialized, contiguous elements in order (what |
306 | /// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code> |
307 | /// logically uninitialized, contiguous elements. |
308 | /// |
309 | /// A vector containing the elements `'a'` and `'b'` with capacity 4 can be |
310 | /// visualized as below. The top part is the `Vec` struct, it contains a |
311 | /// pointer to the head of the allocation in the heap, length and capacity. |
312 | /// The bottom part is the allocation on the heap, a contiguous memory block. |
313 | /// |
314 | /// ```text |
315 | /// ptr len capacity |
316 | /// +--------+--------+--------+ |
317 | /// | 0x0123 | 2 | 4 | |
318 | /// +--------+--------+--------+ |
319 | /// | |
320 | /// v |
321 | /// Heap +--------+--------+--------+--------+ |
322 | /// | 'a' | 'b' | uninit | uninit | |
323 | /// +--------+--------+--------+--------+ |
324 | /// ``` |
325 | /// |
326 | /// - **uninit** represents memory that is not initialized, see [`MaybeUninit`]. |
327 | /// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory |
328 | /// layout (including the order of fields). |
329 | /// |
330 | /// `Vec` will never perform a "small optimization" where elements are actually |
331 | /// stored on the stack for two reasons: |
332 | /// |
333 | /// * It would make it more difficult for unsafe code to correctly manipulate |
334 | /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were |
335 | /// only moved, and it would be more difficult to determine if a `Vec` had |
336 | /// actually allocated memory. |
337 | /// |
338 | /// * It would penalize the general case, incurring an additional branch |
339 | /// on every access. |
340 | /// |
341 | /// `Vec` will never automatically shrink itself, even if completely empty. This |
342 | /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec` |
343 | /// and then filling it back up to the same [`len`] should incur no calls to |
344 | /// the allocator. If you wish to free up unused memory, use |
345 | /// [`shrink_to_fit`] or [`shrink_to`]. |
346 | /// |
347 | /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is |
348 | /// sufficient. [`push`] and [`insert`] *will* (re)allocate if |
349 | /// <code>[len] == [capacity]</code>. That is, the reported capacity is completely |
350 | /// accurate, and can be relied on. It can even be used to manually free the memory |
351 | /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even |
352 | /// when not necessary. |
353 | /// |
354 | /// `Vec` does not guarantee any particular growth strategy when reallocating |
355 | /// when full, nor when [`reserve`] is called. The current strategy is basic |
356 | /// and it may prove desirable to use a non-constant growth factor. Whatever |
357 | /// strategy is used will of course guarantee *O*(1) amortized [`push`]. |
358 | /// |
359 | /// `vec![x; n]`, `vec![a, b, c, d]`, and |
360 | /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec` |
361 | /// with at least the requested capacity. If <code>[len] == [capacity]</code>, |
362 | /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to |
363 | /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements. |
364 | /// |
365 | /// `Vec` will not specifically overwrite any data that is removed from it, |
366 | /// but also won't specifically preserve it. Its uninitialized memory is |
367 | /// scratch space that it may use however it wants. It will generally just do |
368 | /// whatever is most efficient or otherwise easy to implement. Do not rely on |
369 | /// removed data to be erased for security purposes. Even if you drop a `Vec`, its |
370 | /// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory |
371 | /// first, that might not actually happen because the optimizer does not consider |
372 | /// this a side-effect that must be preserved. There is one case which we will |
373 | /// not break, however: using `unsafe` code to write to the excess capacity, |
374 | /// and then increasing the length to match, is always valid. |
375 | /// |
376 | /// Currently, `Vec` does not guarantee the order in which elements are dropped. |
377 | /// The order has changed in the past and may change again. |
378 | /// |
379 | /// [`get`]: slice::get |
380 | /// [`get_mut`]: slice::get_mut |
381 | /// [`String`]: crate::string::String |
382 | /// [`&str`]: type@str |
383 | /// [`shrink_to_fit`]: Vec::shrink_to_fit |
384 | /// [`shrink_to`]: Vec::shrink_to |
385 | /// [capacity]: Vec::capacity |
386 | /// [`capacity`]: Vec::capacity |
387 | /// [mem::size_of::\<T>]: core::mem::size_of |
388 | /// [len]: Vec::len |
389 | /// [`len`]: Vec::len |
390 | /// [`push`]: Vec::push |
391 | /// [`insert`]: Vec::insert |
392 | /// [`reserve`]: Vec::reserve |
393 | /// [`MaybeUninit`]: core::mem::MaybeUninit |
394 | /// [owned slice]: Box |
395 | #[stable (feature = "rust1" , since = "1.0.0" )] |
396 | #[cfg_attr (not(test), rustc_diagnostic_item = "Vec" )] |
397 | #[rustc_insignificant_dtor ] |
398 | pub struct Vec<T, #[unstable (feature = "allocator_api" , issue = "32838" )] A: Allocator = Global> { |
399 | buf: RawVec<T, A>, |
400 | len: usize, |
401 | } |
402 | |
403 | //////////////////////////////////////////////////////////////////////////////// |
404 | // Inherent methods |
405 | //////////////////////////////////////////////////////////////////////////////// |
406 | |
407 | impl<T> Vec<T> { |
408 | /// Constructs a new, empty `Vec<T>`. |
409 | /// |
410 | /// The vector will not allocate until elements are pushed onto it. |
411 | /// |
412 | /// # Examples |
413 | /// |
414 | /// ``` |
415 | /// # #![allow (unused_mut)] |
416 | /// let mut vec: Vec<i32> = Vec::new(); |
417 | /// ``` |
418 | #[inline ] |
419 | #[rustc_const_stable (feature = "const_vec_new" , since = "1.39.0" )] |
420 | #[stable (feature = "rust1" , since = "1.0.0" )] |
421 | #[must_use ] |
422 | pub const fn new() -> Self { |
423 | Vec { buf: RawVec::NEW, len: 0 } |
424 | } |
425 | |
426 | /// Constructs a new, empty `Vec<T>` with at least the specified capacity. |
427 | /// |
428 | /// The vector will be able to hold at least `capacity` elements without |
429 | /// reallocating. This method is allowed to allocate for more elements than |
430 | /// `capacity`. If `capacity` is 0, the vector will not allocate. |
431 | /// |
432 | /// It is important to note that although the returned vector has the |
433 | /// minimum *capacity* specified, the vector will have a zero *length*. For |
434 | /// an explanation of the difference between length and capacity, see |
435 | /// *[Capacity and reallocation]*. |
436 | /// |
437 | /// If it is important to know the exact allocated capacity of a `Vec`, |
438 | /// always use the [`capacity`] method after construction. |
439 | /// |
440 | /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation |
441 | /// and the capacity will always be `usize::MAX`. |
442 | /// |
443 | /// [Capacity and reallocation]: #capacity-and-reallocation |
444 | /// [`capacity`]: Vec::capacity |
445 | /// |
446 | /// # Panics |
447 | /// |
448 | /// Panics if the new capacity exceeds `isize::MAX` _bytes_. |
449 | /// |
450 | /// # Examples |
451 | /// |
452 | /// ``` |
453 | /// let mut vec = Vec::with_capacity(10); |
454 | /// |
455 | /// // The vector contains no items, even though it has capacity for more |
456 | /// assert_eq!(vec.len(), 0); |
457 | /// assert!(vec.capacity() >= 10); |
458 | /// |
459 | /// // These are all done without reallocating... |
460 | /// for i in 0..10 { |
461 | /// vec.push(i); |
462 | /// } |
463 | /// assert_eq!(vec.len(), 10); |
464 | /// assert!(vec.capacity() >= 10); |
465 | /// |
466 | /// // ...but this may make the vector reallocate |
467 | /// vec.push(11); |
468 | /// assert_eq!(vec.len(), 11); |
469 | /// assert!(vec.capacity() >= 11); |
470 | /// |
471 | /// // A vector of a zero-sized type will always over-allocate, since no |
472 | /// // allocation is necessary |
473 | /// let vec_units = Vec::<()>::with_capacity(10); |
474 | /// assert_eq!(vec_units.capacity(), usize::MAX); |
475 | /// ``` |
476 | #[cfg (not(no_global_oom_handling))] |
477 | #[inline ] |
478 | #[stable (feature = "rust1" , since = "1.0.0" )] |
479 | #[must_use ] |
480 | pub fn with_capacity(capacity: usize) -> Self { |
481 | Self::with_capacity_in(capacity, Global) |
482 | } |
483 | |
484 | /// Constructs a new, empty `Vec<T>` with at least the specified capacity. |
485 | /// |
486 | /// The vector will be able to hold at least `capacity` elements without |
487 | /// reallocating. This method is allowed to allocate for more elements than |
488 | /// `capacity`. If `capacity` is 0, the vector will not allocate. |
489 | /// |
490 | /// # Errors |
491 | /// |
492 | /// Returns an error if the capacity exceeds `isize::MAX` _bytes_, |
493 | /// or if the allocator reports allocation failure. |
494 | #[inline ] |
495 | #[unstable (feature = "try_with_capacity" , issue = "91913" )] |
496 | pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> { |
497 | Self::try_with_capacity_in(capacity, Global) |
498 | } |
499 | |
500 | /// Creates a `Vec<T>` directly from a pointer, a length, and a capacity. |
501 | /// |
502 | /// # Safety |
503 | /// |
504 | /// This is highly unsafe, due to the number of invariants that aren't |
505 | /// checked: |
506 | /// |
507 | /// * `ptr` must have been allocated using the global allocator, such as via |
508 | /// the [`alloc::alloc`] function. |
509 | /// * `T` needs to have the same alignment as what `ptr` was allocated with. |
510 | /// (`T` having a less strict alignment is not sufficient, the alignment really |
511 | /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be |
512 | /// allocated and deallocated with the same layout.) |
513 | /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs |
514 | /// to be the same size as the pointer was allocated with. (Because similar to |
515 | /// alignment, [`dealloc`] must be called with the same layout `size`.) |
516 | /// * `length` needs to be less than or equal to `capacity`. |
517 | /// * The first `length` values must be properly initialized values of type `T`. |
518 | /// * `capacity` needs to be the capacity that the pointer was allocated with. |
519 | /// * The allocated size in bytes must be no larger than `isize::MAX`. |
520 | /// See the safety documentation of [`pointer::offset`]. |
521 | /// |
522 | /// These requirements are always upheld by any `ptr` that has been allocated |
523 | /// via `Vec<T>`. Other allocation sources are allowed if the invariants are |
524 | /// upheld. |
525 | /// |
526 | /// Violating these may cause problems like corrupting the allocator's |
527 | /// internal data structures. For example it is normally **not** safe |
528 | /// to build a `Vec<u8>` from a pointer to a C `char` array with length |
529 | /// `size_t`, doing so is only safe if the array was initially allocated by |
530 | /// a `Vec` or `String`. |
531 | /// It's also not safe to build one from a `Vec<u16>` and its length, because |
532 | /// the allocator cares about the alignment, and these two types have different |
533 | /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after |
534 | /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid |
535 | /// these issues, it is often preferable to do casting/transmuting using |
536 | /// [`slice::from_raw_parts`] instead. |
537 | /// |
538 | /// The ownership of `ptr` is effectively transferred to the |
539 | /// `Vec<T>` which may then deallocate, reallocate or change the |
540 | /// contents of memory pointed to by the pointer at will. Ensure |
541 | /// that nothing else uses the pointer after calling this |
542 | /// function. |
543 | /// |
544 | /// [`String`]: crate::string::String |
545 | /// [`alloc::alloc`]: crate::alloc::alloc |
546 | /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc |
547 | /// |
548 | /// # Examples |
549 | /// |
550 | /// ``` |
551 | /// use std::ptr; |
552 | /// use std::mem; |
553 | /// |
554 | /// let v = vec![1, 2, 3]; |
555 | /// |
556 | // FIXME Update this when vec_into_raw_parts is stabilized |
557 | /// // Prevent running `v`'s destructor so we are in complete control |
558 | /// // of the allocation. |
559 | /// let mut v = mem::ManuallyDrop::new(v); |
560 | /// |
561 | /// // Pull out the various important pieces of information about `v` |
562 | /// let p = v.as_mut_ptr(); |
563 | /// let len = v.len(); |
564 | /// let cap = v.capacity(); |
565 | /// |
566 | /// unsafe { |
567 | /// // Overwrite memory with 4, 5, 6 |
568 | /// for i in 0..len { |
569 | /// ptr::write(p.add(i), 4 + i); |
570 | /// } |
571 | /// |
572 | /// // Put everything back together into a Vec |
573 | /// let rebuilt = Vec::from_raw_parts(p, len, cap); |
574 | /// assert_eq!(rebuilt, [4, 5, 6]); |
575 | /// } |
576 | /// ``` |
577 | /// |
578 | /// Using memory that was allocated elsewhere: |
579 | /// |
580 | /// ```rust |
581 | /// use std::alloc::{alloc, Layout}; |
582 | /// |
583 | /// fn main() { |
584 | /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen" ); |
585 | /// |
586 | /// let vec = unsafe { |
587 | /// let mem = alloc(layout).cast::<u32>(); |
588 | /// if mem.is_null() { |
589 | /// return; |
590 | /// } |
591 | /// |
592 | /// mem.write(1_000_000); |
593 | /// |
594 | /// Vec::from_raw_parts(mem, 1, 16) |
595 | /// }; |
596 | /// |
597 | /// assert_eq!(vec, &[1_000_000]); |
598 | /// assert_eq!(vec.capacity(), 16); |
599 | /// } |
600 | /// ``` |
601 | #[inline ] |
602 | #[stable (feature = "rust1" , since = "1.0.0" )] |
603 | pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { |
604 | unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) } |
605 | } |
606 | |
607 | /// A convenience method for hoisting the non-null precondition out of [`Vec::from_raw_parts`]. |
608 | /// |
609 | /// # Safety |
610 | /// |
611 | /// See [`Vec::from_raw_parts`]. |
612 | #[inline ] |
613 | #[cfg (not(no_global_oom_handling))] // required by tests/run-make/alloc-no-oom-handling |
614 | pub(crate) unsafe fn from_nonnull(ptr: NonNull<T>, length: usize, capacity: usize) -> Self { |
615 | unsafe { Self::from_nonnull_in(ptr, length, capacity, Global) } |
616 | } |
617 | } |
618 | |
619 | impl<T, A: Allocator> Vec<T, A> { |
620 | /// Constructs a new, empty `Vec<T, A>`. |
621 | /// |
622 | /// The vector will not allocate until elements are pushed onto it. |
623 | /// |
624 | /// # Examples |
625 | /// |
626 | /// ``` |
627 | /// #![feature(allocator_api)] |
628 | /// |
629 | /// use std::alloc::System; |
630 | /// |
631 | /// # #[allow (unused_mut)] |
632 | /// let mut vec: Vec<i32, _> = Vec::new_in(System); |
633 | /// ``` |
634 | #[inline ] |
635 | #[unstable (feature = "allocator_api" , issue = "32838" )] |
636 | pub const fn new_in(alloc: A) -> Self { |
637 | Vec { buf: RawVec::new_in(alloc), len: 0 } |
638 | } |
639 | |
640 | /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity |
641 | /// with the provided allocator. |
642 | /// |
643 | /// The vector will be able to hold at least `capacity` elements without |
644 | /// reallocating. This method is allowed to allocate for more elements than |
645 | /// `capacity`. If `capacity` is 0, the vector will not allocate. |
646 | /// |
647 | /// It is important to note that although the returned vector has the |
648 | /// minimum *capacity* specified, the vector will have a zero *length*. For |
649 | /// an explanation of the difference between length and capacity, see |
650 | /// *[Capacity and reallocation]*. |
651 | /// |
652 | /// If it is important to know the exact allocated capacity of a `Vec`, |
653 | /// always use the [`capacity`] method after construction. |
654 | /// |
655 | /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation |
656 | /// and the capacity will always be `usize::MAX`. |
657 | /// |
658 | /// [Capacity and reallocation]: #capacity-and-reallocation |
659 | /// [`capacity`]: Vec::capacity |
660 | /// |
661 | /// # Panics |
662 | /// |
663 | /// Panics if the new capacity exceeds `isize::MAX` _bytes_. |
664 | /// |
665 | /// # Examples |
666 | /// |
667 | /// ``` |
668 | /// #![feature(allocator_api)] |
669 | /// |
670 | /// use std::alloc::System; |
671 | /// |
672 | /// let mut vec = Vec::with_capacity_in(10, System); |
673 | /// |
674 | /// // The vector contains no items, even though it has capacity for more |
675 | /// assert_eq!(vec.len(), 0); |
676 | /// assert!(vec.capacity() >= 10); |
677 | /// |
678 | /// // These are all done without reallocating... |
679 | /// for i in 0..10 { |
680 | /// vec.push(i); |
681 | /// } |
682 | /// assert_eq!(vec.len(), 10); |
683 | /// assert!(vec.capacity() >= 10); |
684 | /// |
685 | /// // ...but this may make the vector reallocate |
686 | /// vec.push(11); |
687 | /// assert_eq!(vec.len(), 11); |
688 | /// assert!(vec.capacity() >= 11); |
689 | /// |
690 | /// // A vector of a zero-sized type will always over-allocate, since no |
691 | /// // allocation is necessary |
692 | /// let vec_units = Vec::<(), System>::with_capacity_in(10, System); |
693 | /// assert_eq!(vec_units.capacity(), usize::MAX); |
694 | /// ``` |
695 | #[cfg (not(no_global_oom_handling))] |
696 | #[inline ] |
697 | #[unstable (feature = "allocator_api" , issue = "32838" )] |
698 | pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { |
699 | Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } |
700 | } |
701 | |
702 | /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity |
703 | /// with the provided allocator. |
704 | /// |
705 | /// The vector will be able to hold at least `capacity` elements without |
706 | /// reallocating. This method is allowed to allocate for more elements than |
707 | /// `capacity`. If `capacity` is 0, the vector will not allocate. |
708 | /// |
709 | /// # Errors |
710 | /// |
711 | /// Returns an error if the capacity exceeds `isize::MAX` _bytes_, |
712 | /// or if the allocator reports allocation failure. |
713 | #[inline ] |
714 | #[unstable (feature = "allocator_api" , issue = "32838" )] |
715 | // #[unstable(feature = "try_with_capacity", issue = "91913")] |
716 | pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> { |
717 | Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 }) |
718 | } |
719 | |
720 | /// Creates a `Vec<T, A>` directly from a pointer, a length, a capacity, |
721 | /// and an allocator. |
722 | /// |
723 | /// # Safety |
724 | /// |
725 | /// This is highly unsafe, due to the number of invariants that aren't |
726 | /// checked: |
727 | /// |
728 | /// * `ptr` must be [*currently allocated*] via the given allocator `alloc`. |
729 | /// * `T` needs to have the same alignment as what `ptr` was allocated with. |
730 | /// (`T` having a less strict alignment is not sufficient, the alignment really |
731 | /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be |
732 | /// allocated and deallocated with the same layout.) |
733 | /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs |
734 | /// to be the same size as the pointer was allocated with. (Because similar to |
735 | /// alignment, [`dealloc`] must be called with the same layout `size`.) |
736 | /// * `length` needs to be less than or equal to `capacity`. |
737 | /// * The first `length` values must be properly initialized values of type `T`. |
738 | /// * `capacity` needs to [*fit*] the layout size that the pointer was allocated with. |
739 | /// * The allocated size in bytes must be no larger than `isize::MAX`. |
740 | /// See the safety documentation of [`pointer::offset`]. |
741 | /// |
742 | /// These requirements are always upheld by any `ptr` that has been allocated |
743 | /// via `Vec<T, A>`. Other allocation sources are allowed if the invariants are |
744 | /// upheld. |
745 | /// |
746 | /// Violating these may cause problems like corrupting the allocator's |
747 | /// internal data structures. For example it is **not** safe |
748 | /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`. |
749 | /// It's also not safe to build one from a `Vec<u16>` and its length, because |
750 | /// the allocator cares about the alignment, and these two types have different |
751 | /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after |
752 | /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. |
753 | /// |
754 | /// The ownership of `ptr` is effectively transferred to the |
755 | /// `Vec<T>` which may then deallocate, reallocate or change the |
756 | /// contents of memory pointed to by the pointer at will. Ensure |
757 | /// that nothing else uses the pointer after calling this |
758 | /// function. |
759 | /// |
760 | /// [`String`]: crate::string::String |
761 | /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc |
762 | /// [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory |
763 | /// [*fit*]: crate::alloc::Allocator#memory-fitting |
764 | /// |
765 | /// # Examples |
766 | /// |
767 | /// ``` |
768 | /// #![feature(allocator_api)] |
769 | /// |
770 | /// use std::alloc::System; |
771 | /// |
772 | /// use std::ptr; |
773 | /// use std::mem; |
774 | /// |
775 | /// let mut v = Vec::with_capacity_in(3, System); |
776 | /// v.push(1); |
777 | /// v.push(2); |
778 | /// v.push(3); |
779 | /// |
780 | // FIXME Update this when vec_into_raw_parts is stabilized |
781 | /// // Prevent running `v`'s destructor so we are in complete control |
782 | /// // of the allocation. |
783 | /// let mut v = mem::ManuallyDrop::new(v); |
784 | /// |
785 | /// // Pull out the various important pieces of information about `v` |
786 | /// let p = v.as_mut_ptr(); |
787 | /// let len = v.len(); |
788 | /// let cap = v.capacity(); |
789 | /// let alloc = v.allocator(); |
790 | /// |
791 | /// unsafe { |
792 | /// // Overwrite memory with 4, 5, 6 |
793 | /// for i in 0..len { |
794 | /// ptr::write(p.add(i), 4 + i); |
795 | /// } |
796 | /// |
797 | /// // Put everything back together into a Vec |
798 | /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); |
799 | /// assert_eq!(rebuilt, [4, 5, 6]); |
800 | /// } |
801 | /// ``` |
802 | /// |
803 | /// Using memory that was allocated elsewhere: |
804 | /// |
805 | /// ```rust |
806 | /// #![feature(allocator_api)] |
807 | /// |
808 | /// use std::alloc::{AllocError, Allocator, Global, Layout}; |
809 | /// |
810 | /// fn main() { |
811 | /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen" ); |
812 | /// |
813 | /// let vec = unsafe { |
814 | /// let mem = match Global.allocate(layout) { |
815 | /// Ok(mem) => mem.cast::<u32>().as_ptr(), |
816 | /// Err(AllocError) => return, |
817 | /// }; |
818 | /// |
819 | /// mem.write(1_000_000); |
820 | /// |
821 | /// Vec::from_raw_parts_in(mem, 1, 16, Global) |
822 | /// }; |
823 | /// |
824 | /// assert_eq!(vec, &[1_000_000]); |
825 | /// assert_eq!(vec.capacity(), 16); |
826 | /// } |
827 | /// ``` |
828 | #[inline ] |
829 | #[unstable (feature = "allocator_api" , issue = "32838" )] |
830 | pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { |
831 | unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } |
832 | } |
833 | |
834 | /// A convenience method for hoisting the non-null precondition out of [`Vec::from_raw_parts_in`]. |
835 | /// |
836 | /// # Safety |
837 | /// |
838 | /// See [`Vec::from_raw_parts_in`]. |
839 | #[inline ] |
840 | #[cfg (not(no_global_oom_handling))] // required by tests/run-make/alloc-no-oom-handling |
841 | pub(crate) unsafe fn from_nonnull_in( |
842 | ptr: NonNull<T>, |
843 | length: usize, |
844 | capacity: usize, |
845 | alloc: A, |
846 | ) -> Self { |
847 | unsafe { Vec { buf: RawVec::from_nonnull_in(ptr, capacity, alloc), len: length } } |
848 | } |
849 | |
850 | /// Decomposes a `Vec<T>` into its raw components: `(pointer, length, capacity)`. |
851 | /// |
852 | /// Returns the raw pointer to the underlying data, the length of |
853 | /// the vector (in elements), and the allocated capacity of the |
854 | /// data (in elements). These are the same arguments in the same |
855 | /// order as the arguments to [`from_raw_parts`]. |
856 | /// |
857 | /// After calling this function, the caller is responsible for the |
858 | /// memory previously managed by the `Vec`. The only way to do |
859 | /// this is to convert the raw pointer, length, and capacity back |
860 | /// into a `Vec` with the [`from_raw_parts`] function, allowing |
861 | /// the destructor to perform the cleanup. |
862 | /// |
863 | /// [`from_raw_parts`]: Vec::from_raw_parts |
864 | /// |
865 | /// # Examples |
866 | /// |
867 | /// ``` |
868 | /// #![feature(vec_into_raw_parts)] |
869 | /// let v: Vec<i32> = vec![-1, 0, 1]; |
870 | /// |
871 | /// let (ptr, len, cap) = v.into_raw_parts(); |
872 | /// |
873 | /// let rebuilt = unsafe { |
874 | /// // We can now make changes to the components, such as |
875 | /// // transmuting the raw pointer to a compatible type. |
876 | /// let ptr = ptr as *mut u32; |
877 | /// |
878 | /// Vec::from_raw_parts(ptr, len, cap) |
879 | /// }; |
880 | /// assert_eq!(rebuilt, [4294967295, 0, 1]); |
881 | /// ``` |
882 | #[unstable (feature = "vec_into_raw_parts" , reason = "new API" , issue = "65816" )] |
883 | pub fn into_raw_parts(self) -> (*mut T, usize, usize) { |
884 | let mut me = ManuallyDrop::new(self); |
885 | (me.as_mut_ptr(), me.len(), me.capacity()) |
886 | } |
887 | |
888 | /// Decomposes a `Vec<T>` into its raw components: `(pointer, length, capacity, allocator)`. |
889 | /// |
890 | /// Returns the raw pointer to the underlying data, the length of the vector (in elements), |
891 | /// the allocated capacity of the data (in elements), and the allocator. These are the same |
892 | /// arguments in the same order as the arguments to [`from_raw_parts_in`]. |
893 | /// |
894 | /// After calling this function, the caller is responsible for the |
895 | /// memory previously managed by the `Vec`. The only way to do |
896 | /// this is to convert the raw pointer, length, and capacity back |
897 | /// into a `Vec` with the [`from_raw_parts_in`] function, allowing |
898 | /// the destructor to perform the cleanup. |
899 | /// |
900 | /// [`from_raw_parts_in`]: Vec::from_raw_parts_in |
901 | /// |
902 | /// # Examples |
903 | /// |
904 | /// ``` |
905 | /// #![feature(allocator_api, vec_into_raw_parts)] |
906 | /// |
907 | /// use std::alloc::System; |
908 | /// |
909 | /// let mut v: Vec<i32, System> = Vec::new_in(System); |
910 | /// v.push(-1); |
911 | /// v.push(0); |
912 | /// v.push(1); |
913 | /// |
914 | /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc(); |
915 | /// |
916 | /// let rebuilt = unsafe { |
917 | /// // We can now make changes to the components, such as |
918 | /// // transmuting the raw pointer to a compatible type. |
919 | /// let ptr = ptr as *mut u32; |
920 | /// |
921 | /// Vec::from_raw_parts_in(ptr, len, cap, alloc) |
922 | /// }; |
923 | /// assert_eq!(rebuilt, [4294967295, 0, 1]); |
924 | /// ``` |
925 | #[unstable (feature = "allocator_api" , issue = "32838" )] |
926 | // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] |
927 | pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) { |
928 | let mut me = ManuallyDrop::new(self); |
929 | let len = me.len(); |
930 | let capacity = me.capacity(); |
931 | let ptr = me.as_mut_ptr(); |
932 | let alloc = unsafe { ptr::read(me.allocator()) }; |
933 | (ptr, len, capacity, alloc) |
934 | } |
935 | |
936 | /// Returns the total number of elements the vector can hold without |
937 | /// reallocating. |
938 | /// |
939 | /// # Examples |
940 | /// |
941 | /// ``` |
942 | /// let mut vec: Vec<i32> = Vec::with_capacity(10); |
943 | /// vec.push(42); |
944 | /// assert!(vec.capacity() >= 10); |
945 | /// ``` |
946 | #[inline ] |
947 | #[stable (feature = "rust1" , since = "1.0.0" )] |
948 | pub fn capacity(&self) -> usize { |
949 | self.buf.capacity() |
950 | } |
951 | |
952 | /// Reserves capacity for at least `additional` more elements to be inserted |
953 | /// in the given `Vec<T>`. The collection may reserve more space to |
954 | /// speculatively avoid frequent reallocations. After calling `reserve`, |
955 | /// capacity will be greater than or equal to `self.len() + additional`. |
956 | /// Does nothing if capacity is already sufficient. |
957 | /// |
958 | /// # Panics |
959 | /// |
960 | /// Panics if the new capacity exceeds `isize::MAX` _bytes_. |
961 | /// |
962 | /// # Examples |
963 | /// |
964 | /// ``` |
965 | /// let mut vec = vec![1]; |
966 | /// vec.reserve(10); |
967 | /// assert!(vec.capacity() >= 11); |
968 | /// ``` |
969 | #[cfg (not(no_global_oom_handling))] |
970 | #[stable (feature = "rust1" , since = "1.0.0" )] |
971 | pub fn reserve(&mut self, additional: usize) { |
972 | self.buf.reserve(self.len, additional); |
973 | } |
974 | |
975 | /// Reserves the minimum capacity for at least `additional` more elements to |
976 | /// be inserted in the given `Vec<T>`. Unlike [`reserve`], this will not |
977 | /// deliberately over-allocate to speculatively avoid frequent allocations. |
978 | /// After calling `reserve_exact`, capacity will be greater than or equal to |
979 | /// `self.len() + additional`. Does nothing if the capacity is already |
980 | /// sufficient. |
981 | /// |
982 | /// Note that the allocator may give the collection more space than it |
983 | /// requests. Therefore, capacity can not be relied upon to be precisely |
984 | /// minimal. Prefer [`reserve`] if future insertions are expected. |
985 | /// |
986 | /// [`reserve`]: Vec::reserve |
987 | /// |
988 | /// # Panics |
989 | /// |
990 | /// Panics if the new capacity exceeds `isize::MAX` _bytes_. |
991 | /// |
992 | /// # Examples |
993 | /// |
994 | /// ``` |
995 | /// let mut vec = vec![1]; |
996 | /// vec.reserve_exact(10); |
997 | /// assert!(vec.capacity() >= 11); |
998 | /// ``` |
999 | #[cfg (not(no_global_oom_handling))] |
1000 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1001 | pub fn reserve_exact(&mut self, additional: usize) { |
1002 | self.buf.reserve_exact(self.len, additional); |
1003 | } |
1004 | |
1005 | /// Tries to reserve capacity for at least `additional` more elements to be inserted |
1006 | /// in the given `Vec<T>`. The collection may reserve more space to speculatively avoid |
1007 | /// frequent reallocations. After calling `try_reserve`, capacity will be |
1008 | /// greater than or equal to `self.len() + additional` if it returns |
1009 | /// `Ok(())`. Does nothing if capacity is already sufficient. This method |
1010 | /// preserves the contents even if an error occurs. |
1011 | /// |
1012 | /// # Errors |
1013 | /// |
1014 | /// If the capacity overflows, or the allocator reports a failure, then an error |
1015 | /// is returned. |
1016 | /// |
1017 | /// # Examples |
1018 | /// |
1019 | /// ``` |
1020 | /// use std::collections::TryReserveError; |
1021 | /// |
1022 | /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> { |
1023 | /// let mut output = Vec::new(); |
1024 | /// |
1025 | /// // Pre-reserve the memory, exiting if we can't |
1026 | /// output.try_reserve(data.len())?; |
1027 | /// |
1028 | /// // Now we know this can't OOM in the middle of our complex work |
1029 | /// output.extend(data.iter().map(|&val| { |
1030 | /// val * 2 + 5 // very complicated |
1031 | /// })); |
1032 | /// |
1033 | /// Ok(output) |
1034 | /// } |
1035 | /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?" ); |
1036 | /// ``` |
1037 | #[stable (feature = "try_reserve" , since = "1.57.0" )] |
1038 | pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { |
1039 | self.buf.try_reserve(self.len, additional) |
1040 | } |
1041 | |
1042 | /// Tries to reserve the minimum capacity for at least `additional` |
1043 | /// elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`], |
1044 | /// this will not deliberately over-allocate to speculatively avoid frequent |
1045 | /// allocations. After calling `try_reserve_exact`, capacity will be greater |
1046 | /// than or equal to `self.len() + additional` if it returns `Ok(())`. |
1047 | /// Does nothing if the capacity is already sufficient. |
1048 | /// |
1049 | /// Note that the allocator may give the collection more space than it |
1050 | /// requests. Therefore, capacity can not be relied upon to be precisely |
1051 | /// minimal. Prefer [`try_reserve`] if future insertions are expected. |
1052 | /// |
1053 | /// [`try_reserve`]: Vec::try_reserve |
1054 | /// |
1055 | /// # Errors |
1056 | /// |
1057 | /// If the capacity overflows, or the allocator reports a failure, then an error |
1058 | /// is returned. |
1059 | /// |
1060 | /// # Examples |
1061 | /// |
1062 | /// ``` |
1063 | /// use std::collections::TryReserveError; |
1064 | /// |
1065 | /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> { |
1066 | /// let mut output = Vec::new(); |
1067 | /// |
1068 | /// // Pre-reserve the memory, exiting if we can't |
1069 | /// output.try_reserve_exact(data.len())?; |
1070 | /// |
1071 | /// // Now we know this can't OOM in the middle of our complex work |
1072 | /// output.extend(data.iter().map(|&val| { |
1073 | /// val * 2 + 5 // very complicated |
1074 | /// })); |
1075 | /// |
1076 | /// Ok(output) |
1077 | /// } |
1078 | /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?" ); |
1079 | /// ``` |
1080 | #[stable (feature = "try_reserve" , since = "1.57.0" )] |
1081 | pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { |
1082 | self.buf.try_reserve_exact(self.len, additional) |
1083 | } |
1084 | |
1085 | /// Shrinks the capacity of the vector as much as possible. |
1086 | /// |
1087 | /// The behavior of this method depends on the allocator, which may either shrink the vector |
1088 | /// in-place or reallocate. The resulting vector might still have some excess capacity, just as |
1089 | /// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details. |
1090 | /// |
1091 | /// [`with_capacity`]: Vec::with_capacity |
1092 | /// |
1093 | /// # Examples |
1094 | /// |
1095 | /// ``` |
1096 | /// let mut vec = Vec::with_capacity(10); |
1097 | /// vec.extend([1, 2, 3]); |
1098 | /// assert!(vec.capacity() >= 10); |
1099 | /// vec.shrink_to_fit(); |
1100 | /// assert!(vec.capacity() >= 3); |
1101 | /// ``` |
1102 | #[cfg (not(no_global_oom_handling))] |
1103 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1104 | pub fn shrink_to_fit(&mut self) { |
1105 | // The capacity is never less than the length, and there's nothing to do when |
1106 | // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` |
1107 | // by only calling it with a greater capacity. |
1108 | if self.capacity() > self.len { |
1109 | self.buf.shrink_to_fit(self.len); |
1110 | } |
1111 | } |
1112 | |
1113 | /// Shrinks the capacity of the vector with a lower bound. |
1114 | /// |
1115 | /// The capacity will remain at least as large as both the length |
1116 | /// and the supplied value. |
1117 | /// |
1118 | /// If the current capacity is less than the lower limit, this is a no-op. |
1119 | /// |
1120 | /// # Examples |
1121 | /// |
1122 | /// ``` |
1123 | /// let mut vec = Vec::with_capacity(10); |
1124 | /// vec.extend([1, 2, 3]); |
1125 | /// assert!(vec.capacity() >= 10); |
1126 | /// vec.shrink_to(4); |
1127 | /// assert!(vec.capacity() >= 4); |
1128 | /// vec.shrink_to(0); |
1129 | /// assert!(vec.capacity() >= 3); |
1130 | /// ``` |
1131 | #[cfg (not(no_global_oom_handling))] |
1132 | #[stable (feature = "shrink_to" , since = "1.56.0" )] |
1133 | pub fn shrink_to(&mut self, min_capacity: usize) { |
1134 | if self.capacity() > min_capacity { |
1135 | self.buf.shrink_to_fit(cmp::max(self.len, min_capacity)); |
1136 | } |
1137 | } |
1138 | |
1139 | /// Converts the vector into [`Box<[T]>`][owned slice]. |
1140 | /// |
1141 | /// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`]. |
1142 | /// |
1143 | /// [owned slice]: Box |
1144 | /// [`shrink_to_fit`]: Vec::shrink_to_fit |
1145 | /// |
1146 | /// # Examples |
1147 | /// |
1148 | /// ``` |
1149 | /// let v = vec![1, 2, 3]; |
1150 | /// |
1151 | /// let slice = v.into_boxed_slice(); |
1152 | /// ``` |
1153 | /// |
1154 | /// Any excess capacity is removed: |
1155 | /// |
1156 | /// ``` |
1157 | /// let mut vec = Vec::with_capacity(10); |
1158 | /// vec.extend([1, 2, 3]); |
1159 | /// |
1160 | /// assert!(vec.capacity() >= 10); |
1161 | /// let slice = vec.into_boxed_slice(); |
1162 | /// assert_eq!(slice.into_vec().capacity(), 3); |
1163 | /// ``` |
1164 | #[cfg (not(no_global_oom_handling))] |
1165 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1166 | pub fn into_boxed_slice(mut self) -> Box<[T], A> { |
1167 | unsafe { |
1168 | self.shrink_to_fit(); |
1169 | let me = ManuallyDrop::new(self); |
1170 | let buf = ptr::read(&me.buf); |
1171 | let len = me.len(); |
1172 | buf.into_box(len).assume_init() |
1173 | } |
1174 | } |
1175 | |
1176 | /// Shortens the vector, keeping the first `len` elements and dropping |
1177 | /// the rest. |
1178 | /// |
1179 | /// If `len` is greater or equal to the vector's current length, this has |
1180 | /// no effect. |
1181 | /// |
1182 | /// The [`drain`] method can emulate `truncate`, but causes the excess |
1183 | /// elements to be returned instead of dropped. |
1184 | /// |
1185 | /// Note that this method has no effect on the allocated capacity |
1186 | /// of the vector. |
1187 | /// |
1188 | /// # Examples |
1189 | /// |
1190 | /// Truncating a five element vector to two elements: |
1191 | /// |
1192 | /// ``` |
1193 | /// let mut vec = vec![1, 2, 3, 4, 5]; |
1194 | /// vec.truncate(2); |
1195 | /// assert_eq!(vec, [1, 2]); |
1196 | /// ``` |
1197 | /// |
1198 | /// No truncation occurs when `len` is greater than the vector's current |
1199 | /// length: |
1200 | /// |
1201 | /// ``` |
1202 | /// let mut vec = vec![1, 2, 3]; |
1203 | /// vec.truncate(8); |
1204 | /// assert_eq!(vec, [1, 2, 3]); |
1205 | /// ``` |
1206 | /// |
1207 | /// Truncating when `len == 0` is equivalent to calling the [`clear`] |
1208 | /// method. |
1209 | /// |
1210 | /// ``` |
1211 | /// let mut vec = vec![1, 2, 3]; |
1212 | /// vec.truncate(0); |
1213 | /// assert_eq!(vec, []); |
1214 | /// ``` |
1215 | /// |
1216 | /// [`clear`]: Vec::clear |
1217 | /// [`drain`]: Vec::drain |
1218 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1219 | pub fn truncate(&mut self, len: usize) { |
1220 | // This is safe because: |
1221 | // |
1222 | // * the slice passed to `drop_in_place` is valid; the `len > self.len` |
1223 | // case avoids creating an invalid slice, and |
1224 | // * the `len` of the vector is shrunk before calling `drop_in_place`, |
1225 | // such that no value will be dropped twice in case `drop_in_place` |
1226 | // were to panic once (if it panics twice, the program aborts). |
1227 | unsafe { |
1228 | // Note: It's intentional that this is `>` and not `>=`. |
1229 | // Changing it to `>=` has negative performance |
1230 | // implications in some cases. See #78884 for more. |
1231 | if len > self.len { |
1232 | return; |
1233 | } |
1234 | let remaining_len = self.len - len; |
1235 | let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len); |
1236 | self.len = len; |
1237 | ptr::drop_in_place(s); |
1238 | } |
1239 | } |
1240 | |
1241 | /// Extracts a slice containing the entire vector. |
1242 | /// |
1243 | /// Equivalent to `&s[..]`. |
1244 | /// |
1245 | /// # Examples |
1246 | /// |
1247 | /// ``` |
1248 | /// use std::io::{self, Write}; |
1249 | /// let buffer = vec![1, 2, 3, 5, 8]; |
1250 | /// io::sink().write(buffer.as_slice()).unwrap(); |
1251 | /// ``` |
1252 | #[inline ] |
1253 | #[stable (feature = "vec_as_slice" , since = "1.7.0" )] |
1254 | pub fn as_slice(&self) -> &[T] { |
1255 | self |
1256 | } |
1257 | |
1258 | /// Extracts a mutable slice of the entire vector. |
1259 | /// |
1260 | /// Equivalent to `&mut s[..]`. |
1261 | /// |
1262 | /// # Examples |
1263 | /// |
1264 | /// ``` |
1265 | /// use std::io::{self, Read}; |
1266 | /// let mut buffer = vec![0; 3]; |
1267 | /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); |
1268 | /// ``` |
1269 | #[inline ] |
1270 | #[stable (feature = "vec_as_slice" , since = "1.7.0" )] |
1271 | pub fn as_mut_slice(&mut self) -> &mut [T] { |
1272 | self |
1273 | } |
1274 | |
1275 | /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer |
1276 | /// valid for zero sized reads if the vector didn't allocate. |
1277 | /// |
1278 | /// The caller must ensure that the vector outlives the pointer this |
1279 | /// function returns, or else it will end up pointing to garbage. |
1280 | /// Modifying the vector may cause its buffer to be reallocated, |
1281 | /// which would also make any pointers to it invalid. |
1282 | /// |
1283 | /// The caller must also ensure that the memory the pointer (non-transitively) points to |
1284 | /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer |
1285 | /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`]. |
1286 | /// |
1287 | /// This method guarantees that for the purpose of the aliasing model, this method |
1288 | /// does not materialize a reference to the underlying slice, and thus the returned pointer |
1289 | /// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`]. |
1290 | /// Note that calling other methods that materialize mutable references to the slice, |
1291 | /// or mutable references to specific elements you are planning on accessing through this pointer, |
1292 | /// as well as writing to those elements, may still invalidate this pointer. |
1293 | /// See the second example below for how this guarantee can be used. |
1294 | /// |
1295 | /// |
1296 | /// # Examples |
1297 | /// |
1298 | /// ``` |
1299 | /// let x = vec![1, 2, 4]; |
1300 | /// let x_ptr = x.as_ptr(); |
1301 | /// |
1302 | /// unsafe { |
1303 | /// for i in 0..x.len() { |
1304 | /// assert_eq!(*x_ptr.add(i), 1 << i); |
1305 | /// } |
1306 | /// } |
1307 | /// ``` |
1308 | /// |
1309 | /// Due to the aliasing guarantee, the following code is legal: |
1310 | /// |
1311 | /// ```rust |
1312 | /// unsafe { |
1313 | /// let mut v = vec![0, 1, 2]; |
1314 | /// let ptr1 = v.as_ptr(); |
1315 | /// let _ = ptr1.read(); |
1316 | /// let ptr2 = v.as_mut_ptr().offset(2); |
1317 | /// ptr2.write(2); |
1318 | /// // Notably, the write to `ptr2` did *not* invalidate `ptr1` |
1319 | /// // because it mutated a different element: |
1320 | /// let _ = ptr1.read(); |
1321 | /// } |
1322 | /// ``` |
1323 | /// |
1324 | /// [`as_mut_ptr`]: Vec::as_mut_ptr |
1325 | /// [`as_ptr`]: Vec::as_ptr |
1326 | #[stable (feature = "vec_as_ptr" , since = "1.37.0" )] |
1327 | #[rustc_never_returns_null_ptr ] |
1328 | #[inline ] |
1329 | pub fn as_ptr(&self) -> *const T { |
1330 | // We shadow the slice method of the same name to avoid going through |
1331 | // `deref`, which creates an intermediate reference. |
1332 | self.buf.ptr() |
1333 | } |
1334 | |
1335 | /// Returns an unsafe mutable pointer to the vector's buffer, or a dangling |
1336 | /// raw pointer valid for zero sized reads if the vector didn't allocate. |
1337 | /// |
1338 | /// The caller must ensure that the vector outlives the pointer this |
1339 | /// function returns, or else it will end up pointing to garbage. |
1340 | /// Modifying the vector may cause its buffer to be reallocated, |
1341 | /// which would also make any pointers to it invalid. |
1342 | /// |
1343 | /// This method guarantees that for the purpose of the aliasing model, this method |
1344 | /// does not materialize a reference to the underlying slice, and thus the returned pointer |
1345 | /// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`]. |
1346 | /// Note that calling other methods that materialize references to the slice, |
1347 | /// or references to specific elements you are planning on accessing through this pointer, |
1348 | /// may still invalidate this pointer. |
1349 | /// See the second example below for how this guarantee can be used. |
1350 | /// |
1351 | /// |
1352 | /// # Examples |
1353 | /// |
1354 | /// ``` |
1355 | /// // Allocate vector big enough for 4 elements. |
1356 | /// let size = 4; |
1357 | /// let mut x: Vec<i32> = Vec::with_capacity(size); |
1358 | /// let x_ptr = x.as_mut_ptr(); |
1359 | /// |
1360 | /// // Initialize elements via raw pointer writes, then set length. |
1361 | /// unsafe { |
1362 | /// for i in 0..size { |
1363 | /// *x_ptr.add(i) = i as i32; |
1364 | /// } |
1365 | /// x.set_len(size); |
1366 | /// } |
1367 | /// assert_eq!(&*x, &[0, 1, 2, 3]); |
1368 | /// ``` |
1369 | /// |
1370 | /// Due to the aliasing guarantee, the following code is legal: |
1371 | /// |
1372 | /// ```rust |
1373 | /// unsafe { |
1374 | /// let mut v = vec![0]; |
1375 | /// let ptr1 = v.as_mut_ptr(); |
1376 | /// ptr1.write(1); |
1377 | /// let ptr2 = v.as_mut_ptr(); |
1378 | /// ptr2.write(2); |
1379 | /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`: |
1380 | /// ptr1.write(3); |
1381 | /// } |
1382 | /// ``` |
1383 | /// |
1384 | /// [`as_mut_ptr`]: Vec::as_mut_ptr |
1385 | /// [`as_ptr`]: Vec::as_ptr |
1386 | #[stable (feature = "vec_as_ptr" , since = "1.37.0" )] |
1387 | #[rustc_never_returns_null_ptr ] |
1388 | #[inline ] |
1389 | pub fn as_mut_ptr(&mut self) -> *mut T { |
1390 | // We shadow the slice method of the same name to avoid going through |
1391 | // `deref_mut`, which creates an intermediate reference. |
1392 | self.buf.ptr() |
1393 | } |
1394 | |
1395 | /// Returns a reference to the underlying allocator. |
1396 | #[unstable (feature = "allocator_api" , issue = "32838" )] |
1397 | #[inline ] |
1398 | pub fn allocator(&self) -> &A { |
1399 | self.buf.allocator() |
1400 | } |
1401 | |
1402 | /// Forces the length of the vector to `new_len`. |
1403 | /// |
1404 | /// This is a low-level operation that maintains none of the normal |
1405 | /// invariants of the type. Normally changing the length of a vector |
1406 | /// is done using one of the safe operations instead, such as |
1407 | /// [`truncate`], [`resize`], [`extend`], or [`clear`]. |
1408 | /// |
1409 | /// [`truncate`]: Vec::truncate |
1410 | /// [`resize`]: Vec::resize |
1411 | /// [`extend`]: Extend::extend |
1412 | /// [`clear`]: Vec::clear |
1413 | /// |
1414 | /// # Safety |
1415 | /// |
1416 | /// - `new_len` must be less than or equal to [`capacity()`]. |
1417 | /// - The elements at `old_len..new_len` must be initialized. |
1418 | /// |
1419 | /// [`capacity()`]: Vec::capacity |
1420 | /// |
1421 | /// # Examples |
1422 | /// |
1423 | /// This method can be useful for situations in which the vector |
1424 | /// is serving as a buffer for other code, particularly over FFI: |
1425 | /// |
1426 | /// ```no_run |
1427 | /// # #![allow (dead_code)] |
1428 | /// # // This is just a minimal skeleton for the doc example; |
1429 | /// # // don't use this as a starting point for a real library. |
1430 | /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void } |
1431 | /// # const Z_OK: i32 = 0; |
1432 | /// # extern "C" { |
1433 | /// # fn deflateGetDictionary( |
1434 | /// # strm: *mut std::ffi::c_void, |
1435 | /// # dictionary: *mut u8, |
1436 | /// # dictLength: *mut usize, |
1437 | /// # ) -> i32; |
1438 | /// # } |
1439 | /// # impl StreamWrapper { |
1440 | /// pub fn get_dictionary(&self) -> Option<Vec<u8>> { |
1441 | /// // Per the FFI method's docs, "32768 bytes is always enough". |
1442 | /// let mut dict = Vec::with_capacity(32_768); |
1443 | /// let mut dict_length = 0; |
1444 | /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that: |
1445 | /// // 1. `dict_length` elements were initialized. |
1446 | /// // 2. `dict_length` <= the capacity (32_768) |
1447 | /// // which makes `set_len` safe to call. |
1448 | /// unsafe { |
1449 | /// // Make the FFI call... |
1450 | /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length); |
1451 | /// if r == Z_OK { |
1452 | /// // ...and update the length to what was initialized. |
1453 | /// dict.set_len(dict_length); |
1454 | /// Some(dict) |
1455 | /// } else { |
1456 | /// None |
1457 | /// } |
1458 | /// } |
1459 | /// } |
1460 | /// # } |
1461 | /// ``` |
1462 | /// |
1463 | /// While the following example is sound, there is a memory leak since |
1464 | /// the inner vectors were not freed prior to the `set_len` call: |
1465 | /// |
1466 | /// ``` |
1467 | /// let mut vec = vec![vec![1, 0, 0], |
1468 | /// vec![0, 1, 0], |
1469 | /// vec![0, 0, 1]]; |
1470 | /// // SAFETY: |
1471 | /// // 1. `old_len..0` is empty so no elements need to be initialized. |
1472 | /// // 2. `0 <= capacity` always holds whatever `capacity` is. |
1473 | /// unsafe { |
1474 | /// vec.set_len(0); |
1475 | /// } |
1476 | /// ``` |
1477 | /// |
1478 | /// Normally, here, one would use [`clear`] instead to correctly drop |
1479 | /// the contents and thus not leak memory. |
1480 | #[inline ] |
1481 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1482 | pub unsafe fn set_len(&mut self, new_len: usize) { |
1483 | debug_assert!(new_len <= self.capacity()); |
1484 | |
1485 | self.len = new_len; |
1486 | } |
1487 | |
1488 | /// Removes an element from the vector and returns it. |
1489 | /// |
1490 | /// The removed element is replaced by the last element of the vector. |
1491 | /// |
1492 | /// This does not preserve ordering of the remaining elements, but is *O*(1). |
1493 | /// If you need to preserve the element order, use [`remove`] instead. |
1494 | /// |
1495 | /// [`remove`]: Vec::remove |
1496 | /// |
1497 | /// # Panics |
1498 | /// |
1499 | /// Panics if `index` is out of bounds. |
1500 | /// |
1501 | /// # Examples |
1502 | /// |
1503 | /// ``` |
1504 | /// let mut v = vec!["foo" , "bar" , "baz" , "qux" ]; |
1505 | /// |
1506 | /// assert_eq!(v.swap_remove(1), "bar" ); |
1507 | /// assert_eq!(v, ["foo" , "qux" , "baz" ]); |
1508 | /// |
1509 | /// assert_eq!(v.swap_remove(0), "foo" ); |
1510 | /// assert_eq!(v, ["baz" , "qux" ]); |
1511 | /// ``` |
1512 | #[inline ] |
1513 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1514 | pub fn swap_remove(&mut self, index: usize) -> T { |
1515 | #[cold ] |
1516 | #[cfg_attr (not(feature = "panic_immediate_abort" ), inline(never))] |
1517 | #[track_caller ] |
1518 | fn assert_failed(index: usize, len: usize) -> ! { |
1519 | panic!("swap_remove index (is {index}) should be < len (is {len})" ); |
1520 | } |
1521 | |
1522 | let len = self.len(); |
1523 | if index >= len { |
1524 | assert_failed(index, len); |
1525 | } |
1526 | unsafe { |
1527 | // We replace self[index] with the last element. Note that if the |
1528 | // bounds check above succeeds there must be a last element (which |
1529 | // can be self[index] itself). |
1530 | let value = ptr::read(self.as_ptr().add(index)); |
1531 | let base_ptr = self.as_mut_ptr(); |
1532 | ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); |
1533 | self.set_len(len - 1); |
1534 | value |
1535 | } |
1536 | } |
1537 | |
1538 | /// Inserts an element at position `index` within the vector, shifting all |
1539 | /// elements after it to the right. |
1540 | /// |
1541 | /// # Panics |
1542 | /// |
1543 | /// Panics if `index > len`. |
1544 | /// |
1545 | /// # Examples |
1546 | /// |
1547 | /// ``` |
1548 | /// let mut vec = vec![1, 2, 3]; |
1549 | /// vec.insert(1, 4); |
1550 | /// assert_eq!(vec, [1, 4, 2, 3]); |
1551 | /// vec.insert(4, 5); |
1552 | /// assert_eq!(vec, [1, 4, 2, 3, 5]); |
1553 | /// ``` |
1554 | /// |
1555 | /// # Time complexity |
1556 | /// |
1557 | /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be |
1558 | /// shifted to the right. In the worst case, all elements are shifted when |
1559 | /// the insertion index is 0. |
1560 | #[cfg (not(no_global_oom_handling))] |
1561 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1562 | pub fn insert(&mut self, index: usize, element: T) { |
1563 | #[cold ] |
1564 | #[cfg_attr (not(feature = "panic_immediate_abort" ), inline(never))] |
1565 | #[track_caller ] |
1566 | fn assert_failed(index: usize, len: usize) -> ! { |
1567 | panic!("insertion index (is {index}) should be <= len (is {len})" ); |
1568 | } |
1569 | |
1570 | let len = self.len(); |
1571 | if index > len { |
1572 | assert_failed(index, len); |
1573 | } |
1574 | |
1575 | // space for the new element |
1576 | if len == self.buf.capacity() { |
1577 | self.buf.grow_one(); |
1578 | } |
1579 | |
1580 | unsafe { |
1581 | // infallible |
1582 | // The spot to put the new value |
1583 | { |
1584 | let p = self.as_mut_ptr().add(index); |
1585 | if index < len { |
1586 | // Shift everything over to make space. (Duplicating the |
1587 | // `index`th element into two consecutive places.) |
1588 | ptr::copy(p, p.add(1), len - index); |
1589 | } |
1590 | // Write it in, overwriting the first copy of the `index`th |
1591 | // element. |
1592 | ptr::write(p, element); |
1593 | } |
1594 | self.set_len(len + 1); |
1595 | } |
1596 | } |
1597 | |
1598 | /// Removes and returns the element at position `index` within the vector, |
1599 | /// shifting all elements after it to the left. |
1600 | /// |
1601 | /// Note: Because this shifts over the remaining elements, it has a |
1602 | /// worst-case performance of *O*(*n*). If you don't need the order of elements |
1603 | /// to be preserved, use [`swap_remove`] instead. If you'd like to remove |
1604 | /// elements from the beginning of the `Vec`, consider using |
1605 | /// [`VecDeque::pop_front`] instead. |
1606 | /// |
1607 | /// [`swap_remove`]: Vec::swap_remove |
1608 | /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front |
1609 | /// |
1610 | /// # Panics |
1611 | /// |
1612 | /// Panics if `index` is out of bounds. |
1613 | /// |
1614 | /// # Examples |
1615 | /// |
1616 | /// ``` |
1617 | /// let mut v = vec![1, 2, 3]; |
1618 | /// assert_eq!(v.remove(1), 2); |
1619 | /// assert_eq!(v, [1, 3]); |
1620 | /// ``` |
1621 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1622 | #[track_caller ] |
1623 | #[rustc_confusables ("delete" , "take" )] |
1624 | pub fn remove(&mut self, index: usize) -> T { |
1625 | #[cold ] |
1626 | #[cfg_attr (not(feature = "panic_immediate_abort" ), inline(never))] |
1627 | #[track_caller ] |
1628 | fn assert_failed(index: usize, len: usize) -> ! { |
1629 | panic!("removal index (is {index}) should be < len (is {len})" ); |
1630 | } |
1631 | |
1632 | let len = self.len(); |
1633 | if index >= len { |
1634 | assert_failed(index, len); |
1635 | } |
1636 | unsafe { |
1637 | // infallible |
1638 | let ret; |
1639 | { |
1640 | // the place we are taking from. |
1641 | let ptr = self.as_mut_ptr().add(index); |
1642 | // copy it out, unsafely having a copy of the value on |
1643 | // the stack and in the vector at the same time. |
1644 | ret = ptr::read(ptr); |
1645 | |
1646 | // Shift everything down to fill in that spot. |
1647 | ptr::copy(ptr.add(1), ptr, len - index - 1); |
1648 | } |
1649 | self.set_len(len - 1); |
1650 | ret |
1651 | } |
1652 | } |
1653 | |
1654 | /// Retains only the elements specified by the predicate. |
1655 | /// |
1656 | /// In other words, remove all elements `e` for which `f(&e)` returns `false`. |
1657 | /// This method operates in place, visiting each element exactly once in the |
1658 | /// original order, and preserves the order of the retained elements. |
1659 | /// |
1660 | /// # Examples |
1661 | /// |
1662 | /// ``` |
1663 | /// let mut vec = vec![1, 2, 3, 4]; |
1664 | /// vec.retain(|&x| x % 2 == 0); |
1665 | /// assert_eq!(vec, [2, 4]); |
1666 | /// ``` |
1667 | /// |
1668 | /// Because the elements are visited exactly once in the original order, |
1669 | /// external state may be used to decide which elements to keep. |
1670 | /// |
1671 | /// ``` |
1672 | /// let mut vec = vec![1, 2, 3, 4, 5]; |
1673 | /// let keep = [false, true, true, false, true]; |
1674 | /// let mut iter = keep.iter(); |
1675 | /// vec.retain(|_| *iter.next().unwrap()); |
1676 | /// assert_eq!(vec, [2, 3, 5]); |
1677 | /// ``` |
1678 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1679 | pub fn retain<F>(&mut self, mut f: F) |
1680 | where |
1681 | F: FnMut(&T) -> bool, |
1682 | { |
1683 | self.retain_mut(|elem| f(elem)); |
1684 | } |
1685 | |
1686 | /// Retains only the elements specified by the predicate, passing a mutable reference to it. |
1687 | /// |
1688 | /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. |
1689 | /// This method operates in place, visiting each element exactly once in the |
1690 | /// original order, and preserves the order of the retained elements. |
1691 | /// |
1692 | /// # Examples |
1693 | /// |
1694 | /// ``` |
1695 | /// let mut vec = vec![1, 2, 3, 4]; |
1696 | /// vec.retain_mut(|x| if *x <= 3 { |
1697 | /// *x += 1; |
1698 | /// true |
1699 | /// } else { |
1700 | /// false |
1701 | /// }); |
1702 | /// assert_eq!(vec, [2, 3, 4]); |
1703 | /// ``` |
1704 | #[stable (feature = "vec_retain_mut" , since = "1.61.0" )] |
1705 | pub fn retain_mut<F>(&mut self, mut f: F) |
1706 | where |
1707 | F: FnMut(&mut T) -> bool, |
1708 | { |
1709 | let original_len = self.len(); |
1710 | // Avoid double drop if the drop guard is not executed, |
1711 | // since we may make some holes during the process. |
1712 | unsafe { self.set_len(0) }; |
1713 | |
1714 | // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked] |
1715 | // |<- processed len ->| ^- next to check |
1716 | // |<- deleted cnt ->| |
1717 | // |<- original_len ->| |
1718 | // Kept: Elements which predicate returns true on. |
1719 | // Hole: Moved or dropped element slot. |
1720 | // Unchecked: Unchecked valid elements. |
1721 | // |
1722 | // This drop guard will be invoked when predicate or `drop` of element panicked. |
1723 | // It shifts unchecked elements to cover holes and `set_len` to the correct length. |
1724 | // In cases when predicate and `drop` never panick, it will be optimized out. |
1725 | struct BackshiftOnDrop<'a, T, A: Allocator> { |
1726 | v: &'a mut Vec<T, A>, |
1727 | processed_len: usize, |
1728 | deleted_cnt: usize, |
1729 | original_len: usize, |
1730 | } |
1731 | |
1732 | impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> { |
1733 | fn drop(&mut self) { |
1734 | if self.deleted_cnt > 0 { |
1735 | // SAFETY: Trailing unchecked items must be valid since we never touch them. |
1736 | unsafe { |
1737 | ptr::copy( |
1738 | self.v.as_ptr().add(self.processed_len), |
1739 | self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), |
1740 | self.original_len - self.processed_len, |
1741 | ); |
1742 | } |
1743 | } |
1744 | // SAFETY: After filling holes, all items are in contiguous memory. |
1745 | unsafe { |
1746 | self.v.set_len(self.original_len - self.deleted_cnt); |
1747 | } |
1748 | } |
1749 | } |
1750 | |
1751 | let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; |
1752 | |
1753 | fn process_loop<F, T, A: Allocator, const DELETED: bool>( |
1754 | original_len: usize, |
1755 | f: &mut F, |
1756 | g: &mut BackshiftOnDrop<'_, T, A>, |
1757 | ) where |
1758 | F: FnMut(&mut T) -> bool, |
1759 | { |
1760 | while g.processed_len != original_len { |
1761 | // SAFETY: Unchecked element must be valid. |
1762 | let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; |
1763 | if !f(cur) { |
1764 | // Advance early to avoid double drop if `drop_in_place` panicked. |
1765 | g.processed_len += 1; |
1766 | g.deleted_cnt += 1; |
1767 | // SAFETY: We never touch this element again after dropped. |
1768 | unsafe { ptr::drop_in_place(cur) }; |
1769 | // We already advanced the counter. |
1770 | if DELETED { |
1771 | continue; |
1772 | } else { |
1773 | break; |
1774 | } |
1775 | } |
1776 | if DELETED { |
1777 | // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element. |
1778 | // We use copy for move, and never touch this element again. |
1779 | unsafe { |
1780 | let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); |
1781 | ptr::copy_nonoverlapping(cur, hole_slot, 1); |
1782 | } |
1783 | } |
1784 | g.processed_len += 1; |
1785 | } |
1786 | } |
1787 | |
1788 | // Stage 1: Nothing was deleted. |
1789 | process_loop::<F, T, A, false>(original_len, &mut f, &mut g); |
1790 | |
1791 | // Stage 2: Some elements were deleted. |
1792 | process_loop::<F, T, A, true>(original_len, &mut f, &mut g); |
1793 | |
1794 | // All item are processed. This can be optimized to `set_len` by LLVM. |
1795 | drop(g); |
1796 | } |
1797 | |
1798 | /// Removes all but the first of consecutive elements in the vector that resolve to the same |
1799 | /// key. |
1800 | /// |
1801 | /// If the vector is sorted, this removes all duplicates. |
1802 | /// |
1803 | /// # Examples |
1804 | /// |
1805 | /// ``` |
1806 | /// let mut vec = vec![10, 20, 21, 30, 20]; |
1807 | /// |
1808 | /// vec.dedup_by_key(|i| *i / 10); |
1809 | /// |
1810 | /// assert_eq!(vec, [10, 20, 30, 20]); |
1811 | /// ``` |
1812 | #[stable (feature = "dedup_by" , since = "1.16.0" )] |
1813 | #[inline ] |
1814 | pub fn dedup_by_key<F, K>(&mut self, mut key: F) |
1815 | where |
1816 | F: FnMut(&mut T) -> K, |
1817 | K: PartialEq, |
1818 | { |
1819 | self.dedup_by(|a, b| key(a) == key(b)) |
1820 | } |
1821 | |
1822 | /// Removes all but the first of consecutive elements in the vector satisfying a given equality |
1823 | /// relation. |
1824 | /// |
1825 | /// The `same_bucket` function is passed references to two elements from the vector and |
1826 | /// must determine if the elements compare equal. The elements are passed in opposite order |
1827 | /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed. |
1828 | /// |
1829 | /// If the vector is sorted, this removes all duplicates. |
1830 | /// |
1831 | /// # Examples |
1832 | /// |
1833 | /// ``` |
1834 | /// let mut vec = vec!["foo" , "bar" , "Bar" , "baz" , "bar" ]; |
1835 | /// |
1836 | /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); |
1837 | /// |
1838 | /// assert_eq!(vec, ["foo" , "bar" , "baz" , "bar" ]); |
1839 | /// ``` |
1840 | #[stable (feature = "dedup_by" , since = "1.16.0" )] |
1841 | pub fn dedup_by<F>(&mut self, mut same_bucket: F) |
1842 | where |
1843 | F: FnMut(&mut T, &mut T) -> bool, |
1844 | { |
1845 | let len = self.len(); |
1846 | if len <= 1 { |
1847 | return; |
1848 | } |
1849 | |
1850 | // Check if we ever want to remove anything. |
1851 | // This allows to use copy_non_overlapping in next cycle. |
1852 | // And avoids any memory writes if we don't need to remove anything. |
1853 | let mut first_duplicate_idx: usize = 1; |
1854 | let start = self.as_mut_ptr(); |
1855 | while first_duplicate_idx != len { |
1856 | let found_duplicate = unsafe { |
1857 | // SAFETY: first_duplicate always in range [1..len) |
1858 | // Note that we start iteration from 1 so we never overflow. |
1859 | let prev = start.add(first_duplicate_idx.wrapping_sub(1)); |
1860 | let current = start.add(first_duplicate_idx); |
1861 | // We explicitly say in docs that references are reversed. |
1862 | same_bucket(&mut *current, &mut *prev) |
1863 | }; |
1864 | if found_duplicate { |
1865 | break; |
1866 | } |
1867 | first_duplicate_idx += 1; |
1868 | } |
1869 | // Don't need to remove anything. |
1870 | // We cannot get bigger than len. |
1871 | if first_duplicate_idx == len { |
1872 | return; |
1873 | } |
1874 | |
1875 | /* INVARIANT: vec.len() > read > write > write-1 >= 0 */ |
1876 | struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { |
1877 | /* Offset of the element we want to check if it is duplicate */ |
1878 | read: usize, |
1879 | |
1880 | /* Offset of the place where we want to place the non-duplicate |
1881 | * when we find it. */ |
1882 | write: usize, |
1883 | |
1884 | /* The Vec that would need correction if `same_bucket` panicked */ |
1885 | vec: &'a mut Vec<T, A>, |
1886 | } |
1887 | |
1888 | impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> { |
1889 | fn drop(&mut self) { |
1890 | /* This code gets executed when `same_bucket` panics */ |
1891 | |
1892 | /* SAFETY: invariant guarantees that `read - write` |
1893 | * and `len - read` never overflow and that the copy is always |
1894 | * in-bounds. */ |
1895 | unsafe { |
1896 | let ptr = self.vec.as_mut_ptr(); |
1897 | let len = self.vec.len(); |
1898 | |
1899 | /* How many items were left when `same_bucket` panicked. |
1900 | * Basically vec[read..].len() */ |
1901 | let items_left = len.wrapping_sub(self.read); |
1902 | |
1903 | /* Pointer to first item in vec[write..write+items_left] slice */ |
1904 | let dropped_ptr = ptr.add(self.write); |
1905 | /* Pointer to first item in vec[read..] slice */ |
1906 | let valid_ptr = ptr.add(self.read); |
1907 | |
1908 | /* Copy `vec[read..]` to `vec[write..write+items_left]`. |
1909 | * The slices can overlap, so `copy_nonoverlapping` cannot be used */ |
1910 | ptr::copy(valid_ptr, dropped_ptr, items_left); |
1911 | |
1912 | /* How many items have been already dropped |
1913 | * Basically vec[read..write].len() */ |
1914 | let dropped = self.read.wrapping_sub(self.write); |
1915 | |
1916 | self.vec.set_len(len - dropped); |
1917 | } |
1918 | } |
1919 | } |
1920 | |
1921 | /* Drop items while going through Vec, it should be more efficient than |
1922 | * doing slice partition_dedup + truncate */ |
1923 | |
1924 | // Construct gap first and then drop item to avoid memory corruption if `T::drop` panics. |
1925 | let mut gap = |
1926 | FillGapOnDrop { read: first_duplicate_idx + 1, write: first_duplicate_idx, vec: self }; |
1927 | unsafe { |
1928 | // SAFETY: we checked that first_duplicate_idx in bounds before. |
1929 | // If drop panics, `gap` would remove this item without drop. |
1930 | ptr::drop_in_place(start.add(first_duplicate_idx)); |
1931 | } |
1932 | |
1933 | /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr |
1934 | * are always in-bounds and read_ptr never aliases prev_ptr */ |
1935 | unsafe { |
1936 | while gap.read < len { |
1937 | let read_ptr = start.add(gap.read); |
1938 | let prev_ptr = start.add(gap.write.wrapping_sub(1)); |
1939 | |
1940 | // We explicitly say in docs that references are reversed. |
1941 | let found_duplicate = same_bucket(&mut *read_ptr, &mut *prev_ptr); |
1942 | if found_duplicate { |
1943 | // Increase `gap.read` now since the drop may panic. |
1944 | gap.read += 1; |
1945 | /* We have found duplicate, drop it in-place */ |
1946 | ptr::drop_in_place(read_ptr); |
1947 | } else { |
1948 | let write_ptr = start.add(gap.write); |
1949 | |
1950 | /* read_ptr cannot be equal to write_ptr because at this point |
1951 | * we guaranteed to skip at least one element (before loop starts). |
1952 | */ |
1953 | ptr::copy_nonoverlapping(read_ptr, write_ptr, 1); |
1954 | |
1955 | /* We have filled that place, so go further */ |
1956 | gap.write += 1; |
1957 | gap.read += 1; |
1958 | } |
1959 | } |
1960 | |
1961 | /* Technically we could let `gap` clean up with its Drop, but |
1962 | * when `same_bucket` is guaranteed to not panic, this bloats a little |
1963 | * the codegen, so we just do it manually */ |
1964 | gap.vec.set_len(gap.write); |
1965 | mem::forget(gap); |
1966 | } |
1967 | } |
1968 | |
1969 | /// Appends an element to the back of a collection. |
1970 | /// |
1971 | /// # Panics |
1972 | /// |
1973 | /// Panics if the new capacity exceeds `isize::MAX` _bytes_. |
1974 | /// |
1975 | /// # Examples |
1976 | /// |
1977 | /// ``` |
1978 | /// let mut vec = vec![1, 2]; |
1979 | /// vec.push(3); |
1980 | /// assert_eq!(vec, [1, 2, 3]); |
1981 | /// ``` |
1982 | /// |
1983 | /// # Time complexity |
1984 | /// |
1985 | /// Takes amortized *O*(1) time. If the vector's length would exceed its |
1986 | /// capacity after the push, *O*(*capacity*) time is taken to copy the |
1987 | /// vector's elements to a larger allocation. This expensive operation is |
1988 | /// offset by the *capacity* *O*(1) insertions it allows. |
1989 | #[cfg (not(no_global_oom_handling))] |
1990 | #[inline ] |
1991 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1992 | #[rustc_confusables ("push_back" , "put" , "append" )] |
1993 | pub fn push(&mut self, value: T) { |
1994 | // Inform codegen that the length does not change across grow_one(). |
1995 | let len = self.len; |
1996 | // This will panic or abort if we would allocate > isize::MAX bytes |
1997 | // or if the length increment would overflow for zero-sized types. |
1998 | if len == self.buf.capacity() { |
1999 | self.buf.grow_one(); |
2000 | } |
2001 | unsafe { |
2002 | let end = self.as_mut_ptr().add(len); |
2003 | ptr::write(end, value); |
2004 | self.len = len + 1; |
2005 | } |
2006 | } |
2007 | |
2008 | /// Appends an element if there is sufficient spare capacity, otherwise an error is returned |
2009 | /// with the element. |
2010 | /// |
2011 | /// Unlike [`push`] this method will not reallocate when there's insufficient capacity. |
2012 | /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity. |
2013 | /// |
2014 | /// [`push`]: Vec::push |
2015 | /// [`reserve`]: Vec::reserve |
2016 | /// [`try_reserve`]: Vec::try_reserve |
2017 | /// |
2018 | /// # Examples |
2019 | /// |
2020 | /// A manual, panic-free alternative to [`FromIterator`]: |
2021 | /// |
2022 | /// ``` |
2023 | /// #![feature(vec_push_within_capacity)] |
2024 | /// |
2025 | /// use std::collections::TryReserveError; |
2026 | /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> { |
2027 | /// let mut vec = Vec::new(); |
2028 | /// for value in iter { |
2029 | /// if let Err(value) = vec.push_within_capacity(value) { |
2030 | /// vec.try_reserve(1)?; |
2031 | /// // this cannot fail, the previous line either returned or added at least 1 free slot |
2032 | /// let _ = vec.push_within_capacity(value); |
2033 | /// } |
2034 | /// } |
2035 | /// Ok(vec) |
2036 | /// } |
2037 | /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100))); |
2038 | /// ``` |
2039 | /// |
2040 | /// # Time complexity |
2041 | /// |
2042 | /// Takes *O*(1) time. |
2043 | #[inline ] |
2044 | #[unstable (feature = "vec_push_within_capacity" , issue = "100486" )] |
2045 | pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> { |
2046 | if self.len == self.buf.capacity() { |
2047 | return Err(value); |
2048 | } |
2049 | unsafe { |
2050 | let end = self.as_mut_ptr().add(self.len); |
2051 | ptr::write(end, value); |
2052 | self.len += 1; |
2053 | } |
2054 | Ok(()) |
2055 | } |
2056 | |
2057 | /// Removes the last element from a vector and returns it, or [`None`] if it |
2058 | /// is empty. |
2059 | /// |
2060 | /// If you'd like to pop the first element, consider using |
2061 | /// [`VecDeque::pop_front`] instead. |
2062 | /// |
2063 | /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front |
2064 | /// |
2065 | /// # Examples |
2066 | /// |
2067 | /// ``` |
2068 | /// let mut vec = vec![1, 2, 3]; |
2069 | /// assert_eq!(vec.pop(), Some(3)); |
2070 | /// assert_eq!(vec, [1, 2]); |
2071 | /// ``` |
2072 | /// |
2073 | /// # Time complexity |
2074 | /// |
2075 | /// Takes *O*(1) time. |
2076 | #[inline ] |
2077 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2078 | pub fn pop(&mut self) -> Option<T> { |
2079 | if self.len == 0 { |
2080 | None |
2081 | } else { |
2082 | unsafe { |
2083 | self.len -= 1; |
2084 | core::hint::assert_unchecked(self.len < self.capacity()); |
2085 | Some(ptr::read(self.as_ptr().add(self.len()))) |
2086 | } |
2087 | } |
2088 | } |
2089 | |
2090 | /// Removes and returns the last element in a vector if the predicate |
2091 | /// returns `true`, or [`None`] if the predicate returns false or the vector |
2092 | /// is empty. |
2093 | /// |
2094 | /// # Examples |
2095 | /// |
2096 | /// ``` |
2097 | /// #![feature(vec_pop_if)] |
2098 | /// |
2099 | /// let mut vec = vec![1, 2, 3, 4]; |
2100 | /// let pred = |x: &mut i32| *x % 2 == 0; |
2101 | /// |
2102 | /// assert_eq!(vec.pop_if(pred), Some(4)); |
2103 | /// assert_eq!(vec, [1, 2, 3]); |
2104 | /// assert_eq!(vec.pop_if(pred), None); |
2105 | /// ``` |
2106 | #[unstable (feature = "vec_pop_if" , issue = "122741" )] |
2107 | pub fn pop_if<F>(&mut self, f: F) -> Option<T> |
2108 | where |
2109 | F: FnOnce(&mut T) -> bool, |
2110 | { |
2111 | let last = self.last_mut()?; |
2112 | if f(last) { self.pop() } else { None } |
2113 | } |
2114 | |
2115 | /// Moves all the elements of `other` into `self`, leaving `other` empty. |
2116 | /// |
2117 | /// # Panics |
2118 | /// |
2119 | /// Panics if the new capacity exceeds `isize::MAX` _bytes_. |
2120 | /// |
2121 | /// # Examples |
2122 | /// |
2123 | /// ``` |
2124 | /// let mut vec = vec![1, 2, 3]; |
2125 | /// let mut vec2 = vec![4, 5, 6]; |
2126 | /// vec.append(&mut vec2); |
2127 | /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); |
2128 | /// assert_eq!(vec2, []); |
2129 | /// ``` |
2130 | #[cfg (not(no_global_oom_handling))] |
2131 | #[inline ] |
2132 | #[stable (feature = "append" , since = "1.4.0" )] |
2133 | pub fn append(&mut self, other: &mut Self) { |
2134 | unsafe { |
2135 | self.append_elements(other.as_slice() as _); |
2136 | other.set_len(0); |
2137 | } |
2138 | } |
2139 | |
2140 | /// Appends elements to `self` from other buffer. |
2141 | #[cfg (not(no_global_oom_handling))] |
2142 | #[inline ] |
2143 | unsafe fn append_elements(&mut self, other: *const [T]) { |
2144 | let count = unsafe { (*other).len() }; |
2145 | self.reserve(count); |
2146 | let len = self.len(); |
2147 | unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; |
2148 | self.len += count; |
2149 | } |
2150 | |
2151 | /// Removes the specified range from the vector in bulk, returning all |
2152 | /// removed elements as an iterator. If the iterator is dropped before |
2153 | /// being fully consumed, it drops the remaining removed elements. |
2154 | /// |
2155 | /// The returned iterator keeps a mutable borrow on the vector to optimize |
2156 | /// its implementation. |
2157 | /// |
2158 | /// # Panics |
2159 | /// |
2160 | /// Panics if the starting point is greater than the end point or if |
2161 | /// the end point is greater than the length of the vector. |
2162 | /// |
2163 | /// # Leaking |
2164 | /// |
2165 | /// If the returned iterator goes out of scope without being dropped (due to |
2166 | /// [`mem::forget`], for example), the vector may have lost and leaked |
2167 | /// elements arbitrarily, including elements outside the range. |
2168 | /// |
2169 | /// # Examples |
2170 | /// |
2171 | /// ``` |
2172 | /// let mut v = vec![1, 2, 3]; |
2173 | /// let u: Vec<_> = v.drain(1..).collect(); |
2174 | /// assert_eq!(v, &[1]); |
2175 | /// assert_eq!(u, &[2, 3]); |
2176 | /// |
2177 | /// // A full range clears the vector, like `clear()` does |
2178 | /// v.drain(..); |
2179 | /// assert_eq!(v, &[]); |
2180 | /// ``` |
2181 | #[stable (feature = "drain" , since = "1.6.0" )] |
2182 | pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> |
2183 | where |
2184 | R: RangeBounds<usize>, |
2185 | { |
2186 | // Memory safety |
2187 | // |
2188 | // When the Drain is first created, it shortens the length of |
2189 | // the source vector to make sure no uninitialized or moved-from elements |
2190 | // are accessible at all if the Drain's destructor never gets to run. |
2191 | // |
2192 | // Drain will ptr::read out the values to remove. |
2193 | // When finished, remaining tail of the vec is copied back to cover |
2194 | // the hole, and the vector length is restored to the new length. |
2195 | // |
2196 | let len = self.len(); |
2197 | let Range { start, end } = slice::range(range, ..len); |
2198 | |
2199 | unsafe { |
2200 | // set self.vec length's to start, to be safe in case Drain is leaked |
2201 | self.set_len(start); |
2202 | let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start); |
2203 | Drain { |
2204 | tail_start: end, |
2205 | tail_len: len - end, |
2206 | iter: range_slice.iter(), |
2207 | vec: NonNull::from(self), |
2208 | } |
2209 | } |
2210 | } |
2211 | |
2212 | /// Clears the vector, removing all values. |
2213 | /// |
2214 | /// Note that this method has no effect on the allocated capacity |
2215 | /// of the vector. |
2216 | /// |
2217 | /// # Examples |
2218 | /// |
2219 | /// ``` |
2220 | /// let mut v = vec![1, 2, 3]; |
2221 | /// |
2222 | /// v.clear(); |
2223 | /// |
2224 | /// assert!(v.is_empty()); |
2225 | /// ``` |
2226 | #[inline ] |
2227 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2228 | pub fn clear(&mut self) { |
2229 | let elems: *mut [T] = self.as_mut_slice(); |
2230 | |
2231 | // SAFETY: |
2232 | // - `elems` comes directly from `as_mut_slice` and is therefore valid. |
2233 | // - Setting `self.len` before calling `drop_in_place` means that, |
2234 | // if an element's `Drop` impl panics, the vector's `Drop` impl will |
2235 | // do nothing (leaking the rest of the elements) instead of dropping |
2236 | // some twice. |
2237 | unsafe { |
2238 | self.len = 0; |
2239 | ptr::drop_in_place(elems); |
2240 | } |
2241 | } |
2242 | |
2243 | /// Returns the number of elements in the vector, also referred to |
2244 | /// as its 'length'. |
2245 | /// |
2246 | /// # Examples |
2247 | /// |
2248 | /// ``` |
2249 | /// let a = vec![1, 2, 3]; |
2250 | /// assert_eq!(a.len(), 3); |
2251 | /// ``` |
2252 | #[inline ] |
2253 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2254 | #[rustc_confusables ("length" , "size" )] |
2255 | pub fn len(&self) -> usize { |
2256 | self.len |
2257 | } |
2258 | |
2259 | /// Returns `true` if the vector contains no elements. |
2260 | /// |
2261 | /// # Examples |
2262 | /// |
2263 | /// ``` |
2264 | /// let mut v = Vec::new(); |
2265 | /// assert!(v.is_empty()); |
2266 | /// |
2267 | /// v.push(1); |
2268 | /// assert!(!v.is_empty()); |
2269 | /// ``` |
2270 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2271 | pub fn is_empty(&self) -> bool { |
2272 | self.len() == 0 |
2273 | } |
2274 | |
2275 | /// Splits the collection into two at the given index. |
2276 | /// |
2277 | /// Returns a newly allocated vector containing the elements in the range |
2278 | /// `[at, len)`. After the call, the original vector will be left containing |
2279 | /// the elements `[0, at)` with its previous capacity unchanged. |
2280 | /// |
2281 | /// - If you want to take ownership of the entire contents and capacity of |
2282 | /// the vector, see [`mem::take`] or [`mem::replace`]. |
2283 | /// - If you don't need the returned vector at all, see [`Vec::truncate`]. |
2284 | /// - If you want to take ownership of an arbitrary subslice, or you don't |
2285 | /// necessarily want to store the removed items in a vector, see [`Vec::drain`]. |
2286 | /// |
2287 | /// # Panics |
2288 | /// |
2289 | /// Panics if `at > len`. |
2290 | /// |
2291 | /// # Examples |
2292 | /// |
2293 | /// ``` |
2294 | /// let mut vec = vec![1, 2, 3]; |
2295 | /// let vec2 = vec.split_off(1); |
2296 | /// assert_eq!(vec, [1]); |
2297 | /// assert_eq!(vec2, [2, 3]); |
2298 | /// ``` |
2299 | #[cfg (not(no_global_oom_handling))] |
2300 | #[inline ] |
2301 | #[must_use = "use `.truncate()` if you don't need the other half" ] |
2302 | #[stable (feature = "split_off" , since = "1.4.0" )] |
2303 | pub fn split_off(&mut self, at: usize) -> Self |
2304 | where |
2305 | A: Clone, |
2306 | { |
2307 | #[cold ] |
2308 | #[cfg_attr (not(feature = "panic_immediate_abort" ), inline(never))] |
2309 | #[track_caller ] |
2310 | fn assert_failed(at: usize, len: usize) -> ! { |
2311 | panic!("`at` split index (is {at}) should be <= len (is {len})" ); |
2312 | } |
2313 | |
2314 | if at > self.len() { |
2315 | assert_failed(at, self.len()); |
2316 | } |
2317 | |
2318 | let other_len = self.len - at; |
2319 | let mut other = Vec::with_capacity_in(other_len, self.allocator().clone()); |
2320 | |
2321 | // Unsafely `set_len` and copy items to `other`. |
2322 | unsafe { |
2323 | self.set_len(at); |
2324 | other.set_len(other_len); |
2325 | |
2326 | ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len()); |
2327 | } |
2328 | other |
2329 | } |
2330 | |
2331 | /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. |
2332 | /// |
2333 | /// If `new_len` is greater than `len`, the `Vec` is extended by the |
2334 | /// difference, with each additional slot filled with the result of |
2335 | /// calling the closure `f`. The return values from `f` will end up |
2336 | /// in the `Vec` in the order they have been generated. |
2337 | /// |
2338 | /// If `new_len` is less than `len`, the `Vec` is simply truncated. |
2339 | /// |
2340 | /// This method uses a closure to create new values on every push. If |
2341 | /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you |
2342 | /// want to use the [`Default`] trait to generate values, you can |
2343 | /// pass [`Default::default`] as the second argument. |
2344 | /// |
2345 | /// # Examples |
2346 | /// |
2347 | /// ``` |
2348 | /// let mut vec = vec![1, 2, 3]; |
2349 | /// vec.resize_with(5, Default::default); |
2350 | /// assert_eq!(vec, [1, 2, 3, 0, 0]); |
2351 | /// |
2352 | /// let mut vec = vec![]; |
2353 | /// let mut p = 1; |
2354 | /// vec.resize_with(4, || { p *= 2; p }); |
2355 | /// assert_eq!(vec, [2, 4, 8, 16]); |
2356 | /// ``` |
2357 | #[cfg (not(no_global_oom_handling))] |
2358 | #[stable (feature = "vec_resize_with" , since = "1.33.0" )] |
2359 | pub fn resize_with<F>(&mut self, new_len: usize, f: F) |
2360 | where |
2361 | F: FnMut() -> T, |
2362 | { |
2363 | let len = self.len(); |
2364 | if new_len > len { |
2365 | self.extend_trusted(iter::repeat_with(f).take(new_len - len)); |
2366 | } else { |
2367 | self.truncate(new_len); |
2368 | } |
2369 | } |
2370 | |
2371 | /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, |
2372 | /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime |
2373 | /// `'a`. If the type has only static references, or none at all, then this |
2374 | /// may be chosen to be `'static`. |
2375 | /// |
2376 | /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, |
2377 | /// so the leaked allocation may include unused capacity that is not part |
2378 | /// of the returned slice. |
2379 | /// |
2380 | /// This function is mainly useful for data that lives for the remainder of |
2381 | /// the program's life. Dropping the returned reference will cause a memory |
2382 | /// leak. |
2383 | /// |
2384 | /// # Examples |
2385 | /// |
2386 | /// Simple usage: |
2387 | /// |
2388 | /// ``` |
2389 | /// let x = vec![1, 2, 3]; |
2390 | /// let static_ref: &'static mut [usize] = x.leak(); |
2391 | /// static_ref[0] += 1; |
2392 | /// assert_eq!(static_ref, &[2, 2, 3]); |
2393 | /// ``` |
2394 | #[stable (feature = "vec_leak" , since = "1.47.0" )] |
2395 | #[inline ] |
2396 | pub fn leak<'a>(self) -> &'a mut [T] |
2397 | where |
2398 | A: 'a, |
2399 | { |
2400 | let mut me = ManuallyDrop::new(self); |
2401 | unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) } |
2402 | } |
2403 | |
2404 | /// Returns the remaining spare capacity of the vector as a slice of |
2405 | /// `MaybeUninit<T>`. |
2406 | /// |
2407 | /// The returned slice can be used to fill the vector with data (e.g. by |
2408 | /// reading from a file) before marking the data as initialized using the |
2409 | /// [`set_len`] method. |
2410 | /// |
2411 | /// [`set_len`]: Vec::set_len |
2412 | /// |
2413 | /// # Examples |
2414 | /// |
2415 | /// ``` |
2416 | /// // Allocate vector big enough for 10 elements. |
2417 | /// let mut v = Vec::with_capacity(10); |
2418 | /// |
2419 | /// // Fill in the first 3 elements. |
2420 | /// let uninit = v.spare_capacity_mut(); |
2421 | /// uninit[0].write(0); |
2422 | /// uninit[1].write(1); |
2423 | /// uninit[2].write(2); |
2424 | /// |
2425 | /// // Mark the first 3 elements of the vector as being initialized. |
2426 | /// unsafe { |
2427 | /// v.set_len(3); |
2428 | /// } |
2429 | /// |
2430 | /// assert_eq!(&v, &[0, 1, 2]); |
2431 | /// ``` |
2432 | #[stable (feature = "vec_spare_capacity" , since = "1.60.0" )] |
2433 | #[inline ] |
2434 | pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { |
2435 | // Note: |
2436 | // This method is not implemented in terms of `split_at_spare_mut`, |
2437 | // to prevent invalidation of pointers to the buffer. |
2438 | unsafe { |
2439 | slice::from_raw_parts_mut( |
2440 | self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>, |
2441 | self.buf.capacity() - self.len, |
2442 | ) |
2443 | } |
2444 | } |
2445 | |
2446 | /// Returns vector content as a slice of `T`, along with the remaining spare |
2447 | /// capacity of the vector as a slice of `MaybeUninit<T>`. |
2448 | /// |
2449 | /// The returned spare capacity slice can be used to fill the vector with data |
2450 | /// (e.g. by reading from a file) before marking the data as initialized using |
2451 | /// the [`set_len`] method. |
2452 | /// |
2453 | /// [`set_len`]: Vec::set_len |
2454 | /// |
2455 | /// Note that this is a low-level API, which should be used with care for |
2456 | /// optimization purposes. If you need to append data to a `Vec` |
2457 | /// you can use [`push`], [`extend`], [`extend_from_slice`], |
2458 | /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or |
2459 | /// [`resize_with`], depending on your exact needs. |
2460 | /// |
2461 | /// [`push`]: Vec::push |
2462 | /// [`extend`]: Vec::extend |
2463 | /// [`extend_from_slice`]: Vec::extend_from_slice |
2464 | /// [`extend_from_within`]: Vec::extend_from_within |
2465 | /// [`insert`]: Vec::insert |
2466 | /// [`append`]: Vec::append |
2467 | /// [`resize`]: Vec::resize |
2468 | /// [`resize_with`]: Vec::resize_with |
2469 | /// |
2470 | /// # Examples |
2471 | /// |
2472 | /// ``` |
2473 | /// #![feature(vec_split_at_spare)] |
2474 | /// |
2475 | /// let mut v = vec![1, 1, 2]; |
2476 | /// |
2477 | /// // Reserve additional space big enough for 10 elements. |
2478 | /// v.reserve(10); |
2479 | /// |
2480 | /// let (init, uninit) = v.split_at_spare_mut(); |
2481 | /// let sum = init.iter().copied().sum::<u32>(); |
2482 | /// |
2483 | /// // Fill in the next 4 elements. |
2484 | /// uninit[0].write(sum); |
2485 | /// uninit[1].write(sum * 2); |
2486 | /// uninit[2].write(sum * 3); |
2487 | /// uninit[3].write(sum * 4); |
2488 | /// |
2489 | /// // Mark the 4 elements of the vector as being initialized. |
2490 | /// unsafe { |
2491 | /// let len = v.len(); |
2492 | /// v.set_len(len + 4); |
2493 | /// } |
2494 | /// |
2495 | /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]); |
2496 | /// ``` |
2497 | #[unstable (feature = "vec_split_at_spare" , issue = "81944" )] |
2498 | #[inline ] |
2499 | pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) { |
2500 | // SAFETY: |
2501 | // - len is ignored and so never changed |
2502 | let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() }; |
2503 | (init, spare) |
2504 | } |
2505 | |
2506 | /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`. |
2507 | /// |
2508 | /// This method provides unique access to all vec parts at once in `extend_from_within`. |
2509 | unsafe fn split_at_spare_mut_with_len( |
2510 | &mut self, |
2511 | ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) { |
2512 | let ptr = self.as_mut_ptr(); |
2513 | // SAFETY: |
2514 | // - `ptr` is guaranteed to be valid for `self.len` elements |
2515 | // - but the allocation extends out to `self.buf.capacity()` elements, possibly |
2516 | // uninitialized |
2517 | let spare_ptr = unsafe { ptr.add(self.len) }; |
2518 | let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>(); |
2519 | let spare_len = self.buf.capacity() - self.len; |
2520 | |
2521 | // SAFETY: |
2522 | // - `ptr` is guaranteed to be valid for `self.len` elements |
2523 | // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized` |
2524 | unsafe { |
2525 | let initialized = slice::from_raw_parts_mut(ptr, self.len); |
2526 | let spare = slice::from_raw_parts_mut(spare_ptr, spare_len); |
2527 | |
2528 | (initialized, spare, &mut self.len) |
2529 | } |
2530 | } |
2531 | } |
2532 | |
2533 | impl<T: Clone, A: Allocator> Vec<T, A> { |
2534 | /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. |
2535 | /// |
2536 | /// If `new_len` is greater than `len`, the `Vec` is extended by the |
2537 | /// difference, with each additional slot filled with `value`. |
2538 | /// If `new_len` is less than `len`, the `Vec` is simply truncated. |
2539 | /// |
2540 | /// This method requires `T` to implement [`Clone`], |
2541 | /// in order to be able to clone the passed value. |
2542 | /// If you need more flexibility (or want to rely on [`Default`] instead of |
2543 | /// [`Clone`]), use [`Vec::resize_with`]. |
2544 | /// If you only need to resize to a smaller size, use [`Vec::truncate`]. |
2545 | /// |
2546 | /// # Examples |
2547 | /// |
2548 | /// ``` |
2549 | /// let mut vec = vec!["hello" ]; |
2550 | /// vec.resize(3, "world" ); |
2551 | /// assert_eq!(vec, ["hello" , "world" , "world" ]); |
2552 | /// |
2553 | /// let mut vec = vec![1, 2, 3, 4]; |
2554 | /// vec.resize(2, 0); |
2555 | /// assert_eq!(vec, [1, 2]); |
2556 | /// ``` |
2557 | #[cfg (not(no_global_oom_handling))] |
2558 | #[stable (feature = "vec_resize" , since = "1.5.0" )] |
2559 | pub fn resize(&mut self, new_len: usize, value: T) { |
2560 | let len = self.len(); |
2561 | |
2562 | if new_len > len { |
2563 | self.extend_with(new_len - len, value) |
2564 | } else { |
2565 | self.truncate(new_len); |
2566 | } |
2567 | } |
2568 | |
2569 | /// Clones and appends all elements in a slice to the `Vec`. |
2570 | /// |
2571 | /// Iterates over the slice `other`, clones each element, and then appends |
2572 | /// it to this `Vec`. The `other` slice is traversed in-order. |
2573 | /// |
2574 | /// Note that this function is same as [`extend`] except that it is |
2575 | /// specialized to work with slices instead. If and when Rust gets |
2576 | /// specialization this function will likely be deprecated (but still |
2577 | /// available). |
2578 | /// |
2579 | /// # Examples |
2580 | /// |
2581 | /// ``` |
2582 | /// let mut vec = vec![1]; |
2583 | /// vec.extend_from_slice(&[2, 3, 4]); |
2584 | /// assert_eq!(vec, [1, 2, 3, 4]); |
2585 | /// ``` |
2586 | /// |
2587 | /// [`extend`]: Vec::extend |
2588 | #[cfg (not(no_global_oom_handling))] |
2589 | #[stable (feature = "vec_extend_from_slice" , since = "1.6.0" )] |
2590 | pub fn extend_from_slice(&mut self, other: &[T]) { |
2591 | self.spec_extend(other.iter()) |
2592 | } |
2593 | |
2594 | /// Copies elements from `src` range to the end of the vector. |
2595 | /// |
2596 | /// # Panics |
2597 | /// |
2598 | /// Panics if the starting point is greater than the end point or if |
2599 | /// the end point is greater than the length of the vector. |
2600 | /// |
2601 | /// # Examples |
2602 | /// |
2603 | /// ``` |
2604 | /// let mut vec = vec![0, 1, 2, 3, 4]; |
2605 | /// |
2606 | /// vec.extend_from_within(2..); |
2607 | /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]); |
2608 | /// |
2609 | /// vec.extend_from_within(..2); |
2610 | /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]); |
2611 | /// |
2612 | /// vec.extend_from_within(4..8); |
2613 | /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]); |
2614 | /// ``` |
2615 | #[cfg (not(no_global_oom_handling))] |
2616 | #[stable (feature = "vec_extend_from_within" , since = "1.53.0" )] |
2617 | pub fn extend_from_within<R>(&mut self, src: R) |
2618 | where |
2619 | R: RangeBounds<usize>, |
2620 | { |
2621 | let range = slice::range(src, ..self.len()); |
2622 | self.reserve(range.len()); |
2623 | |
2624 | // SAFETY: |
2625 | // - `slice::range` guarantees that the given range is valid for indexing self |
2626 | unsafe { |
2627 | self.spec_extend_from_within(range); |
2628 | } |
2629 | } |
2630 | } |
2631 | |
2632 | impl<T, A: Allocator, const N: usize> Vec<[T; N], A> { |
2633 | /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`. |
2634 | /// |
2635 | /// # Panics |
2636 | /// |
2637 | /// Panics if the length of the resulting vector would overflow a `usize`. |
2638 | /// |
2639 | /// This is only possible when flattening a vector of arrays of zero-sized |
2640 | /// types, and thus tends to be irrelevant in practice. If |
2641 | /// `size_of::<T>() > 0`, this will never panic. |
2642 | /// |
2643 | /// # Examples |
2644 | /// |
2645 | /// ``` |
2646 | /// #![feature(slice_flatten)] |
2647 | /// |
2648 | /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]]; |
2649 | /// assert_eq!(vec.pop(), Some([7, 8, 9])); |
2650 | /// |
2651 | /// let mut flattened = vec.into_flattened(); |
2652 | /// assert_eq!(flattened.pop(), Some(6)); |
2653 | /// ``` |
2654 | #[unstable (feature = "slice_flatten" , issue = "95629" )] |
2655 | pub fn into_flattened(self) -> Vec<T, A> { |
2656 | let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc(); |
2657 | let (new_len, new_cap) = if T::IS_ZST { |
2658 | (len.checked_mul(N).expect("vec len overflow" ), usize::MAX) |
2659 | } else { |
2660 | // SAFETY: |
2661 | // - `cap * N` cannot overflow because the allocation is already in |
2662 | // the address space. |
2663 | // - Each `[T; N]` has `N` valid elements, so there are `len * N` |
2664 | // valid elements in the allocation. |
2665 | unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) } |
2666 | }; |
2667 | // SAFETY: |
2668 | // - `ptr` was allocated by `self` |
2669 | // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`. |
2670 | // - `new_cap` refers to the same sized allocation as `cap` because |
2671 | // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()` |
2672 | // - `len` <= `cap`, so `len * N` <= `cap * N`. |
2673 | unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) } |
2674 | } |
2675 | } |
2676 | |
2677 | impl<T: Clone, A: Allocator> Vec<T, A> { |
2678 | #[cfg (not(no_global_oom_handling))] |
2679 | /// Extend the vector by `n` clones of value. |
2680 | fn extend_with(&mut self, n: usize, value: T) { |
2681 | self.reserve(n); |
2682 | |
2683 | unsafe { |
2684 | let mut ptr = self.as_mut_ptr().add(self.len()); |
2685 | // Use SetLenOnDrop to work around bug where compiler |
2686 | // might not realize the store through `ptr` through self.set_len() |
2687 | // don't alias. |
2688 | let mut local_len = SetLenOnDrop::new(&mut self.len); |
2689 | |
2690 | // Write all elements except the last one |
2691 | for _ in 1..n { |
2692 | ptr::write(ptr, value.clone()); |
2693 | ptr = ptr.add(1); |
2694 | // Increment the length in every step in case clone() panics |
2695 | local_len.increment_len(1); |
2696 | } |
2697 | |
2698 | if n > 0 { |
2699 | // We can write the last element directly without cloning needlessly |
2700 | ptr::write(ptr, value); |
2701 | local_len.increment_len(1); |
2702 | } |
2703 | |
2704 | // len set by scope guard |
2705 | } |
2706 | } |
2707 | } |
2708 | |
2709 | impl<T: PartialEq, A: Allocator> Vec<T, A> { |
2710 | /// Removes consecutive repeated elements in the vector according to the |
2711 | /// [`PartialEq`] trait implementation. |
2712 | /// |
2713 | /// If the vector is sorted, this removes all duplicates. |
2714 | /// |
2715 | /// # Examples |
2716 | /// |
2717 | /// ``` |
2718 | /// let mut vec = vec![1, 2, 2, 3, 2]; |
2719 | /// |
2720 | /// vec.dedup(); |
2721 | /// |
2722 | /// assert_eq!(vec, [1, 2, 3, 2]); |
2723 | /// ``` |
2724 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2725 | #[inline ] |
2726 | pub fn dedup(&mut self) { |
2727 | self.dedup_by(|a: &mut T, b: &mut T| a == b) |
2728 | } |
2729 | } |
2730 | |
2731 | //////////////////////////////////////////////////////////////////////////////// |
2732 | // Internal methods and functions |
2733 | //////////////////////////////////////////////////////////////////////////////// |
2734 | |
2735 | #[doc (hidden)] |
2736 | #[cfg (not(no_global_oom_handling))] |
2737 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2738 | pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> { |
2739 | <T as SpecFromElem>::from_elem(elem, n, alloc:Global) |
2740 | } |
2741 | |
2742 | #[doc (hidden)] |
2743 | #[cfg (not(no_global_oom_handling))] |
2744 | #[unstable (feature = "allocator_api" , issue = "32838" )] |
2745 | pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> { |
2746 | <T as SpecFromElem>::from_elem(elem, n, alloc) |
2747 | } |
2748 | |
2749 | #[cfg (not(no_global_oom_handling))] |
2750 | trait ExtendFromWithinSpec { |
2751 | /// # Safety |
2752 | /// |
2753 | /// - `src` needs to be valid index |
2754 | /// - `self.capacity() - self.len()` must be `>= src.len()` |
2755 | unsafe fn spec_extend_from_within(&mut self, src: Range<usize>); |
2756 | } |
2757 | |
2758 | #[cfg (not(no_global_oom_handling))] |
2759 | impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> { |
2760 | default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) { |
2761 | // SAFETY: |
2762 | // - len is increased only after initializing elements |
2763 | let (this: &mut [T], spare: &mut [MaybeUninit], len: &mut usize) = unsafe { self.split_at_spare_mut_with_len() }; |
2764 | |
2765 | // SAFETY: |
2766 | // - caller guarantees that src is a valid index |
2767 | let to_clone: &[T] = unsafe { this.get_unchecked(index:src) }; |
2768 | |
2769 | iterimpl Iterator ::zip(a:to_clone, b:spare) |
2770 | .map(|(src: &T, dst: &mut MaybeUninit)| dst.write(val:src.clone())) |
2771 | // Note: |
2772 | // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len |
2773 | // - len is increased after each element to prevent leaks (see issue #82533) |
2774 | .for_each(|_| *len += 1); |
2775 | } |
2776 | } |
2777 | |
2778 | #[cfg (not(no_global_oom_handling))] |
2779 | impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> { |
2780 | unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) { |
2781 | let count = src.len(); |
2782 | { |
2783 | let (init, spare) = self.split_at_spare_mut(); |
2784 | |
2785 | // SAFETY: |
2786 | // - caller guarantees that `src` is a valid index |
2787 | let source = unsafe { init.get_unchecked(src) }; |
2788 | |
2789 | // SAFETY: |
2790 | // - Both pointers are created from unique slice references (`&mut [_]`) |
2791 | // so they are valid and do not overlap. |
2792 | // - Elements are :Copy so it's OK to copy them, without doing |
2793 | // anything with the original values |
2794 | // - `count` is equal to the len of `source`, so source is valid for |
2795 | // `count` reads |
2796 | // - `.reserve(count)` guarantees that `spare.len() >= count` so spare |
2797 | // is valid for `count` writes |
2798 | unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) }; |
2799 | } |
2800 | |
2801 | // SAFETY: |
2802 | // - The elements were just initialized by `copy_nonoverlapping` |
2803 | self.len += count; |
2804 | } |
2805 | } |
2806 | |
2807 | //////////////////////////////////////////////////////////////////////////////// |
2808 | // Common trait implementations for Vec |
2809 | //////////////////////////////////////////////////////////////////////////////// |
2810 | |
2811 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2812 | impl<T, A: Allocator> ops::Deref for Vec<T, A> { |
2813 | type Target = [T]; |
2814 | |
2815 | #[inline ] |
2816 | fn deref(&self) -> &[T] { |
2817 | unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } |
2818 | } |
2819 | } |
2820 | |
2821 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2822 | impl<T, A: Allocator> ops::DerefMut for Vec<T, A> { |
2823 | #[inline ] |
2824 | fn deref_mut(&mut self) -> &mut [T] { |
2825 | unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } |
2826 | } |
2827 | } |
2828 | |
2829 | #[unstable (feature = "deref_pure_trait" , issue = "87121" )] |
2830 | unsafe impl<T, A: Allocator> ops::DerefPure for Vec<T, A> {} |
2831 | |
2832 | #[cfg (not(no_global_oom_handling))] |
2833 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2834 | impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> { |
2835 | #[cfg (not(test))] |
2836 | fn clone(&self) -> Self { |
2837 | let alloc = self.allocator().clone(); |
2838 | <[T]>::to_vec_in(&**self, alloc) |
2839 | } |
2840 | |
2841 | // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is |
2842 | // required for this method definition, is not available. Instead use the |
2843 | // `slice::to_vec` function which is only available with cfg(test) |
2844 | // NB see the slice::hack module in slice.rs for more information |
2845 | #[cfg (test)] |
2846 | fn clone(&self) -> Self { |
2847 | let alloc = self.allocator().clone(); |
2848 | crate::slice::to_vec(&**self, alloc) |
2849 | } |
2850 | |
2851 | /// Overwrites the contents of `self` with a clone of the contents of `source`. |
2852 | /// |
2853 | /// This method is preferred over simply assigning `source.clone()` to `self`, |
2854 | /// as it avoids reallocation if possible. Additionally, if the element type |
2855 | /// `T` overrides `clone_from()`, this will reuse the resources of `self`'s |
2856 | /// elements as well. |
2857 | /// |
2858 | /// # Examples |
2859 | /// |
2860 | /// ``` |
2861 | /// let x = vec![5, 6, 7]; |
2862 | /// let mut y = vec![8, 9, 10]; |
2863 | /// let yp: *const i32 = y.as_ptr(); |
2864 | /// |
2865 | /// y.clone_from(&x); |
2866 | /// |
2867 | /// // The value is the same |
2868 | /// assert_eq!(x, y); |
2869 | /// |
2870 | /// // And no reallocation occurred |
2871 | /// assert_eq!(yp, y.as_ptr()); |
2872 | /// ``` |
2873 | fn clone_from(&mut self, source: &Self) { |
2874 | crate::slice::SpecCloneIntoVec::clone_into(source.as_slice(), self); |
2875 | } |
2876 | } |
2877 | |
2878 | /// The hash of a vector is the same as that of the corresponding slice, |
2879 | /// as required by the `core::borrow::Borrow` implementation. |
2880 | /// |
2881 | /// ``` |
2882 | /// use std::hash::BuildHasher; |
2883 | /// |
2884 | /// let b = std::hash::RandomState::new(); |
2885 | /// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09]; |
2886 | /// let s: &[u8] = &[0xa8, 0x3c, 0x09]; |
2887 | /// assert_eq!(b.hash_one(v), b.hash_one(s)); |
2888 | /// ``` |
2889 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2890 | impl<T: Hash, A: Allocator> Hash for Vec<T, A> { |
2891 | #[inline ] |
2892 | fn hash<H: Hasher>(&self, state: &mut H) { |
2893 | Hash::hash(&**self, state) |
2894 | } |
2895 | } |
2896 | |
2897 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2898 | #[rustc_on_unimplemented ( |
2899 | message = "vector indices are of type `usize` or ranges of `usize`" , |
2900 | label = "vector indices are of type `usize` or ranges of `usize`" |
2901 | )] |
2902 | impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> { |
2903 | type Output = I::Output; |
2904 | |
2905 | #[inline ] |
2906 | fn index(&self, index: I) -> &Self::Output { |
2907 | Index::index(&**self, index) |
2908 | } |
2909 | } |
2910 | |
2911 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2912 | #[rustc_on_unimplemented ( |
2913 | message = "vector indices are of type `usize` or ranges of `usize`" , |
2914 | label = "vector indices are of type `usize` or ranges of `usize`" |
2915 | )] |
2916 | impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> { |
2917 | #[inline ] |
2918 | fn index_mut(&mut self, index: I) -> &mut Self::Output { |
2919 | IndexMut::index_mut(&mut **self, index) |
2920 | } |
2921 | } |
2922 | |
2923 | /// Collects an iterator into a Vec, commonly called via [`Iterator::collect()`] |
2924 | /// |
2925 | /// # Allocation behavior |
2926 | /// |
2927 | /// In general `Vec` does not guarantee any particular growth or allocation strategy. |
2928 | /// That also applies to this trait impl. |
2929 | /// |
2930 | /// **Note:** This section covers implementation details and is therefore exempt from |
2931 | /// stability guarantees. |
2932 | /// |
2933 | /// Vec may use any or none of the following strategies, |
2934 | /// depending on the supplied iterator: |
2935 | /// |
2936 | /// * preallocate based on [`Iterator::size_hint()`] |
2937 | /// * and panic if the number of items is outside the provided lower/upper bounds |
2938 | /// * use an amortized growth strategy similar to `pushing` one item at a time |
2939 | /// * perform the iteration in-place on the original allocation backing the iterator |
2940 | /// |
2941 | /// The last case warrants some attention. It is an optimization that in many cases reduces peak memory |
2942 | /// consumption and improves cache locality. But when big, short-lived allocations are created, |
2943 | /// only a small fraction of their items get collected, no further use is made of the spare capacity |
2944 | /// and the resulting `Vec` is moved into a longer-lived structure, then this can lead to the large |
2945 | /// allocations having their lifetimes unnecessarily extended which can result in increased memory |
2946 | /// footprint. |
2947 | /// |
2948 | /// In cases where this is an issue, the excess capacity can be discarded with [`Vec::shrink_to()`], |
2949 | /// [`Vec::shrink_to_fit()`] or by collecting into [`Box<[T]>`][owned slice] instead, which additionally reduces |
2950 | /// the size of the long-lived struct. |
2951 | /// |
2952 | /// [owned slice]: Box |
2953 | /// |
2954 | /// ```rust |
2955 | /// # use std::sync::Mutex; |
2956 | /// static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new()); |
2957 | /// |
2958 | /// for i in 0..10 { |
2959 | /// let big_temporary: Vec<u16> = (0..1024).collect(); |
2960 | /// // discard most items |
2961 | /// let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect(); |
2962 | /// // without this a lot of unused capacity might be moved into the global |
2963 | /// result.shrink_to_fit(); |
2964 | /// LONG_LIVED.lock().unwrap().push(result); |
2965 | /// } |
2966 | /// ``` |
2967 | #[cfg (not(no_global_oom_handling))] |
2968 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2969 | impl<T> FromIterator<T> for Vec<T> { |
2970 | #[inline ] |
2971 | fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> { |
2972 | <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter()) |
2973 | } |
2974 | } |
2975 | |
2976 | #[stable (feature = "rust1" , since = "1.0.0" )] |
2977 | impl<T, A: Allocator> IntoIterator for Vec<T, A> { |
2978 | type Item = T; |
2979 | type IntoIter = IntoIter<T, A>; |
2980 | |
2981 | /// Creates a consuming iterator, that is, one that moves each value out of |
2982 | /// the vector (from start to end). The vector cannot be used after calling |
2983 | /// this. |
2984 | /// |
2985 | /// # Examples |
2986 | /// |
2987 | /// ``` |
2988 | /// let v = vec!["a" .to_string(), "b" .to_string()]; |
2989 | /// let mut v_iter = v.into_iter(); |
2990 | /// |
2991 | /// let first_element: Option<String> = v_iter.next(); |
2992 | /// |
2993 | /// assert_eq!(first_element, Some("a" .to_string())); |
2994 | /// assert_eq!(v_iter.next(), Some("b" .to_string())); |
2995 | /// assert_eq!(v_iter.next(), None); |
2996 | /// ``` |
2997 | #[inline ] |
2998 | fn into_iter(self) -> Self::IntoIter { |
2999 | unsafe { |
3000 | let me = ManuallyDrop::new(self); |
3001 | let alloc = ManuallyDrop::new(ptr::read(me.allocator())); |
3002 | let buf = me.buf.non_null(); |
3003 | let begin = buf.as_ptr(); |
3004 | let end = if T::IS_ZST { |
3005 | begin.wrapping_byte_add(me.len()) |
3006 | } else { |
3007 | begin.add(me.len()) as *const T |
3008 | }; |
3009 | let cap = me.buf.capacity(); |
3010 | IntoIter { buf, phantom: PhantomData, cap, alloc, ptr: buf, end } |
3011 | } |
3012 | } |
3013 | } |
3014 | |
3015 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3016 | impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> { |
3017 | type Item = &'a T; |
3018 | type IntoIter = slice::Iter<'a, T>; |
3019 | |
3020 | fn into_iter(self) -> Self::IntoIter { |
3021 | self.iter() |
3022 | } |
3023 | } |
3024 | |
3025 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3026 | impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> { |
3027 | type Item = &'a mut T; |
3028 | type IntoIter = slice::IterMut<'a, T>; |
3029 | |
3030 | fn into_iter(self) -> Self::IntoIter { |
3031 | self.iter_mut() |
3032 | } |
3033 | } |
3034 | |
3035 | #[cfg (not(no_global_oom_handling))] |
3036 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3037 | impl<T, A: Allocator> Extend<T> for Vec<T, A> { |
3038 | #[inline ] |
3039 | fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { |
3040 | <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter()) |
3041 | } |
3042 | |
3043 | #[inline ] |
3044 | fn extend_one(&mut self, item: T) { |
3045 | self.push(item); |
3046 | } |
3047 | |
3048 | #[inline ] |
3049 | fn extend_reserve(&mut self, additional: usize) { |
3050 | self.reserve(additional); |
3051 | } |
3052 | } |
3053 | |
3054 | impl<T, A: Allocator> Vec<T, A> { |
3055 | // leaf method to which various SpecFrom/SpecExtend implementations delegate when |
3056 | // they have no further optimizations to apply |
3057 | #[cfg (not(no_global_oom_handling))] |
3058 | fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) { |
3059 | // This is the case for a general iterator. |
3060 | // |
3061 | // This function should be the moral equivalent of: |
3062 | // |
3063 | // for item in iterator { |
3064 | // self.push(item); |
3065 | // } |
3066 | while let Some(element) = iterator.next() { |
3067 | let len = self.len(); |
3068 | if len == self.capacity() { |
3069 | let (lower, _) = iterator.size_hint(); |
3070 | self.reserve(lower.saturating_add(1)); |
3071 | } |
3072 | unsafe { |
3073 | ptr::write(self.as_mut_ptr().add(len), element); |
3074 | // Since next() executes user code which can panic we have to bump the length |
3075 | // after each step. |
3076 | // NB can't overflow since we would have had to alloc the address space |
3077 | self.set_len(len + 1); |
3078 | } |
3079 | } |
3080 | } |
3081 | |
3082 | // specific extend for `TrustedLen` iterators, called both by the specializations |
3083 | // and internal places where resolving specialization makes compilation slower |
3084 | #[cfg (not(no_global_oom_handling))] |
3085 | fn extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) { |
3086 | let (low, high) = iterator.size_hint(); |
3087 | if let Some(additional) = high { |
3088 | debug_assert_eq!( |
3089 | low, |
3090 | additional, |
3091 | "TrustedLen iterator's size hint is not exact: {:?}" , |
3092 | (low, high) |
3093 | ); |
3094 | self.reserve(additional); |
3095 | unsafe { |
3096 | let ptr = self.as_mut_ptr(); |
3097 | let mut local_len = SetLenOnDrop::new(&mut self.len); |
3098 | iterator.for_each(move |element| { |
3099 | ptr::write(ptr.add(local_len.current_len()), element); |
3100 | // Since the loop executes user code which can panic we have to update |
3101 | // the length every step to correctly drop what we've written. |
3102 | // NB can't overflow since we would have had to alloc the address space |
3103 | local_len.increment_len(1); |
3104 | }); |
3105 | } |
3106 | } else { |
3107 | // Per TrustedLen contract a `None` upper bound means that the iterator length |
3108 | // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway. |
3109 | // Since the other branch already panics eagerly (via `reserve()`) we do the same here. |
3110 | // This avoids additional codegen for a fallback code path which would eventually |
3111 | // panic anyway. |
3112 | panic!("capacity overflow" ); |
3113 | } |
3114 | } |
3115 | |
3116 | /// Creates a splicing iterator that replaces the specified range in the vector |
3117 | /// with the given `replace_with` iterator and yields the removed items. |
3118 | /// `replace_with` does not need to be the same length as `range`. |
3119 | /// |
3120 | /// `range` is removed even if the iterator is not consumed until the end. |
3121 | /// |
3122 | /// It is unspecified how many elements are removed from the vector |
3123 | /// if the `Splice` value is leaked. |
3124 | /// |
3125 | /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped. |
3126 | /// |
3127 | /// This is optimal if: |
3128 | /// |
3129 | /// * The tail (elements in the vector after `range`) is empty, |
3130 | /// * or `replace_with` yields fewer or equal elements than `range`’s length |
3131 | /// * or the lower bound of its `size_hint()` is exact. |
3132 | /// |
3133 | /// Otherwise, a temporary vector is allocated and the tail is moved twice. |
3134 | /// |
3135 | /// # Panics |
3136 | /// |
3137 | /// Panics if the starting point is greater than the end point or if |
3138 | /// the end point is greater than the length of the vector. |
3139 | /// |
3140 | /// # Examples |
3141 | /// |
3142 | /// ``` |
3143 | /// let mut v = vec![1, 2, 3, 4]; |
3144 | /// let new = [7, 8, 9]; |
3145 | /// let u: Vec<_> = v.splice(1..3, new).collect(); |
3146 | /// assert_eq!(v, &[1, 7, 8, 9, 4]); |
3147 | /// assert_eq!(u, &[2, 3]); |
3148 | /// ``` |
3149 | #[cfg (not(no_global_oom_handling))] |
3150 | #[inline ] |
3151 | #[stable (feature = "vec_splice" , since = "1.21.0" )] |
3152 | pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> |
3153 | where |
3154 | R: RangeBounds<usize>, |
3155 | I: IntoIterator<Item = T>, |
3156 | { |
3157 | Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } |
3158 | } |
3159 | |
3160 | /// Creates an iterator which uses a closure to determine if an element should be removed. |
3161 | /// |
3162 | /// If the closure returns true, then the element is removed and yielded. |
3163 | /// If the closure returns false, the element will remain in the vector and will not be yielded |
3164 | /// by the iterator. |
3165 | /// |
3166 | /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating |
3167 | /// or the iteration short-circuits, then the remaining elements will be retained. |
3168 | /// Use [`retain`] with a negated predicate if you do not need the returned iterator. |
3169 | /// |
3170 | /// [`retain`]: Vec::retain |
3171 | /// |
3172 | /// Using this method is equivalent to the following code: |
3173 | /// |
3174 | /// ``` |
3175 | /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 }; |
3176 | /// # let mut vec = vec![1, 2, 3, 4, 5, 6]; |
3177 | /// let mut i = 0; |
3178 | /// while i < vec.len() { |
3179 | /// if some_predicate(&mut vec[i]) { |
3180 | /// let val = vec.remove(i); |
3181 | /// // your code here |
3182 | /// } else { |
3183 | /// i += 1; |
3184 | /// } |
3185 | /// } |
3186 | /// |
3187 | /// # assert_eq!(vec, vec![1, 4, 5]); |
3188 | /// ``` |
3189 | /// |
3190 | /// But `extract_if` is easier to use. `extract_if` is also more efficient, |
3191 | /// because it can backshift the elements of the array in bulk. |
3192 | /// |
3193 | /// Note that `extract_if` also lets you mutate every element in the filter closure, |
3194 | /// regardless of whether you choose to keep or remove it. |
3195 | /// |
3196 | /// # Examples |
3197 | /// |
3198 | /// Splitting an array into evens and odds, reusing the original allocation: |
3199 | /// |
3200 | /// ``` |
3201 | /// #![feature(extract_if)] |
3202 | /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]; |
3203 | /// |
3204 | /// let evens = numbers.extract_if(|x| *x % 2 == 0).collect::<Vec<_>>(); |
3205 | /// let odds = numbers; |
3206 | /// |
3207 | /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); |
3208 | /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); |
3209 | /// ``` |
3210 | #[unstable (feature = "extract_if" , reason = "recently added" , issue = "43244" )] |
3211 | pub fn extract_if<F>(&mut self, filter: F) -> ExtractIf<'_, T, F, A> |
3212 | where |
3213 | F: FnMut(&mut T) -> bool, |
3214 | { |
3215 | let old_len = self.len(); |
3216 | |
3217 | // Guard against us getting leaked (leak amplification) |
3218 | unsafe { |
3219 | self.set_len(0); |
3220 | } |
3221 | |
3222 | ExtractIf { vec: self, idx: 0, del: 0, old_len, pred: filter } |
3223 | } |
3224 | } |
3225 | |
3226 | /// Extend implementation that copies elements out of references before pushing them onto the Vec. |
3227 | /// |
3228 | /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to |
3229 | /// append the entire slice at once. |
3230 | /// |
3231 | /// [`copy_from_slice`]: slice::copy_from_slice |
3232 | #[cfg (not(no_global_oom_handling))] |
3233 | #[stable (feature = "extend_ref" , since = "1.2.0" )] |
3234 | impl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec<T, A> { |
3235 | fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { |
3236 | self.spec_extend(iter.into_iter()) |
3237 | } |
3238 | |
3239 | #[inline ] |
3240 | fn extend_one(&mut self, &item: T: &'a T) { |
3241 | self.push(item); |
3242 | } |
3243 | |
3244 | #[inline ] |
3245 | fn extend_reserve(&mut self, additional: usize) { |
3246 | self.reserve(additional); |
3247 | } |
3248 | } |
3249 | |
3250 | /// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison). |
3251 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3252 | impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1> |
3253 | where |
3254 | T: PartialOrd, |
3255 | A1: Allocator, |
3256 | A2: Allocator, |
3257 | { |
3258 | #[inline ] |
3259 | fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering> { |
3260 | PartialOrd::partial_cmp(&**self, &**other) |
3261 | } |
3262 | } |
3263 | |
3264 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3265 | impl<T: Eq, A: Allocator> Eq for Vec<T, A> {} |
3266 | |
3267 | /// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison). |
3268 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3269 | impl<T: Ord, A: Allocator> Ord for Vec<T, A> { |
3270 | #[inline ] |
3271 | fn cmp(&self, other: &Self) -> Ordering { |
3272 | Ord::cmp(&**self, &**other) |
3273 | } |
3274 | } |
3275 | |
3276 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3277 | unsafe impl<#[may_dangle ] T, A: Allocator> Drop for Vec<T, A> { |
3278 | fn drop(&mut self) { |
3279 | unsafe { |
3280 | // use drop for [T] |
3281 | // use a raw slice to refer to the elements of the vector as weakest necessary type; |
3282 | // could avoid questions of validity in certain cases |
3283 | ptr::drop_in_place(to_drop:ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) |
3284 | } |
3285 | // RawVec handles deallocation |
3286 | } |
3287 | } |
3288 | |
3289 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3290 | impl<T> Default for Vec<T> { |
3291 | /// Creates an empty `Vec<T>`. |
3292 | /// |
3293 | /// The vector will not allocate until elements are pushed onto it. |
3294 | fn default() -> Vec<T> { |
3295 | Vec::new() |
3296 | } |
3297 | } |
3298 | |
3299 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3300 | impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> { |
3301 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
3302 | fmt::Debug::fmt(&**self, f) |
3303 | } |
3304 | } |
3305 | |
3306 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3307 | impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> { |
3308 | fn as_ref(&self) -> &Vec<T, A> { |
3309 | self |
3310 | } |
3311 | } |
3312 | |
3313 | #[stable (feature = "vec_as_mut" , since = "1.5.0" )] |
3314 | impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> { |
3315 | fn as_mut(&mut self) -> &mut Vec<T, A> { |
3316 | self |
3317 | } |
3318 | } |
3319 | |
3320 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3321 | impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> { |
3322 | fn as_ref(&self) -> &[T] { |
3323 | self |
3324 | } |
3325 | } |
3326 | |
3327 | #[stable (feature = "vec_as_mut" , since = "1.5.0" )] |
3328 | impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> { |
3329 | fn as_mut(&mut self) -> &mut [T] { |
3330 | self |
3331 | } |
3332 | } |
3333 | |
3334 | #[cfg (not(no_global_oom_handling))] |
3335 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3336 | impl<T: Clone> From<&[T]> for Vec<T> { |
3337 | /// Allocate a `Vec<T>` and fill it by cloning `s`'s items. |
3338 | /// |
3339 | /// # Examples |
3340 | /// |
3341 | /// ``` |
3342 | /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]); |
3343 | /// ``` |
3344 | #[cfg (not(test))] |
3345 | fn from(s: &[T]) -> Vec<T> { |
3346 | s.to_vec() |
3347 | } |
3348 | #[cfg (test)] |
3349 | fn from(s: &[T]) -> Vec<T> { |
3350 | crate::slice::to_vec(s, Global) |
3351 | } |
3352 | } |
3353 | |
3354 | #[cfg (not(no_global_oom_handling))] |
3355 | #[stable (feature = "vec_from_mut" , since = "1.19.0" )] |
3356 | impl<T: Clone> From<&mut [T]> for Vec<T> { |
3357 | /// Allocate a `Vec<T>` and fill it by cloning `s`'s items. |
3358 | /// |
3359 | /// # Examples |
3360 | /// |
3361 | /// ``` |
3362 | /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]); |
3363 | /// ``` |
3364 | #[cfg (not(test))] |
3365 | fn from(s: &mut [T]) -> Vec<T> { |
3366 | s.to_vec() |
3367 | } |
3368 | #[cfg (test)] |
3369 | fn from(s: &mut [T]) -> Vec<T> { |
3370 | crate::slice::to_vec(s, Global) |
3371 | } |
3372 | } |
3373 | |
3374 | #[cfg (not(no_global_oom_handling))] |
3375 | #[stable (feature = "vec_from_array_ref" , since = "1.74.0" )] |
3376 | impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> { |
3377 | /// Allocate a `Vec<T>` and fill it by cloning `s`'s items. |
3378 | /// |
3379 | /// # Examples |
3380 | /// |
3381 | /// ``` |
3382 | /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]); |
3383 | /// ``` |
3384 | fn from(s: &[T; N]) -> Vec<T> { |
3385 | Self::from(s.as_slice()) |
3386 | } |
3387 | } |
3388 | |
3389 | #[cfg (not(no_global_oom_handling))] |
3390 | #[stable (feature = "vec_from_array_ref" , since = "1.74.0" )] |
3391 | impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> { |
3392 | /// Allocate a `Vec<T>` and fill it by cloning `s`'s items. |
3393 | /// |
3394 | /// # Examples |
3395 | /// |
3396 | /// ``` |
3397 | /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]); |
3398 | /// ``` |
3399 | fn from(s: &mut [T; N]) -> Vec<T> { |
3400 | Self::from(s.as_mut_slice()) |
3401 | } |
3402 | } |
3403 | |
3404 | #[cfg (not(no_global_oom_handling))] |
3405 | #[stable (feature = "vec_from_array" , since = "1.44.0" )] |
3406 | impl<T, const N: usize> From<[T; N]> for Vec<T> { |
3407 | /// Allocate a `Vec<T>` and move `s`'s items into it. |
3408 | /// |
3409 | /// # Examples |
3410 | /// |
3411 | /// ``` |
3412 | /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]); |
3413 | /// ``` |
3414 | #[cfg (not(test))] |
3415 | fn from(s: [T; N]) -> Vec<T> { |
3416 | <[T]>::into_vec(self:Box::new(s)) |
3417 | } |
3418 | |
3419 | #[cfg (test)] |
3420 | fn from(s: [T; N]) -> Vec<T> { |
3421 | crate::slice::into_vec(Box::new(s)) |
3422 | } |
3423 | } |
3424 | |
3425 | #[stable (feature = "vec_from_cow_slice" , since = "1.14.0" )] |
3426 | impl<'a, T> From<Cow<'a, [T]>> for Vec<T> |
3427 | where |
3428 | [T]: ToOwned<Owned = Vec<T>>, |
3429 | { |
3430 | /// Convert a clone-on-write slice into a vector. |
3431 | /// |
3432 | /// If `s` already owns a `Vec<T>`, it will be returned directly. |
3433 | /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and |
3434 | /// filled by cloning `s`'s items into it. |
3435 | /// |
3436 | /// # Examples |
3437 | /// |
3438 | /// ``` |
3439 | /// # use std::borrow::Cow; |
3440 | /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]); |
3441 | /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]); |
3442 | /// assert_eq!(Vec::from(o), Vec::from(b)); |
3443 | /// ``` |
3444 | fn from(s: Cow<'a, [T]>) -> Vec<T> { |
3445 | s.into_owned() |
3446 | } |
3447 | } |
3448 | |
3449 | // note: test pulls in std, which causes errors here |
3450 | #[cfg (not(test))] |
3451 | #[stable (feature = "vec_from_box" , since = "1.18.0" )] |
3452 | impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> { |
3453 | /// Convert a boxed slice into a vector by transferring ownership of |
3454 | /// the existing heap allocation. |
3455 | /// |
3456 | /// # Examples |
3457 | /// |
3458 | /// ``` |
3459 | /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice(); |
3460 | /// assert_eq!(Vec::from(b), vec![1, 2, 3]); |
3461 | /// ``` |
3462 | fn from(s: Box<[T], A>) -> Self { |
3463 | s.into_vec() |
3464 | } |
3465 | } |
3466 | |
3467 | // note: test pulls in std, which causes errors here |
3468 | #[cfg (not(no_global_oom_handling))] |
3469 | #[cfg (not(test))] |
3470 | #[stable (feature = "box_from_vec" , since = "1.20.0" )] |
3471 | impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> { |
3472 | /// Convert a vector into a boxed slice. |
3473 | /// |
3474 | /// Before doing the conversion, this method discards excess capacity like [`Vec::shrink_to_fit`]. |
3475 | /// |
3476 | /// [owned slice]: Box |
3477 | /// [`Vec::shrink_to_fit`]: Vec::shrink_to_fit |
3478 | /// |
3479 | /// # Examples |
3480 | /// |
3481 | /// ``` |
3482 | /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); |
3483 | /// ``` |
3484 | /// |
3485 | /// Any excess capacity is removed: |
3486 | /// ``` |
3487 | /// let mut vec = Vec::with_capacity(10); |
3488 | /// vec.extend([1, 2, 3]); |
3489 | /// |
3490 | /// assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice()); |
3491 | /// ``` |
3492 | fn from(v: Vec<T, A>) -> Self { |
3493 | v.into_boxed_slice() |
3494 | } |
3495 | } |
3496 | |
3497 | #[cfg (not(no_global_oom_handling))] |
3498 | #[stable (feature = "rust1" , since = "1.0.0" )] |
3499 | impl From<&str> for Vec<u8> { |
3500 | /// Allocate a `Vec<u8>` and fill it with a UTF-8 string. |
3501 | /// |
3502 | /// # Examples |
3503 | /// |
3504 | /// ``` |
3505 | /// assert_eq!(Vec::from("123" ), vec![b'1' , b'2' , b'3' ]); |
3506 | /// ``` |
3507 | fn from(s: &str) -> Vec<u8> { |
3508 | From::from(s.as_bytes()) |
3509 | } |
3510 | } |
3511 | |
3512 | #[stable (feature = "array_try_from_vec" , since = "1.48.0" )] |
3513 | impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] { |
3514 | type Error = Vec<T, A>; |
3515 | |
3516 | /// Gets the entire contents of the `Vec<T>` as an array, |
3517 | /// if its size exactly matches that of the requested array. |
3518 | /// |
3519 | /// # Examples |
3520 | /// |
3521 | /// ``` |
3522 | /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3])); |
3523 | /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([])); |
3524 | /// ``` |
3525 | /// |
3526 | /// If the length doesn't match, the input comes back in `Err`: |
3527 | /// ``` |
3528 | /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into(); |
3529 | /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); |
3530 | /// ``` |
3531 | /// |
3532 | /// If you're fine with just getting a prefix of the `Vec<T>`, |
3533 | /// you can call [`.truncate(N)`](Vec::truncate) first. |
3534 | /// ``` |
3535 | /// let mut v = String::from("hello world" ).into_bytes(); |
3536 | /// v.sort(); |
3537 | /// v.truncate(2); |
3538 | /// let [a, b]: [_; 2] = v.try_into().unwrap(); |
3539 | /// assert_eq!(a, b' ' ); |
3540 | /// assert_eq!(b, b'd' ); |
3541 | /// ``` |
3542 | fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> { |
3543 | if vec.len() != N { |
3544 | return Err(vec); |
3545 | } |
3546 | |
3547 | // SAFETY: `.set_len(0)` is always sound. |
3548 | unsafe { vec.set_len(0) }; |
3549 | |
3550 | // SAFETY: A `Vec`'s pointer is always aligned properly, and |
3551 | // the alignment the array needs is the same as the items. |
3552 | // We checked earlier that we have sufficient items. |
3553 | // The items will not double-drop as the `set_len` |
3554 | // tells the `Vec` not to also drop them. |
3555 | let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) }; |
3556 | Ok(array) |
3557 | } |
3558 | } |
3559 | |