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