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