162306a36Sopenharmony_ci// SPDX-License-Identifier: Apache-2.0 OR MIT 262306a36Sopenharmony_ci 362306a36Sopenharmony_ci//! A contiguous growable array type with heap-allocated contents, written 462306a36Sopenharmony_ci//! `Vec<T>`. 562306a36Sopenharmony_ci//! 662306a36Sopenharmony_ci//! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and 762306a36Sopenharmony_ci//! *O*(1) pop (from the end). 862306a36Sopenharmony_ci//! 962306a36Sopenharmony_ci//! Vectors ensure they never allocate more than `isize::MAX` bytes. 1062306a36Sopenharmony_ci//! 1162306a36Sopenharmony_ci//! # Examples 1262306a36Sopenharmony_ci//! 1362306a36Sopenharmony_ci//! You can explicitly create a [`Vec`] with [`Vec::new`]: 1462306a36Sopenharmony_ci//! 1562306a36Sopenharmony_ci//! ``` 1662306a36Sopenharmony_ci//! let v: Vec<i32> = Vec::new(); 1762306a36Sopenharmony_ci//! ``` 1862306a36Sopenharmony_ci//! 1962306a36Sopenharmony_ci//! ...or by using the [`vec!`] macro: 2062306a36Sopenharmony_ci//! 2162306a36Sopenharmony_ci//! ``` 2262306a36Sopenharmony_ci//! let v: Vec<i32> = vec![]; 2362306a36Sopenharmony_ci//! 2462306a36Sopenharmony_ci//! let v = vec![1, 2, 3, 4, 5]; 2562306a36Sopenharmony_ci//! 2662306a36Sopenharmony_ci//! let v = vec![0; 10]; // ten zeroes 2762306a36Sopenharmony_ci//! ``` 2862306a36Sopenharmony_ci//! 2962306a36Sopenharmony_ci//! You can [`push`] values onto the end of a vector (which will grow the vector 3062306a36Sopenharmony_ci//! as needed): 3162306a36Sopenharmony_ci//! 3262306a36Sopenharmony_ci//! ``` 3362306a36Sopenharmony_ci//! let mut v = vec![1, 2]; 3462306a36Sopenharmony_ci//! 3562306a36Sopenharmony_ci//! v.push(3); 3662306a36Sopenharmony_ci//! ``` 3762306a36Sopenharmony_ci//! 3862306a36Sopenharmony_ci//! Popping values works in much the same way: 3962306a36Sopenharmony_ci//! 4062306a36Sopenharmony_ci//! ``` 4162306a36Sopenharmony_ci//! let mut v = vec![1, 2]; 4262306a36Sopenharmony_ci//! 4362306a36Sopenharmony_ci//! let two = v.pop(); 4462306a36Sopenharmony_ci//! ``` 4562306a36Sopenharmony_ci//! 4662306a36Sopenharmony_ci//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits): 4762306a36Sopenharmony_ci//! 4862306a36Sopenharmony_ci//! ``` 4962306a36Sopenharmony_ci//! let mut v = vec![1, 2, 3]; 5062306a36Sopenharmony_ci//! let three = v[2]; 5162306a36Sopenharmony_ci//! v[1] = v[1] + 5; 5262306a36Sopenharmony_ci//! ``` 5362306a36Sopenharmony_ci//! 5462306a36Sopenharmony_ci//! [`push`]: Vec::push 5562306a36Sopenharmony_ci 5662306a36Sopenharmony_ci#![stable(feature = "rust1", since = "1.0.0")] 5762306a36Sopenharmony_ci 5862306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 5962306a36Sopenharmony_ciuse core::cmp; 6062306a36Sopenharmony_ciuse core::cmp::Ordering; 6162306a36Sopenharmony_ciuse core::fmt; 6262306a36Sopenharmony_ciuse core::hash::{Hash, Hasher}; 6362306a36Sopenharmony_ciuse core::iter; 6462306a36Sopenharmony_ciuse core::marker::PhantomData; 6562306a36Sopenharmony_ciuse core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties}; 6662306a36Sopenharmony_ciuse core::ops::{self, Index, IndexMut, Range, RangeBounds}; 6762306a36Sopenharmony_ciuse core::ptr::{self, NonNull}; 6862306a36Sopenharmony_ciuse core::slice::{self, SliceIndex}; 6962306a36Sopenharmony_ci 7062306a36Sopenharmony_ciuse crate::alloc::{Allocator, Global}; 7162306a36Sopenharmony_ci#[cfg(not(no_borrow))] 7262306a36Sopenharmony_ciuse crate::borrow::{Cow, ToOwned}; 7362306a36Sopenharmony_ciuse crate::boxed::Box; 7462306a36Sopenharmony_ciuse crate::collections::{TryReserveError, TryReserveErrorKind}; 7562306a36Sopenharmony_ciuse crate::raw_vec::RawVec; 7662306a36Sopenharmony_ci 7762306a36Sopenharmony_ci#[unstable(feature = "extract_if", reason = "recently added", issue = "43244")] 7862306a36Sopenharmony_cipub use self::extract_if::ExtractIf; 7962306a36Sopenharmony_ci 8062306a36Sopenharmony_cimod extract_if; 8162306a36Sopenharmony_ci 8262306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 8362306a36Sopenharmony_ci#[stable(feature = "vec_splice", since = "1.21.0")] 8462306a36Sopenharmony_cipub use self::splice::Splice; 8562306a36Sopenharmony_ci 8662306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 8762306a36Sopenharmony_cimod splice; 8862306a36Sopenharmony_ci 8962306a36Sopenharmony_ci#[stable(feature = "drain", since = "1.6.0")] 9062306a36Sopenharmony_cipub use self::drain::Drain; 9162306a36Sopenharmony_ci 9262306a36Sopenharmony_cimod drain; 9362306a36Sopenharmony_ci 9462306a36Sopenharmony_ci#[cfg(not(no_borrow))] 9562306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 9662306a36Sopenharmony_cimod cow; 9762306a36Sopenharmony_ci 9862306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 9962306a36Sopenharmony_cipub(crate) use self::in_place_collect::AsVecIntoIter; 10062306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 10162306a36Sopenharmony_cipub use self::into_iter::IntoIter; 10262306a36Sopenharmony_ci 10362306a36Sopenharmony_cimod into_iter; 10462306a36Sopenharmony_ci 10562306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 10662306a36Sopenharmony_ciuse self::is_zero::IsZero; 10762306a36Sopenharmony_ci 10862306a36Sopenharmony_cimod is_zero; 10962306a36Sopenharmony_ci 11062306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 11162306a36Sopenharmony_cimod in_place_collect; 11262306a36Sopenharmony_ci 11362306a36Sopenharmony_cimod partial_eq; 11462306a36Sopenharmony_ci 11562306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 11662306a36Sopenharmony_ciuse self::spec_from_elem::SpecFromElem; 11762306a36Sopenharmony_ci 11862306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 11962306a36Sopenharmony_cimod spec_from_elem; 12062306a36Sopenharmony_ci 12162306a36Sopenharmony_ciuse self::set_len_on_drop::SetLenOnDrop; 12262306a36Sopenharmony_ci 12362306a36Sopenharmony_cimod set_len_on_drop; 12462306a36Sopenharmony_ci 12562306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 12662306a36Sopenharmony_ciuse self::in_place_drop::{InPlaceDrop, InPlaceDstBufDrop}; 12762306a36Sopenharmony_ci 12862306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 12962306a36Sopenharmony_cimod in_place_drop; 13062306a36Sopenharmony_ci 13162306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 13262306a36Sopenharmony_ciuse self::spec_from_iter_nested::SpecFromIterNested; 13362306a36Sopenharmony_ci 13462306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 13562306a36Sopenharmony_cimod spec_from_iter_nested; 13662306a36Sopenharmony_ci 13762306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 13862306a36Sopenharmony_ciuse self::spec_from_iter::SpecFromIter; 13962306a36Sopenharmony_ci 14062306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 14162306a36Sopenharmony_cimod spec_from_iter; 14262306a36Sopenharmony_ci 14362306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 14462306a36Sopenharmony_ciuse self::spec_extend::SpecExtend; 14562306a36Sopenharmony_ci 14662306a36Sopenharmony_ciuse self::spec_extend::TrySpecExtend; 14762306a36Sopenharmony_ci 14862306a36Sopenharmony_cimod spec_extend; 14962306a36Sopenharmony_ci 15062306a36Sopenharmony_ci/// A contiguous growable array type, written as `Vec<T>`, short for 'vector'. 15162306a36Sopenharmony_ci/// 15262306a36Sopenharmony_ci/// # Examples 15362306a36Sopenharmony_ci/// 15462306a36Sopenharmony_ci/// ``` 15562306a36Sopenharmony_ci/// let mut vec = Vec::new(); 15662306a36Sopenharmony_ci/// vec.push(1); 15762306a36Sopenharmony_ci/// vec.push(2); 15862306a36Sopenharmony_ci/// 15962306a36Sopenharmony_ci/// assert_eq!(vec.len(), 2); 16062306a36Sopenharmony_ci/// assert_eq!(vec[0], 1); 16162306a36Sopenharmony_ci/// 16262306a36Sopenharmony_ci/// assert_eq!(vec.pop(), Some(2)); 16362306a36Sopenharmony_ci/// assert_eq!(vec.len(), 1); 16462306a36Sopenharmony_ci/// 16562306a36Sopenharmony_ci/// vec[0] = 7; 16662306a36Sopenharmony_ci/// assert_eq!(vec[0], 7); 16762306a36Sopenharmony_ci/// 16862306a36Sopenharmony_ci/// vec.extend([1, 2, 3]); 16962306a36Sopenharmony_ci/// 17062306a36Sopenharmony_ci/// for x in &vec { 17162306a36Sopenharmony_ci/// println!("{x}"); 17262306a36Sopenharmony_ci/// } 17362306a36Sopenharmony_ci/// assert_eq!(vec, [7, 1, 2, 3]); 17462306a36Sopenharmony_ci/// ``` 17562306a36Sopenharmony_ci/// 17662306a36Sopenharmony_ci/// The [`vec!`] macro is provided for convenient initialization: 17762306a36Sopenharmony_ci/// 17862306a36Sopenharmony_ci/// ``` 17962306a36Sopenharmony_ci/// let mut vec1 = vec![1, 2, 3]; 18062306a36Sopenharmony_ci/// vec1.push(4); 18162306a36Sopenharmony_ci/// let vec2 = Vec::from([1, 2, 3, 4]); 18262306a36Sopenharmony_ci/// assert_eq!(vec1, vec2); 18362306a36Sopenharmony_ci/// ``` 18462306a36Sopenharmony_ci/// 18562306a36Sopenharmony_ci/// It can also initialize each element of a `Vec<T>` with a given value. 18662306a36Sopenharmony_ci/// This may be more efficient than performing allocation and initialization 18762306a36Sopenharmony_ci/// in separate steps, especially when initializing a vector of zeros: 18862306a36Sopenharmony_ci/// 18962306a36Sopenharmony_ci/// ``` 19062306a36Sopenharmony_ci/// let vec = vec![0; 5]; 19162306a36Sopenharmony_ci/// assert_eq!(vec, [0, 0, 0, 0, 0]); 19262306a36Sopenharmony_ci/// 19362306a36Sopenharmony_ci/// // The following is equivalent, but potentially slower: 19462306a36Sopenharmony_ci/// let mut vec = Vec::with_capacity(5); 19562306a36Sopenharmony_ci/// vec.resize(5, 0); 19662306a36Sopenharmony_ci/// assert_eq!(vec, [0, 0, 0, 0, 0]); 19762306a36Sopenharmony_ci/// ``` 19862306a36Sopenharmony_ci/// 19962306a36Sopenharmony_ci/// For more information, see 20062306a36Sopenharmony_ci/// [Capacity and Reallocation](#capacity-and-reallocation). 20162306a36Sopenharmony_ci/// 20262306a36Sopenharmony_ci/// Use a `Vec<T>` as an efficient stack: 20362306a36Sopenharmony_ci/// 20462306a36Sopenharmony_ci/// ``` 20562306a36Sopenharmony_ci/// let mut stack = Vec::new(); 20662306a36Sopenharmony_ci/// 20762306a36Sopenharmony_ci/// stack.push(1); 20862306a36Sopenharmony_ci/// stack.push(2); 20962306a36Sopenharmony_ci/// stack.push(3); 21062306a36Sopenharmony_ci/// 21162306a36Sopenharmony_ci/// while let Some(top) = stack.pop() { 21262306a36Sopenharmony_ci/// // Prints 3, 2, 1 21362306a36Sopenharmony_ci/// println!("{top}"); 21462306a36Sopenharmony_ci/// } 21562306a36Sopenharmony_ci/// ``` 21662306a36Sopenharmony_ci/// 21762306a36Sopenharmony_ci/// # Indexing 21862306a36Sopenharmony_ci/// 21962306a36Sopenharmony_ci/// The `Vec` type allows access to values by index, because it implements the 22062306a36Sopenharmony_ci/// [`Index`] trait. An example will be more explicit: 22162306a36Sopenharmony_ci/// 22262306a36Sopenharmony_ci/// ``` 22362306a36Sopenharmony_ci/// let v = vec![0, 2, 4, 6]; 22462306a36Sopenharmony_ci/// println!("{}", v[1]); // it will display '2' 22562306a36Sopenharmony_ci/// ``` 22662306a36Sopenharmony_ci/// 22762306a36Sopenharmony_ci/// However be careful: if you try to access an index which isn't in the `Vec`, 22862306a36Sopenharmony_ci/// your software will panic! You cannot do this: 22962306a36Sopenharmony_ci/// 23062306a36Sopenharmony_ci/// ```should_panic 23162306a36Sopenharmony_ci/// let v = vec![0, 2, 4, 6]; 23262306a36Sopenharmony_ci/// println!("{}", v[6]); // it will panic! 23362306a36Sopenharmony_ci/// ``` 23462306a36Sopenharmony_ci/// 23562306a36Sopenharmony_ci/// Use [`get`] and [`get_mut`] if you want to check whether the index is in 23662306a36Sopenharmony_ci/// the `Vec`. 23762306a36Sopenharmony_ci/// 23862306a36Sopenharmony_ci/// # Slicing 23962306a36Sopenharmony_ci/// 24062306a36Sopenharmony_ci/// A `Vec` can be mutable. On the other hand, slices are read-only objects. 24162306a36Sopenharmony_ci/// To get a [slice][prim@slice], use [`&`]. Example: 24262306a36Sopenharmony_ci/// 24362306a36Sopenharmony_ci/// ``` 24462306a36Sopenharmony_ci/// fn read_slice(slice: &[usize]) { 24562306a36Sopenharmony_ci/// // ... 24662306a36Sopenharmony_ci/// } 24762306a36Sopenharmony_ci/// 24862306a36Sopenharmony_ci/// let v = vec![0, 1]; 24962306a36Sopenharmony_ci/// read_slice(&v); 25062306a36Sopenharmony_ci/// 25162306a36Sopenharmony_ci/// // ... and that's all! 25262306a36Sopenharmony_ci/// // you can also do it like this: 25362306a36Sopenharmony_ci/// let u: &[usize] = &v; 25462306a36Sopenharmony_ci/// // or like this: 25562306a36Sopenharmony_ci/// let u: &[_] = &v; 25662306a36Sopenharmony_ci/// ``` 25762306a36Sopenharmony_ci/// 25862306a36Sopenharmony_ci/// In Rust, it's more common to pass slices as arguments rather than vectors 25962306a36Sopenharmony_ci/// when you just want to provide read access. The same goes for [`String`] and 26062306a36Sopenharmony_ci/// [`&str`]. 26162306a36Sopenharmony_ci/// 26262306a36Sopenharmony_ci/// # Capacity and reallocation 26362306a36Sopenharmony_ci/// 26462306a36Sopenharmony_ci/// The capacity of a vector is the amount of space allocated for any future 26562306a36Sopenharmony_ci/// elements that will be added onto the vector. This is not to be confused with 26662306a36Sopenharmony_ci/// the *length* of a vector, which specifies the number of actual elements 26762306a36Sopenharmony_ci/// within the vector. If a vector's length exceeds its capacity, its capacity 26862306a36Sopenharmony_ci/// will automatically be increased, but its elements will have to be 26962306a36Sopenharmony_ci/// reallocated. 27062306a36Sopenharmony_ci/// 27162306a36Sopenharmony_ci/// For example, a vector with capacity 10 and length 0 would be an empty vector 27262306a36Sopenharmony_ci/// with space for 10 more elements. Pushing 10 or fewer elements onto the 27362306a36Sopenharmony_ci/// vector will not change its capacity or cause reallocation to occur. However, 27462306a36Sopenharmony_ci/// if the vector's length is increased to 11, it will have to reallocate, which 27562306a36Sopenharmony_ci/// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`] 27662306a36Sopenharmony_ci/// whenever possible to specify how big the vector is expected to get. 27762306a36Sopenharmony_ci/// 27862306a36Sopenharmony_ci/// # Guarantees 27962306a36Sopenharmony_ci/// 28062306a36Sopenharmony_ci/// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees 28162306a36Sopenharmony_ci/// about its design. This ensures that it's as low-overhead as possible in 28262306a36Sopenharmony_ci/// the general case, and can be correctly manipulated in primitive ways 28362306a36Sopenharmony_ci/// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`. 28462306a36Sopenharmony_ci/// If additional type parameters are added (e.g., to support custom allocators), 28562306a36Sopenharmony_ci/// overriding their defaults may change the behavior. 28662306a36Sopenharmony_ci/// 28762306a36Sopenharmony_ci/// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length) 28862306a36Sopenharmony_ci/// triplet. No more, no less. The order of these fields is completely 28962306a36Sopenharmony_ci/// unspecified, and you should use the appropriate methods to modify these. 29062306a36Sopenharmony_ci/// The pointer will never be null, so this type is null-pointer-optimized. 29162306a36Sopenharmony_ci/// 29262306a36Sopenharmony_ci/// However, the pointer might not actually point to allocated memory. In particular, 29362306a36Sopenharmony_ci/// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`], 29462306a36Sopenharmony_ci/// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`] 29562306a36Sopenharmony_ci/// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized 29662306a36Sopenharmony_ci/// types inside a `Vec`, it will not allocate space for them. *Note that in this case 29762306a36Sopenharmony_ci/// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only 29862306a36Sopenharmony_ci/// if <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation 29962306a36Sopenharmony_ci/// details are very subtle --- if you intend to allocate memory using a `Vec` 30062306a36Sopenharmony_ci/// and use it for something else (either to pass to unsafe code, or to build your 30162306a36Sopenharmony_ci/// own memory-backed collection), be sure to deallocate this memory by using 30262306a36Sopenharmony_ci/// `from_raw_parts` to recover the `Vec` and then dropping it. 30362306a36Sopenharmony_ci/// 30462306a36Sopenharmony_ci/// If a `Vec` *has* allocated memory, then the memory it points to is on the heap 30562306a36Sopenharmony_ci/// (as defined by the allocator Rust is configured to use by default), and its 30662306a36Sopenharmony_ci/// pointer points to [`len`] initialized, contiguous elements in order (what 30762306a36Sopenharmony_ci/// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code> 30862306a36Sopenharmony_ci/// logically uninitialized, contiguous elements. 30962306a36Sopenharmony_ci/// 31062306a36Sopenharmony_ci/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be 31162306a36Sopenharmony_ci/// visualized as below. The top part is the `Vec` struct, it contains a 31262306a36Sopenharmony_ci/// pointer to the head of the allocation in the heap, length and capacity. 31362306a36Sopenharmony_ci/// The bottom part is the allocation on the heap, a contiguous memory block. 31462306a36Sopenharmony_ci/// 31562306a36Sopenharmony_ci/// ```text 31662306a36Sopenharmony_ci/// ptr len capacity 31762306a36Sopenharmony_ci/// +--------+--------+--------+ 31862306a36Sopenharmony_ci/// | 0x0123 | 2 | 4 | 31962306a36Sopenharmony_ci/// +--------+--------+--------+ 32062306a36Sopenharmony_ci/// | 32162306a36Sopenharmony_ci/// v 32262306a36Sopenharmony_ci/// Heap +--------+--------+--------+--------+ 32362306a36Sopenharmony_ci/// | 'a' | 'b' | uninit | uninit | 32462306a36Sopenharmony_ci/// +--------+--------+--------+--------+ 32562306a36Sopenharmony_ci/// ``` 32662306a36Sopenharmony_ci/// 32762306a36Sopenharmony_ci/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`]. 32862306a36Sopenharmony_ci/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory 32962306a36Sopenharmony_ci/// layout (including the order of fields). 33062306a36Sopenharmony_ci/// 33162306a36Sopenharmony_ci/// `Vec` will never perform a "small optimization" where elements are actually 33262306a36Sopenharmony_ci/// stored on the stack for two reasons: 33362306a36Sopenharmony_ci/// 33462306a36Sopenharmony_ci/// * It would make it more difficult for unsafe code to correctly manipulate 33562306a36Sopenharmony_ci/// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were 33662306a36Sopenharmony_ci/// only moved, and it would be more difficult to determine if a `Vec` had 33762306a36Sopenharmony_ci/// actually allocated memory. 33862306a36Sopenharmony_ci/// 33962306a36Sopenharmony_ci/// * It would penalize the general case, incurring an additional branch 34062306a36Sopenharmony_ci/// on every access. 34162306a36Sopenharmony_ci/// 34262306a36Sopenharmony_ci/// `Vec` will never automatically shrink itself, even if completely empty. This 34362306a36Sopenharmony_ci/// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec` 34462306a36Sopenharmony_ci/// and then filling it back up to the same [`len`] should incur no calls to 34562306a36Sopenharmony_ci/// the allocator. If you wish to free up unused memory, use 34662306a36Sopenharmony_ci/// [`shrink_to_fit`] or [`shrink_to`]. 34762306a36Sopenharmony_ci/// 34862306a36Sopenharmony_ci/// [`push`] and [`insert`] will never (re)allocate if the reported capacity is 34962306a36Sopenharmony_ci/// sufficient. [`push`] and [`insert`] *will* (re)allocate if 35062306a36Sopenharmony_ci/// <code>[len] == [capacity]</code>. That is, the reported capacity is completely 35162306a36Sopenharmony_ci/// accurate, and can be relied on. It can even be used to manually free the memory 35262306a36Sopenharmony_ci/// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even 35362306a36Sopenharmony_ci/// when not necessary. 35462306a36Sopenharmony_ci/// 35562306a36Sopenharmony_ci/// `Vec` does not guarantee any particular growth strategy when reallocating 35662306a36Sopenharmony_ci/// when full, nor when [`reserve`] is called. The current strategy is basic 35762306a36Sopenharmony_ci/// and it may prove desirable to use a non-constant growth factor. Whatever 35862306a36Sopenharmony_ci/// strategy is used will of course guarantee *O*(1) amortized [`push`]. 35962306a36Sopenharmony_ci/// 36062306a36Sopenharmony_ci/// `vec![x; n]`, `vec![a, b, c, d]`, and 36162306a36Sopenharmony_ci/// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec` 36262306a36Sopenharmony_ci/// with exactly the requested capacity. If <code>[len] == [capacity]</code>, 36362306a36Sopenharmony_ci/// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to 36462306a36Sopenharmony_ci/// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements. 36562306a36Sopenharmony_ci/// 36662306a36Sopenharmony_ci/// `Vec` will not specifically overwrite any data that is removed from it, 36762306a36Sopenharmony_ci/// but also won't specifically preserve it. Its uninitialized memory is 36862306a36Sopenharmony_ci/// scratch space that it may use however it wants. It will generally just do 36962306a36Sopenharmony_ci/// whatever is most efficient or otherwise easy to implement. Do not rely on 37062306a36Sopenharmony_ci/// removed data to be erased for security purposes. Even if you drop a `Vec`, its 37162306a36Sopenharmony_ci/// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory 37262306a36Sopenharmony_ci/// first, that might not actually happen because the optimizer does not consider 37362306a36Sopenharmony_ci/// this a side-effect that must be preserved. There is one case which we will 37462306a36Sopenharmony_ci/// not break, however: using `unsafe` code to write to the excess capacity, 37562306a36Sopenharmony_ci/// and then increasing the length to match, is always valid. 37662306a36Sopenharmony_ci/// 37762306a36Sopenharmony_ci/// Currently, `Vec` does not guarantee the order in which elements are dropped. 37862306a36Sopenharmony_ci/// The order has changed in the past and may change again. 37962306a36Sopenharmony_ci/// 38062306a36Sopenharmony_ci/// [`get`]: slice::get 38162306a36Sopenharmony_ci/// [`get_mut`]: slice::get_mut 38262306a36Sopenharmony_ci/// [`String`]: crate::string::String 38362306a36Sopenharmony_ci/// [`&str`]: type@str 38462306a36Sopenharmony_ci/// [`shrink_to_fit`]: Vec::shrink_to_fit 38562306a36Sopenharmony_ci/// [`shrink_to`]: Vec::shrink_to 38662306a36Sopenharmony_ci/// [capacity]: Vec::capacity 38762306a36Sopenharmony_ci/// [`capacity`]: Vec::capacity 38862306a36Sopenharmony_ci/// [mem::size_of::\<T>]: core::mem::size_of 38962306a36Sopenharmony_ci/// [len]: Vec::len 39062306a36Sopenharmony_ci/// [`len`]: Vec::len 39162306a36Sopenharmony_ci/// [`push`]: Vec::push 39262306a36Sopenharmony_ci/// [`insert`]: Vec::insert 39362306a36Sopenharmony_ci/// [`reserve`]: Vec::reserve 39462306a36Sopenharmony_ci/// [`MaybeUninit`]: core::mem::MaybeUninit 39562306a36Sopenharmony_ci/// [owned slice]: Box 39662306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 39762306a36Sopenharmony_ci#[cfg_attr(not(test), rustc_diagnostic_item = "Vec")] 39862306a36Sopenharmony_ci#[rustc_insignificant_dtor] 39962306a36Sopenharmony_cipub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> { 40062306a36Sopenharmony_ci buf: RawVec<T, A>, 40162306a36Sopenharmony_ci len: usize, 40262306a36Sopenharmony_ci} 40362306a36Sopenharmony_ci 40462306a36Sopenharmony_ci//////////////////////////////////////////////////////////////////////////////// 40562306a36Sopenharmony_ci// Inherent methods 40662306a36Sopenharmony_ci//////////////////////////////////////////////////////////////////////////////// 40762306a36Sopenharmony_ci 40862306a36Sopenharmony_ciimpl<T> Vec<T> { 40962306a36Sopenharmony_ci /// Constructs a new, empty `Vec<T>`. 41062306a36Sopenharmony_ci /// 41162306a36Sopenharmony_ci /// The vector will not allocate until elements are pushed onto it. 41262306a36Sopenharmony_ci /// 41362306a36Sopenharmony_ci /// # Examples 41462306a36Sopenharmony_ci /// 41562306a36Sopenharmony_ci /// ``` 41662306a36Sopenharmony_ci /// # #![allow(unused_mut)] 41762306a36Sopenharmony_ci /// let mut vec: Vec<i32> = Vec::new(); 41862306a36Sopenharmony_ci /// ``` 41962306a36Sopenharmony_ci #[inline] 42062306a36Sopenharmony_ci #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] 42162306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 42262306a36Sopenharmony_ci #[must_use] 42362306a36Sopenharmony_ci pub const fn new() -> Self { 42462306a36Sopenharmony_ci Vec { buf: RawVec::NEW, len: 0 } 42562306a36Sopenharmony_ci } 42662306a36Sopenharmony_ci 42762306a36Sopenharmony_ci /// Constructs a new, empty `Vec<T>` with at least the specified capacity. 42862306a36Sopenharmony_ci /// 42962306a36Sopenharmony_ci /// The vector will be able to hold at least `capacity` elements without 43062306a36Sopenharmony_ci /// reallocating. This method is allowed to allocate for more elements than 43162306a36Sopenharmony_ci /// `capacity`. If `capacity` is 0, the vector will not allocate. 43262306a36Sopenharmony_ci /// 43362306a36Sopenharmony_ci /// It is important to note that although the returned vector has the 43462306a36Sopenharmony_ci /// minimum *capacity* specified, the vector will have a zero *length*. For 43562306a36Sopenharmony_ci /// an explanation of the difference between length and capacity, see 43662306a36Sopenharmony_ci /// *[Capacity and reallocation]*. 43762306a36Sopenharmony_ci /// 43862306a36Sopenharmony_ci /// If it is important to know the exact allocated capacity of a `Vec`, 43962306a36Sopenharmony_ci /// always use the [`capacity`] method after construction. 44062306a36Sopenharmony_ci /// 44162306a36Sopenharmony_ci /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation 44262306a36Sopenharmony_ci /// and the capacity will always be `usize::MAX`. 44362306a36Sopenharmony_ci /// 44462306a36Sopenharmony_ci /// [Capacity and reallocation]: #capacity-and-reallocation 44562306a36Sopenharmony_ci /// [`capacity`]: Vec::capacity 44662306a36Sopenharmony_ci /// 44762306a36Sopenharmony_ci /// # Panics 44862306a36Sopenharmony_ci /// 44962306a36Sopenharmony_ci /// Panics if the new capacity exceeds `isize::MAX` bytes. 45062306a36Sopenharmony_ci /// 45162306a36Sopenharmony_ci /// # Examples 45262306a36Sopenharmony_ci /// 45362306a36Sopenharmony_ci /// ``` 45462306a36Sopenharmony_ci /// let mut vec = Vec::with_capacity(10); 45562306a36Sopenharmony_ci /// 45662306a36Sopenharmony_ci /// // The vector contains no items, even though it has capacity for more 45762306a36Sopenharmony_ci /// assert_eq!(vec.len(), 0); 45862306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 45962306a36Sopenharmony_ci /// 46062306a36Sopenharmony_ci /// // These are all done without reallocating... 46162306a36Sopenharmony_ci /// for i in 0..10 { 46262306a36Sopenharmony_ci /// vec.push(i); 46362306a36Sopenharmony_ci /// } 46462306a36Sopenharmony_ci /// assert_eq!(vec.len(), 10); 46562306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 46662306a36Sopenharmony_ci /// 46762306a36Sopenharmony_ci /// // ...but this may make the vector reallocate 46862306a36Sopenharmony_ci /// vec.push(11); 46962306a36Sopenharmony_ci /// assert_eq!(vec.len(), 11); 47062306a36Sopenharmony_ci /// assert!(vec.capacity() >= 11); 47162306a36Sopenharmony_ci /// 47262306a36Sopenharmony_ci /// // A vector of a zero-sized type will always over-allocate, since no 47362306a36Sopenharmony_ci /// // allocation is necessary 47462306a36Sopenharmony_ci /// let vec_units = Vec::<()>::with_capacity(10); 47562306a36Sopenharmony_ci /// assert_eq!(vec_units.capacity(), usize::MAX); 47662306a36Sopenharmony_ci /// ``` 47762306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 47862306a36Sopenharmony_ci #[inline] 47962306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 48062306a36Sopenharmony_ci #[must_use] 48162306a36Sopenharmony_ci pub fn with_capacity(capacity: usize) -> Self { 48262306a36Sopenharmony_ci Self::with_capacity_in(capacity, Global) 48362306a36Sopenharmony_ci } 48462306a36Sopenharmony_ci 48562306a36Sopenharmony_ci /// Tries to construct a new, empty `Vec<T>` with at least the specified capacity. 48662306a36Sopenharmony_ci /// 48762306a36Sopenharmony_ci /// The vector will be able to hold at least `capacity` elements without 48862306a36Sopenharmony_ci /// reallocating. This method is allowed to allocate for more elements than 48962306a36Sopenharmony_ci /// `capacity`. If `capacity` is 0, the vector will not allocate. 49062306a36Sopenharmony_ci /// 49162306a36Sopenharmony_ci /// It is important to note that although the returned vector has the 49262306a36Sopenharmony_ci /// minimum *capacity* specified, the vector will have a zero *length*. For 49362306a36Sopenharmony_ci /// an explanation of the difference between length and capacity, see 49462306a36Sopenharmony_ci /// *[Capacity and reallocation]*. 49562306a36Sopenharmony_ci /// 49662306a36Sopenharmony_ci /// If it is important to know the exact allocated capacity of a `Vec`, 49762306a36Sopenharmony_ci /// always use the [`capacity`] method after construction. 49862306a36Sopenharmony_ci /// 49962306a36Sopenharmony_ci /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation 50062306a36Sopenharmony_ci /// and the capacity will always be `usize::MAX`. 50162306a36Sopenharmony_ci /// 50262306a36Sopenharmony_ci /// [Capacity and reallocation]: #capacity-and-reallocation 50362306a36Sopenharmony_ci /// [`capacity`]: Vec::capacity 50462306a36Sopenharmony_ci /// 50562306a36Sopenharmony_ci /// # Examples 50662306a36Sopenharmony_ci /// 50762306a36Sopenharmony_ci /// ``` 50862306a36Sopenharmony_ci /// let mut vec = Vec::try_with_capacity(10).unwrap(); 50962306a36Sopenharmony_ci /// 51062306a36Sopenharmony_ci /// // The vector contains no items, even though it has capacity for more 51162306a36Sopenharmony_ci /// assert_eq!(vec.len(), 0); 51262306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 51362306a36Sopenharmony_ci /// 51462306a36Sopenharmony_ci /// // These are all done without reallocating... 51562306a36Sopenharmony_ci /// for i in 0..10 { 51662306a36Sopenharmony_ci /// vec.push(i); 51762306a36Sopenharmony_ci /// } 51862306a36Sopenharmony_ci /// assert_eq!(vec.len(), 10); 51962306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 52062306a36Sopenharmony_ci /// 52162306a36Sopenharmony_ci /// // ...but this may make the vector reallocate 52262306a36Sopenharmony_ci /// vec.push(11); 52362306a36Sopenharmony_ci /// assert_eq!(vec.len(), 11); 52462306a36Sopenharmony_ci /// assert!(vec.capacity() >= 11); 52562306a36Sopenharmony_ci /// 52662306a36Sopenharmony_ci /// let mut result = Vec::try_with_capacity(usize::MAX); 52762306a36Sopenharmony_ci /// assert!(result.is_err()); 52862306a36Sopenharmony_ci /// 52962306a36Sopenharmony_ci /// // A vector of a zero-sized type will always over-allocate, since no 53062306a36Sopenharmony_ci /// // allocation is necessary 53162306a36Sopenharmony_ci /// let vec_units = Vec::<()>::try_with_capacity(10).unwrap(); 53262306a36Sopenharmony_ci /// assert_eq!(vec_units.capacity(), usize::MAX); 53362306a36Sopenharmony_ci /// ``` 53462306a36Sopenharmony_ci #[inline] 53562306a36Sopenharmony_ci #[stable(feature = "kernel", since = "1.0.0")] 53662306a36Sopenharmony_ci pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> { 53762306a36Sopenharmony_ci Self::try_with_capacity_in(capacity, Global) 53862306a36Sopenharmony_ci } 53962306a36Sopenharmony_ci 54062306a36Sopenharmony_ci /// Creates a `Vec<T>` directly from a pointer, a capacity, and a length. 54162306a36Sopenharmony_ci /// 54262306a36Sopenharmony_ci /// # Safety 54362306a36Sopenharmony_ci /// 54462306a36Sopenharmony_ci /// This is highly unsafe, due to the number of invariants that aren't 54562306a36Sopenharmony_ci /// checked: 54662306a36Sopenharmony_ci /// 54762306a36Sopenharmony_ci /// * `ptr` must have been allocated using the global allocator, such as via 54862306a36Sopenharmony_ci /// the [`alloc::alloc`] function. 54962306a36Sopenharmony_ci /// * `T` needs to have the same alignment as what `ptr` was allocated with. 55062306a36Sopenharmony_ci /// (`T` having a less strict alignment is not sufficient, the alignment really 55162306a36Sopenharmony_ci /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be 55262306a36Sopenharmony_ci /// allocated and deallocated with the same layout.) 55362306a36Sopenharmony_ci /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs 55462306a36Sopenharmony_ci /// to be the same size as the pointer was allocated with. (Because similar to 55562306a36Sopenharmony_ci /// alignment, [`dealloc`] must be called with the same layout `size`.) 55662306a36Sopenharmony_ci /// * `length` needs to be less than or equal to `capacity`. 55762306a36Sopenharmony_ci /// * The first `length` values must be properly initialized values of type `T`. 55862306a36Sopenharmony_ci /// * `capacity` needs to be the capacity that the pointer was allocated with. 55962306a36Sopenharmony_ci /// * The allocated size in bytes must be no larger than `isize::MAX`. 56062306a36Sopenharmony_ci /// See the safety documentation of [`pointer::offset`]. 56162306a36Sopenharmony_ci /// 56262306a36Sopenharmony_ci /// These requirements are always upheld by any `ptr` that has been allocated 56362306a36Sopenharmony_ci /// via `Vec<T>`. Other allocation sources are allowed if the invariants are 56462306a36Sopenharmony_ci /// upheld. 56562306a36Sopenharmony_ci /// 56662306a36Sopenharmony_ci /// Violating these may cause problems like corrupting the allocator's 56762306a36Sopenharmony_ci /// internal data structures. For example it is normally **not** safe 56862306a36Sopenharmony_ci /// to build a `Vec<u8>` from a pointer to a C `char` array with length 56962306a36Sopenharmony_ci /// `size_t`, doing so is only safe if the array was initially allocated by 57062306a36Sopenharmony_ci /// a `Vec` or `String`. 57162306a36Sopenharmony_ci /// It's also not safe to build one from a `Vec<u16>` and its length, because 57262306a36Sopenharmony_ci /// the allocator cares about the alignment, and these two types have different 57362306a36Sopenharmony_ci /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after 57462306a36Sopenharmony_ci /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid 57562306a36Sopenharmony_ci /// these issues, it is often preferable to do casting/transmuting using 57662306a36Sopenharmony_ci /// [`slice::from_raw_parts`] instead. 57762306a36Sopenharmony_ci /// 57862306a36Sopenharmony_ci /// The ownership of `ptr` is effectively transferred to the 57962306a36Sopenharmony_ci /// `Vec<T>` which may then deallocate, reallocate or change the 58062306a36Sopenharmony_ci /// contents of memory pointed to by the pointer at will. Ensure 58162306a36Sopenharmony_ci /// that nothing else uses the pointer after calling this 58262306a36Sopenharmony_ci /// function. 58362306a36Sopenharmony_ci /// 58462306a36Sopenharmony_ci /// [`String`]: crate::string::String 58562306a36Sopenharmony_ci /// [`alloc::alloc`]: crate::alloc::alloc 58662306a36Sopenharmony_ci /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc 58762306a36Sopenharmony_ci /// 58862306a36Sopenharmony_ci /// # Examples 58962306a36Sopenharmony_ci /// 59062306a36Sopenharmony_ci /// ``` 59162306a36Sopenharmony_ci /// use std::ptr; 59262306a36Sopenharmony_ci /// use std::mem; 59362306a36Sopenharmony_ci /// 59462306a36Sopenharmony_ci /// let v = vec![1, 2, 3]; 59562306a36Sopenharmony_ci /// 59662306a36Sopenharmony_ci // FIXME Update this when vec_into_raw_parts is stabilized 59762306a36Sopenharmony_ci /// // Prevent running `v`'s destructor so we are in complete control 59862306a36Sopenharmony_ci /// // of the allocation. 59962306a36Sopenharmony_ci /// let mut v = mem::ManuallyDrop::new(v); 60062306a36Sopenharmony_ci /// 60162306a36Sopenharmony_ci /// // Pull out the various important pieces of information about `v` 60262306a36Sopenharmony_ci /// let p = v.as_mut_ptr(); 60362306a36Sopenharmony_ci /// let len = v.len(); 60462306a36Sopenharmony_ci /// let cap = v.capacity(); 60562306a36Sopenharmony_ci /// 60662306a36Sopenharmony_ci /// unsafe { 60762306a36Sopenharmony_ci /// // Overwrite memory with 4, 5, 6 60862306a36Sopenharmony_ci /// for i in 0..len { 60962306a36Sopenharmony_ci /// ptr::write(p.add(i), 4 + i); 61062306a36Sopenharmony_ci /// } 61162306a36Sopenharmony_ci /// 61262306a36Sopenharmony_ci /// // Put everything back together into a Vec 61362306a36Sopenharmony_ci /// let rebuilt = Vec::from_raw_parts(p, len, cap); 61462306a36Sopenharmony_ci /// assert_eq!(rebuilt, [4, 5, 6]); 61562306a36Sopenharmony_ci /// } 61662306a36Sopenharmony_ci /// ``` 61762306a36Sopenharmony_ci /// 61862306a36Sopenharmony_ci /// Using memory that was allocated elsewhere: 61962306a36Sopenharmony_ci /// 62062306a36Sopenharmony_ci /// ```rust 62162306a36Sopenharmony_ci /// use std::alloc::{alloc, Layout}; 62262306a36Sopenharmony_ci /// 62362306a36Sopenharmony_ci /// fn main() { 62462306a36Sopenharmony_ci /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen"); 62562306a36Sopenharmony_ci /// 62662306a36Sopenharmony_ci /// let vec = unsafe { 62762306a36Sopenharmony_ci /// let mem = alloc(layout).cast::<u32>(); 62862306a36Sopenharmony_ci /// if mem.is_null() { 62962306a36Sopenharmony_ci /// return; 63062306a36Sopenharmony_ci /// } 63162306a36Sopenharmony_ci /// 63262306a36Sopenharmony_ci /// mem.write(1_000_000); 63362306a36Sopenharmony_ci /// 63462306a36Sopenharmony_ci /// Vec::from_raw_parts(mem, 1, 16) 63562306a36Sopenharmony_ci /// }; 63662306a36Sopenharmony_ci /// 63762306a36Sopenharmony_ci /// assert_eq!(vec, &[1_000_000]); 63862306a36Sopenharmony_ci /// assert_eq!(vec.capacity(), 16); 63962306a36Sopenharmony_ci /// } 64062306a36Sopenharmony_ci /// ``` 64162306a36Sopenharmony_ci #[inline] 64262306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 64362306a36Sopenharmony_ci pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { 64462306a36Sopenharmony_ci unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) } 64562306a36Sopenharmony_ci } 64662306a36Sopenharmony_ci} 64762306a36Sopenharmony_ci 64862306a36Sopenharmony_ciimpl<T, A: Allocator> Vec<T, A> { 64962306a36Sopenharmony_ci /// Constructs a new, empty `Vec<T, A>`. 65062306a36Sopenharmony_ci /// 65162306a36Sopenharmony_ci /// The vector will not allocate until elements are pushed onto it. 65262306a36Sopenharmony_ci /// 65362306a36Sopenharmony_ci /// # Examples 65462306a36Sopenharmony_ci /// 65562306a36Sopenharmony_ci /// ``` 65662306a36Sopenharmony_ci /// #![feature(allocator_api)] 65762306a36Sopenharmony_ci /// 65862306a36Sopenharmony_ci /// use std::alloc::System; 65962306a36Sopenharmony_ci /// 66062306a36Sopenharmony_ci /// # #[allow(unused_mut)] 66162306a36Sopenharmony_ci /// let mut vec: Vec<i32, _> = Vec::new_in(System); 66262306a36Sopenharmony_ci /// ``` 66362306a36Sopenharmony_ci #[inline] 66462306a36Sopenharmony_ci #[unstable(feature = "allocator_api", issue = "32838")] 66562306a36Sopenharmony_ci pub const fn new_in(alloc: A) -> Self { 66662306a36Sopenharmony_ci Vec { buf: RawVec::new_in(alloc), len: 0 } 66762306a36Sopenharmony_ci } 66862306a36Sopenharmony_ci 66962306a36Sopenharmony_ci /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity 67062306a36Sopenharmony_ci /// with the provided allocator. 67162306a36Sopenharmony_ci /// 67262306a36Sopenharmony_ci /// The vector will be able to hold at least `capacity` elements without 67362306a36Sopenharmony_ci /// reallocating. This method is allowed to allocate for more elements than 67462306a36Sopenharmony_ci /// `capacity`. If `capacity` is 0, the vector will not allocate. 67562306a36Sopenharmony_ci /// 67662306a36Sopenharmony_ci /// It is important to note that although the returned vector has the 67762306a36Sopenharmony_ci /// minimum *capacity* specified, the vector will have a zero *length*. For 67862306a36Sopenharmony_ci /// an explanation of the difference between length and capacity, see 67962306a36Sopenharmony_ci /// *[Capacity and reallocation]*. 68062306a36Sopenharmony_ci /// 68162306a36Sopenharmony_ci /// If it is important to know the exact allocated capacity of a `Vec`, 68262306a36Sopenharmony_ci /// always use the [`capacity`] method after construction. 68362306a36Sopenharmony_ci /// 68462306a36Sopenharmony_ci /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation 68562306a36Sopenharmony_ci /// and the capacity will always be `usize::MAX`. 68662306a36Sopenharmony_ci /// 68762306a36Sopenharmony_ci /// [Capacity and reallocation]: #capacity-and-reallocation 68862306a36Sopenharmony_ci /// [`capacity`]: Vec::capacity 68962306a36Sopenharmony_ci /// 69062306a36Sopenharmony_ci /// # Panics 69162306a36Sopenharmony_ci /// 69262306a36Sopenharmony_ci /// Panics if the new capacity exceeds `isize::MAX` bytes. 69362306a36Sopenharmony_ci /// 69462306a36Sopenharmony_ci /// # Examples 69562306a36Sopenharmony_ci /// 69662306a36Sopenharmony_ci /// ``` 69762306a36Sopenharmony_ci /// #![feature(allocator_api)] 69862306a36Sopenharmony_ci /// 69962306a36Sopenharmony_ci /// use std::alloc::System; 70062306a36Sopenharmony_ci /// 70162306a36Sopenharmony_ci /// let mut vec = Vec::with_capacity_in(10, System); 70262306a36Sopenharmony_ci /// 70362306a36Sopenharmony_ci /// // The vector contains no items, even though it has capacity for more 70462306a36Sopenharmony_ci /// assert_eq!(vec.len(), 0); 70562306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 70662306a36Sopenharmony_ci /// 70762306a36Sopenharmony_ci /// // These are all done without reallocating... 70862306a36Sopenharmony_ci /// for i in 0..10 { 70962306a36Sopenharmony_ci /// vec.push(i); 71062306a36Sopenharmony_ci /// } 71162306a36Sopenharmony_ci /// assert_eq!(vec.len(), 10); 71262306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 71362306a36Sopenharmony_ci /// 71462306a36Sopenharmony_ci /// // ...but this may make the vector reallocate 71562306a36Sopenharmony_ci /// vec.push(11); 71662306a36Sopenharmony_ci /// assert_eq!(vec.len(), 11); 71762306a36Sopenharmony_ci /// assert!(vec.capacity() >= 11); 71862306a36Sopenharmony_ci /// 71962306a36Sopenharmony_ci /// // A vector of a zero-sized type will always over-allocate, since no 72062306a36Sopenharmony_ci /// // allocation is necessary 72162306a36Sopenharmony_ci /// let vec_units = Vec::<(), System>::with_capacity_in(10, System); 72262306a36Sopenharmony_ci /// assert_eq!(vec_units.capacity(), usize::MAX); 72362306a36Sopenharmony_ci /// ``` 72462306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 72562306a36Sopenharmony_ci #[inline] 72662306a36Sopenharmony_ci #[unstable(feature = "allocator_api", issue = "32838")] 72762306a36Sopenharmony_ci pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 72862306a36Sopenharmony_ci Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } 72962306a36Sopenharmony_ci } 73062306a36Sopenharmony_ci 73162306a36Sopenharmony_ci /// Tries to construct a new, empty `Vec<T, A>` with at least the specified capacity 73262306a36Sopenharmony_ci /// with the provided allocator. 73362306a36Sopenharmony_ci /// 73462306a36Sopenharmony_ci /// The vector will be able to hold at least `capacity` elements without 73562306a36Sopenharmony_ci /// reallocating. This method is allowed to allocate for more elements than 73662306a36Sopenharmony_ci /// `capacity`. If `capacity` is 0, the vector will not allocate. 73762306a36Sopenharmony_ci /// 73862306a36Sopenharmony_ci /// It is important to note that although the returned vector has the 73962306a36Sopenharmony_ci /// minimum *capacity* specified, the vector will have a zero *length*. For 74062306a36Sopenharmony_ci /// an explanation of the difference between length and capacity, see 74162306a36Sopenharmony_ci /// *[Capacity and reallocation]*. 74262306a36Sopenharmony_ci /// 74362306a36Sopenharmony_ci /// If it is important to know the exact allocated capacity of a `Vec`, 74462306a36Sopenharmony_ci /// always use the [`capacity`] method after construction. 74562306a36Sopenharmony_ci /// 74662306a36Sopenharmony_ci /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation 74762306a36Sopenharmony_ci /// and the capacity will always be `usize::MAX`. 74862306a36Sopenharmony_ci /// 74962306a36Sopenharmony_ci /// [Capacity and reallocation]: #capacity-and-reallocation 75062306a36Sopenharmony_ci /// [`capacity`]: Vec::capacity 75162306a36Sopenharmony_ci /// 75262306a36Sopenharmony_ci /// # Examples 75362306a36Sopenharmony_ci /// 75462306a36Sopenharmony_ci /// ``` 75562306a36Sopenharmony_ci /// #![feature(allocator_api)] 75662306a36Sopenharmony_ci /// 75762306a36Sopenharmony_ci /// use std::alloc::System; 75862306a36Sopenharmony_ci /// 75962306a36Sopenharmony_ci /// let mut vec = Vec::try_with_capacity_in(10, System).unwrap(); 76062306a36Sopenharmony_ci /// 76162306a36Sopenharmony_ci /// // The vector contains no items, even though it has capacity for more 76262306a36Sopenharmony_ci /// assert_eq!(vec.len(), 0); 76362306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 76462306a36Sopenharmony_ci /// 76562306a36Sopenharmony_ci /// // These are all done without reallocating... 76662306a36Sopenharmony_ci /// for i in 0..10 { 76762306a36Sopenharmony_ci /// vec.push(i); 76862306a36Sopenharmony_ci /// } 76962306a36Sopenharmony_ci /// assert_eq!(vec.len(), 10); 77062306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 77162306a36Sopenharmony_ci /// 77262306a36Sopenharmony_ci /// // ...but this may make the vector reallocate 77362306a36Sopenharmony_ci /// vec.push(11); 77462306a36Sopenharmony_ci /// assert_eq!(vec.len(), 11); 77562306a36Sopenharmony_ci /// assert!(vec.capacity() >= 11); 77662306a36Sopenharmony_ci /// 77762306a36Sopenharmony_ci /// let mut result = Vec::try_with_capacity_in(usize::MAX, System); 77862306a36Sopenharmony_ci /// assert!(result.is_err()); 77962306a36Sopenharmony_ci /// 78062306a36Sopenharmony_ci /// // A vector of a zero-sized type will always over-allocate, since no 78162306a36Sopenharmony_ci /// // allocation is necessary 78262306a36Sopenharmony_ci /// let vec_units = Vec::<(), System>::try_with_capacity_in(10, System).unwrap(); 78362306a36Sopenharmony_ci /// assert_eq!(vec_units.capacity(), usize::MAX); 78462306a36Sopenharmony_ci /// ``` 78562306a36Sopenharmony_ci #[inline] 78662306a36Sopenharmony_ci #[stable(feature = "kernel", since = "1.0.0")] 78762306a36Sopenharmony_ci pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> { 78862306a36Sopenharmony_ci Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 }) 78962306a36Sopenharmony_ci } 79062306a36Sopenharmony_ci 79162306a36Sopenharmony_ci /// Creates a `Vec<T, A>` directly from a pointer, a capacity, a length, 79262306a36Sopenharmony_ci /// and an allocator. 79362306a36Sopenharmony_ci /// 79462306a36Sopenharmony_ci /// # Safety 79562306a36Sopenharmony_ci /// 79662306a36Sopenharmony_ci /// This is highly unsafe, due to the number of invariants that aren't 79762306a36Sopenharmony_ci /// checked: 79862306a36Sopenharmony_ci /// 79962306a36Sopenharmony_ci /// * `ptr` must be [*currently allocated*] via the given allocator `alloc`. 80062306a36Sopenharmony_ci /// * `T` needs to have the same alignment as what `ptr` was allocated with. 80162306a36Sopenharmony_ci /// (`T` having a less strict alignment is not sufficient, the alignment really 80262306a36Sopenharmony_ci /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be 80362306a36Sopenharmony_ci /// allocated and deallocated with the same layout.) 80462306a36Sopenharmony_ci /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs 80562306a36Sopenharmony_ci /// to be the same size as the pointer was allocated with. (Because similar to 80662306a36Sopenharmony_ci /// alignment, [`dealloc`] must be called with the same layout `size`.) 80762306a36Sopenharmony_ci /// * `length` needs to be less than or equal to `capacity`. 80862306a36Sopenharmony_ci /// * The first `length` values must be properly initialized values of type `T`. 80962306a36Sopenharmony_ci /// * `capacity` needs to [*fit*] the layout size that the pointer was allocated with. 81062306a36Sopenharmony_ci /// * The allocated size in bytes must be no larger than `isize::MAX`. 81162306a36Sopenharmony_ci /// See the safety documentation of [`pointer::offset`]. 81262306a36Sopenharmony_ci /// 81362306a36Sopenharmony_ci /// These requirements are always upheld by any `ptr` that has been allocated 81462306a36Sopenharmony_ci /// via `Vec<T, A>`. Other allocation sources are allowed if the invariants are 81562306a36Sopenharmony_ci /// upheld. 81662306a36Sopenharmony_ci /// 81762306a36Sopenharmony_ci /// Violating these may cause problems like corrupting the allocator's 81862306a36Sopenharmony_ci /// internal data structures. For example it is **not** safe 81962306a36Sopenharmony_ci /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`. 82062306a36Sopenharmony_ci /// It's also not safe to build one from a `Vec<u16>` and its length, because 82162306a36Sopenharmony_ci /// the allocator cares about the alignment, and these two types have different 82262306a36Sopenharmony_ci /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after 82362306a36Sopenharmony_ci /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. 82462306a36Sopenharmony_ci /// 82562306a36Sopenharmony_ci /// The ownership of `ptr` is effectively transferred to the 82662306a36Sopenharmony_ci /// `Vec<T>` which may then deallocate, reallocate or change the 82762306a36Sopenharmony_ci /// contents of memory pointed to by the pointer at will. Ensure 82862306a36Sopenharmony_ci /// that nothing else uses the pointer after calling this 82962306a36Sopenharmony_ci /// function. 83062306a36Sopenharmony_ci /// 83162306a36Sopenharmony_ci /// [`String`]: crate::string::String 83262306a36Sopenharmony_ci /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc 83362306a36Sopenharmony_ci /// [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory 83462306a36Sopenharmony_ci /// [*fit*]: crate::alloc::Allocator#memory-fitting 83562306a36Sopenharmony_ci /// 83662306a36Sopenharmony_ci /// # Examples 83762306a36Sopenharmony_ci /// 83862306a36Sopenharmony_ci /// ``` 83962306a36Sopenharmony_ci /// #![feature(allocator_api)] 84062306a36Sopenharmony_ci /// 84162306a36Sopenharmony_ci /// use std::alloc::System; 84262306a36Sopenharmony_ci /// 84362306a36Sopenharmony_ci /// use std::ptr; 84462306a36Sopenharmony_ci /// use std::mem; 84562306a36Sopenharmony_ci /// 84662306a36Sopenharmony_ci /// let mut v = Vec::with_capacity_in(3, System); 84762306a36Sopenharmony_ci /// v.push(1); 84862306a36Sopenharmony_ci /// v.push(2); 84962306a36Sopenharmony_ci /// v.push(3); 85062306a36Sopenharmony_ci /// 85162306a36Sopenharmony_ci // FIXME Update this when vec_into_raw_parts is stabilized 85262306a36Sopenharmony_ci /// // Prevent running `v`'s destructor so we are in complete control 85362306a36Sopenharmony_ci /// // of the allocation. 85462306a36Sopenharmony_ci /// let mut v = mem::ManuallyDrop::new(v); 85562306a36Sopenharmony_ci /// 85662306a36Sopenharmony_ci /// // Pull out the various important pieces of information about `v` 85762306a36Sopenharmony_ci /// let p = v.as_mut_ptr(); 85862306a36Sopenharmony_ci /// let len = v.len(); 85962306a36Sopenharmony_ci /// let cap = v.capacity(); 86062306a36Sopenharmony_ci /// let alloc = v.allocator(); 86162306a36Sopenharmony_ci /// 86262306a36Sopenharmony_ci /// unsafe { 86362306a36Sopenharmony_ci /// // Overwrite memory with 4, 5, 6 86462306a36Sopenharmony_ci /// for i in 0..len { 86562306a36Sopenharmony_ci /// ptr::write(p.add(i), 4 + i); 86662306a36Sopenharmony_ci /// } 86762306a36Sopenharmony_ci /// 86862306a36Sopenharmony_ci /// // Put everything back together into a Vec 86962306a36Sopenharmony_ci /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); 87062306a36Sopenharmony_ci /// assert_eq!(rebuilt, [4, 5, 6]); 87162306a36Sopenharmony_ci /// } 87262306a36Sopenharmony_ci /// ``` 87362306a36Sopenharmony_ci /// 87462306a36Sopenharmony_ci /// Using memory that was allocated elsewhere: 87562306a36Sopenharmony_ci /// 87662306a36Sopenharmony_ci /// ```rust 87762306a36Sopenharmony_ci /// #![feature(allocator_api)] 87862306a36Sopenharmony_ci /// 87962306a36Sopenharmony_ci /// use std::alloc::{AllocError, Allocator, Global, Layout}; 88062306a36Sopenharmony_ci /// 88162306a36Sopenharmony_ci /// fn main() { 88262306a36Sopenharmony_ci /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen"); 88362306a36Sopenharmony_ci /// 88462306a36Sopenharmony_ci /// let vec = unsafe { 88562306a36Sopenharmony_ci /// let mem = match Global.allocate(layout) { 88662306a36Sopenharmony_ci /// Ok(mem) => mem.cast::<u32>().as_ptr(), 88762306a36Sopenharmony_ci /// Err(AllocError) => return, 88862306a36Sopenharmony_ci /// }; 88962306a36Sopenharmony_ci /// 89062306a36Sopenharmony_ci /// mem.write(1_000_000); 89162306a36Sopenharmony_ci /// 89262306a36Sopenharmony_ci /// Vec::from_raw_parts_in(mem, 1, 16, Global) 89362306a36Sopenharmony_ci /// }; 89462306a36Sopenharmony_ci /// 89562306a36Sopenharmony_ci /// assert_eq!(vec, &[1_000_000]); 89662306a36Sopenharmony_ci /// assert_eq!(vec.capacity(), 16); 89762306a36Sopenharmony_ci /// } 89862306a36Sopenharmony_ci /// ``` 89962306a36Sopenharmony_ci #[inline] 90062306a36Sopenharmony_ci #[unstable(feature = "allocator_api", issue = "32838")] 90162306a36Sopenharmony_ci pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { 90262306a36Sopenharmony_ci unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } 90362306a36Sopenharmony_ci } 90462306a36Sopenharmony_ci 90562306a36Sopenharmony_ci /// Decomposes a `Vec<T>` into its raw components. 90662306a36Sopenharmony_ci /// 90762306a36Sopenharmony_ci /// Returns the raw pointer to the underlying data, the length of 90862306a36Sopenharmony_ci /// the vector (in elements), and the allocated capacity of the 90962306a36Sopenharmony_ci /// data (in elements). These are the same arguments in the same 91062306a36Sopenharmony_ci /// order as the arguments to [`from_raw_parts`]. 91162306a36Sopenharmony_ci /// 91262306a36Sopenharmony_ci /// After calling this function, the caller is responsible for the 91362306a36Sopenharmony_ci /// memory previously managed by the `Vec`. The only way to do 91462306a36Sopenharmony_ci /// this is to convert the raw pointer, length, and capacity back 91562306a36Sopenharmony_ci /// into a `Vec` with the [`from_raw_parts`] function, allowing 91662306a36Sopenharmony_ci /// the destructor to perform the cleanup. 91762306a36Sopenharmony_ci /// 91862306a36Sopenharmony_ci /// [`from_raw_parts`]: Vec::from_raw_parts 91962306a36Sopenharmony_ci /// 92062306a36Sopenharmony_ci /// # Examples 92162306a36Sopenharmony_ci /// 92262306a36Sopenharmony_ci /// ``` 92362306a36Sopenharmony_ci /// #![feature(vec_into_raw_parts)] 92462306a36Sopenharmony_ci /// let v: Vec<i32> = vec![-1, 0, 1]; 92562306a36Sopenharmony_ci /// 92662306a36Sopenharmony_ci /// let (ptr, len, cap) = v.into_raw_parts(); 92762306a36Sopenharmony_ci /// 92862306a36Sopenharmony_ci /// let rebuilt = unsafe { 92962306a36Sopenharmony_ci /// // We can now make changes to the components, such as 93062306a36Sopenharmony_ci /// // transmuting the raw pointer to a compatible type. 93162306a36Sopenharmony_ci /// let ptr = ptr as *mut u32; 93262306a36Sopenharmony_ci /// 93362306a36Sopenharmony_ci /// Vec::from_raw_parts(ptr, len, cap) 93462306a36Sopenharmony_ci /// }; 93562306a36Sopenharmony_ci /// assert_eq!(rebuilt, [4294967295, 0, 1]); 93662306a36Sopenharmony_ci /// ``` 93762306a36Sopenharmony_ci #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] 93862306a36Sopenharmony_ci pub fn into_raw_parts(self) -> (*mut T, usize, usize) { 93962306a36Sopenharmony_ci let mut me = ManuallyDrop::new(self); 94062306a36Sopenharmony_ci (me.as_mut_ptr(), me.len(), me.capacity()) 94162306a36Sopenharmony_ci } 94262306a36Sopenharmony_ci 94362306a36Sopenharmony_ci /// Decomposes a `Vec<T>` into its raw components. 94462306a36Sopenharmony_ci /// 94562306a36Sopenharmony_ci /// Returns the raw pointer to the underlying data, the length of the vector (in elements), 94662306a36Sopenharmony_ci /// the allocated capacity of the data (in elements), and the allocator. These are the same 94762306a36Sopenharmony_ci /// arguments in the same order as the arguments to [`from_raw_parts_in`]. 94862306a36Sopenharmony_ci /// 94962306a36Sopenharmony_ci /// After calling this function, the caller is responsible for the 95062306a36Sopenharmony_ci /// memory previously managed by the `Vec`. The only way to do 95162306a36Sopenharmony_ci /// this is to convert the raw pointer, length, and capacity back 95262306a36Sopenharmony_ci /// into a `Vec` with the [`from_raw_parts_in`] function, allowing 95362306a36Sopenharmony_ci /// the destructor to perform the cleanup. 95462306a36Sopenharmony_ci /// 95562306a36Sopenharmony_ci /// [`from_raw_parts_in`]: Vec::from_raw_parts_in 95662306a36Sopenharmony_ci /// 95762306a36Sopenharmony_ci /// # Examples 95862306a36Sopenharmony_ci /// 95962306a36Sopenharmony_ci /// ``` 96062306a36Sopenharmony_ci /// #![feature(allocator_api, vec_into_raw_parts)] 96162306a36Sopenharmony_ci /// 96262306a36Sopenharmony_ci /// use std::alloc::System; 96362306a36Sopenharmony_ci /// 96462306a36Sopenharmony_ci /// let mut v: Vec<i32, System> = Vec::new_in(System); 96562306a36Sopenharmony_ci /// v.push(-1); 96662306a36Sopenharmony_ci /// v.push(0); 96762306a36Sopenharmony_ci /// v.push(1); 96862306a36Sopenharmony_ci /// 96962306a36Sopenharmony_ci /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc(); 97062306a36Sopenharmony_ci /// 97162306a36Sopenharmony_ci /// let rebuilt = unsafe { 97262306a36Sopenharmony_ci /// // We can now make changes to the components, such as 97362306a36Sopenharmony_ci /// // transmuting the raw pointer to a compatible type. 97462306a36Sopenharmony_ci /// let ptr = ptr as *mut u32; 97562306a36Sopenharmony_ci /// 97662306a36Sopenharmony_ci /// Vec::from_raw_parts_in(ptr, len, cap, alloc) 97762306a36Sopenharmony_ci /// }; 97862306a36Sopenharmony_ci /// assert_eq!(rebuilt, [4294967295, 0, 1]); 97962306a36Sopenharmony_ci /// ``` 98062306a36Sopenharmony_ci #[unstable(feature = "allocator_api", issue = "32838")] 98162306a36Sopenharmony_ci // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] 98262306a36Sopenharmony_ci pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) { 98362306a36Sopenharmony_ci let mut me = ManuallyDrop::new(self); 98462306a36Sopenharmony_ci let len = me.len(); 98562306a36Sopenharmony_ci let capacity = me.capacity(); 98662306a36Sopenharmony_ci let ptr = me.as_mut_ptr(); 98762306a36Sopenharmony_ci let alloc = unsafe { ptr::read(me.allocator()) }; 98862306a36Sopenharmony_ci (ptr, len, capacity, alloc) 98962306a36Sopenharmony_ci } 99062306a36Sopenharmony_ci 99162306a36Sopenharmony_ci /// Returns the total number of elements the vector can hold without 99262306a36Sopenharmony_ci /// reallocating. 99362306a36Sopenharmony_ci /// 99462306a36Sopenharmony_ci /// # Examples 99562306a36Sopenharmony_ci /// 99662306a36Sopenharmony_ci /// ``` 99762306a36Sopenharmony_ci /// let mut vec: Vec<i32> = Vec::with_capacity(10); 99862306a36Sopenharmony_ci /// vec.push(42); 99962306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 100062306a36Sopenharmony_ci /// ``` 100162306a36Sopenharmony_ci #[inline] 100262306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 100362306a36Sopenharmony_ci pub fn capacity(&self) -> usize { 100462306a36Sopenharmony_ci self.buf.capacity() 100562306a36Sopenharmony_ci } 100662306a36Sopenharmony_ci 100762306a36Sopenharmony_ci /// Reserves capacity for at least `additional` more elements to be inserted 100862306a36Sopenharmony_ci /// in the given `Vec<T>`. The collection may reserve more space to 100962306a36Sopenharmony_ci /// speculatively avoid frequent reallocations. After calling `reserve`, 101062306a36Sopenharmony_ci /// capacity will be greater than or equal to `self.len() + additional`. 101162306a36Sopenharmony_ci /// Does nothing if capacity is already sufficient. 101262306a36Sopenharmony_ci /// 101362306a36Sopenharmony_ci /// # Panics 101462306a36Sopenharmony_ci /// 101562306a36Sopenharmony_ci /// Panics if the new capacity exceeds `isize::MAX` bytes. 101662306a36Sopenharmony_ci /// 101762306a36Sopenharmony_ci /// # Examples 101862306a36Sopenharmony_ci /// 101962306a36Sopenharmony_ci /// ``` 102062306a36Sopenharmony_ci /// let mut vec = vec![1]; 102162306a36Sopenharmony_ci /// vec.reserve(10); 102262306a36Sopenharmony_ci /// assert!(vec.capacity() >= 11); 102362306a36Sopenharmony_ci /// ``` 102462306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 102562306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 102662306a36Sopenharmony_ci pub fn reserve(&mut self, additional: usize) { 102762306a36Sopenharmony_ci self.buf.reserve(self.len, additional); 102862306a36Sopenharmony_ci } 102962306a36Sopenharmony_ci 103062306a36Sopenharmony_ci /// Reserves the minimum capacity for at least `additional` more elements to 103162306a36Sopenharmony_ci /// be inserted in the given `Vec<T>`. Unlike [`reserve`], this will not 103262306a36Sopenharmony_ci /// deliberately over-allocate to speculatively avoid frequent allocations. 103362306a36Sopenharmony_ci /// After calling `reserve_exact`, capacity will be greater than or equal to 103462306a36Sopenharmony_ci /// `self.len() + additional`. Does nothing if the capacity is already 103562306a36Sopenharmony_ci /// sufficient. 103662306a36Sopenharmony_ci /// 103762306a36Sopenharmony_ci /// Note that the allocator may give the collection more space than it 103862306a36Sopenharmony_ci /// requests. Therefore, capacity can not be relied upon to be precisely 103962306a36Sopenharmony_ci /// minimal. Prefer [`reserve`] if future insertions are expected. 104062306a36Sopenharmony_ci /// 104162306a36Sopenharmony_ci /// [`reserve`]: Vec::reserve 104262306a36Sopenharmony_ci /// 104362306a36Sopenharmony_ci /// # Panics 104462306a36Sopenharmony_ci /// 104562306a36Sopenharmony_ci /// Panics if the new capacity exceeds `isize::MAX` bytes. 104662306a36Sopenharmony_ci /// 104762306a36Sopenharmony_ci /// # Examples 104862306a36Sopenharmony_ci /// 104962306a36Sopenharmony_ci /// ``` 105062306a36Sopenharmony_ci /// let mut vec = vec![1]; 105162306a36Sopenharmony_ci /// vec.reserve_exact(10); 105262306a36Sopenharmony_ci /// assert!(vec.capacity() >= 11); 105362306a36Sopenharmony_ci /// ``` 105462306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 105562306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 105662306a36Sopenharmony_ci pub fn reserve_exact(&mut self, additional: usize) { 105762306a36Sopenharmony_ci self.buf.reserve_exact(self.len, additional); 105862306a36Sopenharmony_ci } 105962306a36Sopenharmony_ci 106062306a36Sopenharmony_ci /// Tries to reserve capacity for at least `additional` more elements to be inserted 106162306a36Sopenharmony_ci /// in the given `Vec<T>`. The collection may reserve more space to speculatively avoid 106262306a36Sopenharmony_ci /// frequent reallocations. After calling `try_reserve`, capacity will be 106362306a36Sopenharmony_ci /// greater than or equal to `self.len() + additional` if it returns 106462306a36Sopenharmony_ci /// `Ok(())`. Does nothing if capacity is already sufficient. This method 106562306a36Sopenharmony_ci /// preserves the contents even if an error occurs. 106662306a36Sopenharmony_ci /// 106762306a36Sopenharmony_ci /// # Errors 106862306a36Sopenharmony_ci /// 106962306a36Sopenharmony_ci /// If the capacity overflows, or the allocator reports a failure, then an error 107062306a36Sopenharmony_ci /// is returned. 107162306a36Sopenharmony_ci /// 107262306a36Sopenharmony_ci /// # Examples 107362306a36Sopenharmony_ci /// 107462306a36Sopenharmony_ci /// ``` 107562306a36Sopenharmony_ci /// use std::collections::TryReserveError; 107662306a36Sopenharmony_ci /// 107762306a36Sopenharmony_ci /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> { 107862306a36Sopenharmony_ci /// let mut output = Vec::new(); 107962306a36Sopenharmony_ci /// 108062306a36Sopenharmony_ci /// // Pre-reserve the memory, exiting if we can't 108162306a36Sopenharmony_ci /// output.try_reserve(data.len())?; 108262306a36Sopenharmony_ci /// 108362306a36Sopenharmony_ci /// // Now we know this can't OOM in the middle of our complex work 108462306a36Sopenharmony_ci /// output.extend(data.iter().map(|&val| { 108562306a36Sopenharmony_ci /// val * 2 + 5 // very complicated 108662306a36Sopenharmony_ci /// })); 108762306a36Sopenharmony_ci /// 108862306a36Sopenharmony_ci /// Ok(output) 108962306a36Sopenharmony_ci /// } 109062306a36Sopenharmony_ci /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?"); 109162306a36Sopenharmony_ci /// ``` 109262306a36Sopenharmony_ci #[stable(feature = "try_reserve", since = "1.57.0")] 109362306a36Sopenharmony_ci pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { 109462306a36Sopenharmony_ci self.buf.try_reserve(self.len, additional) 109562306a36Sopenharmony_ci } 109662306a36Sopenharmony_ci 109762306a36Sopenharmony_ci /// Tries to reserve the minimum capacity for at least `additional` 109862306a36Sopenharmony_ci /// elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`], 109962306a36Sopenharmony_ci /// this will not deliberately over-allocate to speculatively avoid frequent 110062306a36Sopenharmony_ci /// allocations. After calling `try_reserve_exact`, capacity will be greater 110162306a36Sopenharmony_ci /// than or equal to `self.len() + additional` if it returns `Ok(())`. 110262306a36Sopenharmony_ci /// Does nothing if the capacity is already sufficient. 110362306a36Sopenharmony_ci /// 110462306a36Sopenharmony_ci /// Note that the allocator may give the collection more space than it 110562306a36Sopenharmony_ci /// requests. Therefore, capacity can not be relied upon to be precisely 110662306a36Sopenharmony_ci /// minimal. Prefer [`try_reserve`] if future insertions are expected. 110762306a36Sopenharmony_ci /// 110862306a36Sopenharmony_ci /// [`try_reserve`]: Vec::try_reserve 110962306a36Sopenharmony_ci /// 111062306a36Sopenharmony_ci /// # Errors 111162306a36Sopenharmony_ci /// 111262306a36Sopenharmony_ci /// If the capacity overflows, or the allocator reports a failure, then an error 111362306a36Sopenharmony_ci /// is returned. 111462306a36Sopenharmony_ci /// 111562306a36Sopenharmony_ci /// # Examples 111662306a36Sopenharmony_ci /// 111762306a36Sopenharmony_ci /// ``` 111862306a36Sopenharmony_ci /// use std::collections::TryReserveError; 111962306a36Sopenharmony_ci /// 112062306a36Sopenharmony_ci /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> { 112162306a36Sopenharmony_ci /// let mut output = Vec::new(); 112262306a36Sopenharmony_ci /// 112362306a36Sopenharmony_ci /// // Pre-reserve the memory, exiting if we can't 112462306a36Sopenharmony_ci /// output.try_reserve_exact(data.len())?; 112562306a36Sopenharmony_ci /// 112662306a36Sopenharmony_ci /// // Now we know this can't OOM in the middle of our complex work 112762306a36Sopenharmony_ci /// output.extend(data.iter().map(|&val| { 112862306a36Sopenharmony_ci /// val * 2 + 5 // very complicated 112962306a36Sopenharmony_ci /// })); 113062306a36Sopenharmony_ci /// 113162306a36Sopenharmony_ci /// Ok(output) 113262306a36Sopenharmony_ci /// } 113362306a36Sopenharmony_ci /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?"); 113462306a36Sopenharmony_ci /// ``` 113562306a36Sopenharmony_ci #[stable(feature = "try_reserve", since = "1.57.0")] 113662306a36Sopenharmony_ci pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { 113762306a36Sopenharmony_ci self.buf.try_reserve_exact(self.len, additional) 113862306a36Sopenharmony_ci } 113962306a36Sopenharmony_ci 114062306a36Sopenharmony_ci /// Shrinks the capacity of the vector as much as possible. 114162306a36Sopenharmony_ci /// 114262306a36Sopenharmony_ci /// It will drop down as close as possible to the length but the allocator 114362306a36Sopenharmony_ci /// may still inform the vector that there is space for a few more elements. 114462306a36Sopenharmony_ci /// 114562306a36Sopenharmony_ci /// # Examples 114662306a36Sopenharmony_ci /// 114762306a36Sopenharmony_ci /// ``` 114862306a36Sopenharmony_ci /// let mut vec = Vec::with_capacity(10); 114962306a36Sopenharmony_ci /// vec.extend([1, 2, 3]); 115062306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 115162306a36Sopenharmony_ci /// vec.shrink_to_fit(); 115262306a36Sopenharmony_ci /// assert!(vec.capacity() >= 3); 115362306a36Sopenharmony_ci /// ``` 115462306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 115562306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 115662306a36Sopenharmony_ci pub fn shrink_to_fit(&mut self) { 115762306a36Sopenharmony_ci // The capacity is never less than the length, and there's nothing to do when 115862306a36Sopenharmony_ci // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` 115962306a36Sopenharmony_ci // by only calling it with a greater capacity. 116062306a36Sopenharmony_ci if self.capacity() > self.len { 116162306a36Sopenharmony_ci self.buf.shrink_to_fit(self.len); 116262306a36Sopenharmony_ci } 116362306a36Sopenharmony_ci } 116462306a36Sopenharmony_ci 116562306a36Sopenharmony_ci /// Shrinks the capacity of the vector with a lower bound. 116662306a36Sopenharmony_ci /// 116762306a36Sopenharmony_ci /// The capacity will remain at least as large as both the length 116862306a36Sopenharmony_ci /// and the supplied value. 116962306a36Sopenharmony_ci /// 117062306a36Sopenharmony_ci /// If the current capacity is less than the lower limit, this is a no-op. 117162306a36Sopenharmony_ci /// 117262306a36Sopenharmony_ci /// # Examples 117362306a36Sopenharmony_ci /// 117462306a36Sopenharmony_ci /// ``` 117562306a36Sopenharmony_ci /// let mut vec = Vec::with_capacity(10); 117662306a36Sopenharmony_ci /// vec.extend([1, 2, 3]); 117762306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 117862306a36Sopenharmony_ci /// vec.shrink_to(4); 117962306a36Sopenharmony_ci /// assert!(vec.capacity() >= 4); 118062306a36Sopenharmony_ci /// vec.shrink_to(0); 118162306a36Sopenharmony_ci /// assert!(vec.capacity() >= 3); 118262306a36Sopenharmony_ci /// ``` 118362306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 118462306a36Sopenharmony_ci #[stable(feature = "shrink_to", since = "1.56.0")] 118562306a36Sopenharmony_ci pub fn shrink_to(&mut self, min_capacity: usize) { 118662306a36Sopenharmony_ci if self.capacity() > min_capacity { 118762306a36Sopenharmony_ci self.buf.shrink_to_fit(cmp::max(self.len, min_capacity)); 118862306a36Sopenharmony_ci } 118962306a36Sopenharmony_ci } 119062306a36Sopenharmony_ci 119162306a36Sopenharmony_ci /// Converts the vector into [`Box<[T]>`][owned slice]. 119262306a36Sopenharmony_ci /// 119362306a36Sopenharmony_ci /// If the vector has excess capacity, its items will be moved into a 119462306a36Sopenharmony_ci /// newly-allocated buffer with exactly the right capacity. 119562306a36Sopenharmony_ci /// 119662306a36Sopenharmony_ci /// [owned slice]: Box 119762306a36Sopenharmony_ci /// 119862306a36Sopenharmony_ci /// # Examples 119962306a36Sopenharmony_ci /// 120062306a36Sopenharmony_ci /// ``` 120162306a36Sopenharmony_ci /// let v = vec![1, 2, 3]; 120262306a36Sopenharmony_ci /// 120362306a36Sopenharmony_ci /// let slice = v.into_boxed_slice(); 120462306a36Sopenharmony_ci /// ``` 120562306a36Sopenharmony_ci /// 120662306a36Sopenharmony_ci /// Any excess capacity is removed: 120762306a36Sopenharmony_ci /// 120862306a36Sopenharmony_ci /// ``` 120962306a36Sopenharmony_ci /// let mut vec = Vec::with_capacity(10); 121062306a36Sopenharmony_ci /// vec.extend([1, 2, 3]); 121162306a36Sopenharmony_ci /// 121262306a36Sopenharmony_ci /// assert!(vec.capacity() >= 10); 121362306a36Sopenharmony_ci /// let slice = vec.into_boxed_slice(); 121462306a36Sopenharmony_ci /// assert_eq!(slice.into_vec().capacity(), 3); 121562306a36Sopenharmony_ci /// ``` 121662306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 121762306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 121862306a36Sopenharmony_ci pub fn into_boxed_slice(mut self) -> Box<[T], A> { 121962306a36Sopenharmony_ci unsafe { 122062306a36Sopenharmony_ci self.shrink_to_fit(); 122162306a36Sopenharmony_ci let me = ManuallyDrop::new(self); 122262306a36Sopenharmony_ci let buf = ptr::read(&me.buf); 122362306a36Sopenharmony_ci let len = me.len(); 122462306a36Sopenharmony_ci buf.into_box(len).assume_init() 122562306a36Sopenharmony_ci } 122662306a36Sopenharmony_ci } 122762306a36Sopenharmony_ci 122862306a36Sopenharmony_ci /// Shortens the vector, keeping the first `len` elements and dropping 122962306a36Sopenharmony_ci /// the rest. 123062306a36Sopenharmony_ci /// 123162306a36Sopenharmony_ci /// If `len` is greater than the vector's current length, this has no 123262306a36Sopenharmony_ci /// effect. 123362306a36Sopenharmony_ci /// 123462306a36Sopenharmony_ci /// The [`drain`] method can emulate `truncate`, but causes the excess 123562306a36Sopenharmony_ci /// elements to be returned instead of dropped. 123662306a36Sopenharmony_ci /// 123762306a36Sopenharmony_ci /// Note that this method has no effect on the allocated capacity 123862306a36Sopenharmony_ci /// of the vector. 123962306a36Sopenharmony_ci /// 124062306a36Sopenharmony_ci /// # Examples 124162306a36Sopenharmony_ci /// 124262306a36Sopenharmony_ci /// Truncating a five element vector to two elements: 124362306a36Sopenharmony_ci /// 124462306a36Sopenharmony_ci /// ``` 124562306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3, 4, 5]; 124662306a36Sopenharmony_ci /// vec.truncate(2); 124762306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2]); 124862306a36Sopenharmony_ci /// ``` 124962306a36Sopenharmony_ci /// 125062306a36Sopenharmony_ci /// No truncation occurs when `len` is greater than the vector's current 125162306a36Sopenharmony_ci /// length: 125262306a36Sopenharmony_ci /// 125362306a36Sopenharmony_ci /// ``` 125462306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3]; 125562306a36Sopenharmony_ci /// vec.truncate(8); 125662306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2, 3]); 125762306a36Sopenharmony_ci /// ``` 125862306a36Sopenharmony_ci /// 125962306a36Sopenharmony_ci /// Truncating when `len == 0` is equivalent to calling the [`clear`] 126062306a36Sopenharmony_ci /// method. 126162306a36Sopenharmony_ci /// 126262306a36Sopenharmony_ci /// ``` 126362306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3]; 126462306a36Sopenharmony_ci /// vec.truncate(0); 126562306a36Sopenharmony_ci /// assert_eq!(vec, []); 126662306a36Sopenharmony_ci /// ``` 126762306a36Sopenharmony_ci /// 126862306a36Sopenharmony_ci /// [`clear`]: Vec::clear 126962306a36Sopenharmony_ci /// [`drain`]: Vec::drain 127062306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 127162306a36Sopenharmony_ci pub fn truncate(&mut self, len: usize) { 127262306a36Sopenharmony_ci // This is safe because: 127362306a36Sopenharmony_ci // 127462306a36Sopenharmony_ci // * the slice passed to `drop_in_place` is valid; the `len > self.len` 127562306a36Sopenharmony_ci // case avoids creating an invalid slice, and 127662306a36Sopenharmony_ci // * the `len` of the vector is shrunk before calling `drop_in_place`, 127762306a36Sopenharmony_ci // such that no value will be dropped twice in case `drop_in_place` 127862306a36Sopenharmony_ci // were to panic once (if it panics twice, the program aborts). 127962306a36Sopenharmony_ci unsafe { 128062306a36Sopenharmony_ci // Note: It's intentional that this is `>` and not `>=`. 128162306a36Sopenharmony_ci // Changing it to `>=` has negative performance 128262306a36Sopenharmony_ci // implications in some cases. See #78884 for more. 128362306a36Sopenharmony_ci if len > self.len { 128462306a36Sopenharmony_ci return; 128562306a36Sopenharmony_ci } 128662306a36Sopenharmony_ci let remaining_len = self.len - len; 128762306a36Sopenharmony_ci let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len); 128862306a36Sopenharmony_ci self.len = len; 128962306a36Sopenharmony_ci ptr::drop_in_place(s); 129062306a36Sopenharmony_ci } 129162306a36Sopenharmony_ci } 129262306a36Sopenharmony_ci 129362306a36Sopenharmony_ci /// Extracts a slice containing the entire vector. 129462306a36Sopenharmony_ci /// 129562306a36Sopenharmony_ci /// Equivalent to `&s[..]`. 129662306a36Sopenharmony_ci /// 129762306a36Sopenharmony_ci /// # Examples 129862306a36Sopenharmony_ci /// 129962306a36Sopenharmony_ci /// ``` 130062306a36Sopenharmony_ci /// use std::io::{self, Write}; 130162306a36Sopenharmony_ci /// let buffer = vec![1, 2, 3, 5, 8]; 130262306a36Sopenharmony_ci /// io::sink().write(buffer.as_slice()).unwrap(); 130362306a36Sopenharmony_ci /// ``` 130462306a36Sopenharmony_ci #[inline] 130562306a36Sopenharmony_ci #[stable(feature = "vec_as_slice", since = "1.7.0")] 130662306a36Sopenharmony_ci pub fn as_slice(&self) -> &[T] { 130762306a36Sopenharmony_ci self 130862306a36Sopenharmony_ci } 130962306a36Sopenharmony_ci 131062306a36Sopenharmony_ci /// Extracts a mutable slice of the entire vector. 131162306a36Sopenharmony_ci /// 131262306a36Sopenharmony_ci /// Equivalent to `&mut s[..]`. 131362306a36Sopenharmony_ci /// 131462306a36Sopenharmony_ci /// # Examples 131562306a36Sopenharmony_ci /// 131662306a36Sopenharmony_ci /// ``` 131762306a36Sopenharmony_ci /// use std::io::{self, Read}; 131862306a36Sopenharmony_ci /// let mut buffer = vec![0; 3]; 131962306a36Sopenharmony_ci /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); 132062306a36Sopenharmony_ci /// ``` 132162306a36Sopenharmony_ci #[inline] 132262306a36Sopenharmony_ci #[stable(feature = "vec_as_slice", since = "1.7.0")] 132362306a36Sopenharmony_ci pub fn as_mut_slice(&mut self) -> &mut [T] { 132462306a36Sopenharmony_ci self 132562306a36Sopenharmony_ci } 132662306a36Sopenharmony_ci 132762306a36Sopenharmony_ci /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer 132862306a36Sopenharmony_ci /// valid for zero sized reads if the vector didn't allocate. 132962306a36Sopenharmony_ci /// 133062306a36Sopenharmony_ci /// The caller must ensure that the vector outlives the pointer this 133162306a36Sopenharmony_ci /// function returns, or else it will end up pointing to garbage. 133262306a36Sopenharmony_ci /// Modifying the vector may cause its buffer to be reallocated, 133362306a36Sopenharmony_ci /// which would also make any pointers to it invalid. 133462306a36Sopenharmony_ci /// 133562306a36Sopenharmony_ci /// The caller must also ensure that the memory the pointer (non-transitively) points to 133662306a36Sopenharmony_ci /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer 133762306a36Sopenharmony_ci /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`]. 133862306a36Sopenharmony_ci /// 133962306a36Sopenharmony_ci /// # Examples 134062306a36Sopenharmony_ci /// 134162306a36Sopenharmony_ci /// ``` 134262306a36Sopenharmony_ci /// let x = vec![1, 2, 4]; 134362306a36Sopenharmony_ci /// let x_ptr = x.as_ptr(); 134462306a36Sopenharmony_ci /// 134562306a36Sopenharmony_ci /// unsafe { 134662306a36Sopenharmony_ci /// for i in 0..x.len() { 134762306a36Sopenharmony_ci /// assert_eq!(*x_ptr.add(i), 1 << i); 134862306a36Sopenharmony_ci /// } 134962306a36Sopenharmony_ci /// } 135062306a36Sopenharmony_ci /// ``` 135162306a36Sopenharmony_ci /// 135262306a36Sopenharmony_ci /// [`as_mut_ptr`]: Vec::as_mut_ptr 135362306a36Sopenharmony_ci #[stable(feature = "vec_as_ptr", since = "1.37.0")] 135462306a36Sopenharmony_ci #[inline] 135562306a36Sopenharmony_ci pub fn as_ptr(&self) -> *const T { 135662306a36Sopenharmony_ci // We shadow the slice method of the same name to avoid going through 135762306a36Sopenharmony_ci // `deref`, which creates an intermediate reference. 135862306a36Sopenharmony_ci self.buf.ptr() 135962306a36Sopenharmony_ci } 136062306a36Sopenharmony_ci 136162306a36Sopenharmony_ci /// Returns an unsafe mutable pointer to the vector's buffer, or a dangling 136262306a36Sopenharmony_ci /// raw pointer valid for zero sized reads if the vector didn't allocate. 136362306a36Sopenharmony_ci /// 136462306a36Sopenharmony_ci /// The caller must ensure that the vector outlives the pointer this 136562306a36Sopenharmony_ci /// function returns, or else it will end up pointing to garbage. 136662306a36Sopenharmony_ci /// Modifying the vector may cause its buffer to be reallocated, 136762306a36Sopenharmony_ci /// which would also make any pointers to it invalid. 136862306a36Sopenharmony_ci /// 136962306a36Sopenharmony_ci /// # Examples 137062306a36Sopenharmony_ci /// 137162306a36Sopenharmony_ci /// ``` 137262306a36Sopenharmony_ci /// // Allocate vector big enough for 4 elements. 137362306a36Sopenharmony_ci /// let size = 4; 137462306a36Sopenharmony_ci /// let mut x: Vec<i32> = Vec::with_capacity(size); 137562306a36Sopenharmony_ci /// let x_ptr = x.as_mut_ptr(); 137662306a36Sopenharmony_ci /// 137762306a36Sopenharmony_ci /// // Initialize elements via raw pointer writes, then set length. 137862306a36Sopenharmony_ci /// unsafe { 137962306a36Sopenharmony_ci /// for i in 0..size { 138062306a36Sopenharmony_ci /// *x_ptr.add(i) = i as i32; 138162306a36Sopenharmony_ci /// } 138262306a36Sopenharmony_ci /// x.set_len(size); 138362306a36Sopenharmony_ci /// } 138462306a36Sopenharmony_ci /// assert_eq!(&*x, &[0, 1, 2, 3]); 138562306a36Sopenharmony_ci /// ``` 138662306a36Sopenharmony_ci #[stable(feature = "vec_as_ptr", since = "1.37.0")] 138762306a36Sopenharmony_ci #[inline] 138862306a36Sopenharmony_ci pub fn as_mut_ptr(&mut self) -> *mut T { 138962306a36Sopenharmony_ci // We shadow the slice method of the same name to avoid going through 139062306a36Sopenharmony_ci // `deref_mut`, which creates an intermediate reference. 139162306a36Sopenharmony_ci self.buf.ptr() 139262306a36Sopenharmony_ci } 139362306a36Sopenharmony_ci 139462306a36Sopenharmony_ci /// Returns a reference to the underlying allocator. 139562306a36Sopenharmony_ci #[unstable(feature = "allocator_api", issue = "32838")] 139662306a36Sopenharmony_ci #[inline] 139762306a36Sopenharmony_ci pub fn allocator(&self) -> &A { 139862306a36Sopenharmony_ci self.buf.allocator() 139962306a36Sopenharmony_ci } 140062306a36Sopenharmony_ci 140162306a36Sopenharmony_ci /// Forces the length of the vector to `new_len`. 140262306a36Sopenharmony_ci /// 140362306a36Sopenharmony_ci /// This is a low-level operation that maintains none of the normal 140462306a36Sopenharmony_ci /// invariants of the type. Normally changing the length of a vector 140562306a36Sopenharmony_ci /// is done using one of the safe operations instead, such as 140662306a36Sopenharmony_ci /// [`truncate`], [`resize`], [`extend`], or [`clear`]. 140762306a36Sopenharmony_ci /// 140862306a36Sopenharmony_ci /// [`truncate`]: Vec::truncate 140962306a36Sopenharmony_ci /// [`resize`]: Vec::resize 141062306a36Sopenharmony_ci /// [`extend`]: Extend::extend 141162306a36Sopenharmony_ci /// [`clear`]: Vec::clear 141262306a36Sopenharmony_ci /// 141362306a36Sopenharmony_ci /// # Safety 141462306a36Sopenharmony_ci /// 141562306a36Sopenharmony_ci /// - `new_len` must be less than or equal to [`capacity()`]. 141662306a36Sopenharmony_ci /// - The elements at `old_len..new_len` must be initialized. 141762306a36Sopenharmony_ci /// 141862306a36Sopenharmony_ci /// [`capacity()`]: Vec::capacity 141962306a36Sopenharmony_ci /// 142062306a36Sopenharmony_ci /// # Examples 142162306a36Sopenharmony_ci /// 142262306a36Sopenharmony_ci /// This method can be useful for situations in which the vector 142362306a36Sopenharmony_ci /// is serving as a buffer for other code, particularly over FFI: 142462306a36Sopenharmony_ci /// 142562306a36Sopenharmony_ci /// ```no_run 142662306a36Sopenharmony_ci /// # #![allow(dead_code)] 142762306a36Sopenharmony_ci /// # // This is just a minimal skeleton for the doc example; 142862306a36Sopenharmony_ci /// # // don't use this as a starting point for a real library. 142962306a36Sopenharmony_ci /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void } 143062306a36Sopenharmony_ci /// # const Z_OK: i32 = 0; 143162306a36Sopenharmony_ci /// # extern "C" { 143262306a36Sopenharmony_ci /// # fn deflateGetDictionary( 143362306a36Sopenharmony_ci /// # strm: *mut std::ffi::c_void, 143462306a36Sopenharmony_ci /// # dictionary: *mut u8, 143562306a36Sopenharmony_ci /// # dictLength: *mut usize, 143662306a36Sopenharmony_ci /// # ) -> i32; 143762306a36Sopenharmony_ci /// # } 143862306a36Sopenharmony_ci /// # impl StreamWrapper { 143962306a36Sopenharmony_ci /// pub fn get_dictionary(&self) -> Option<Vec<u8>> { 144062306a36Sopenharmony_ci /// // Per the FFI method's docs, "32768 bytes is always enough". 144162306a36Sopenharmony_ci /// let mut dict = Vec::with_capacity(32_768); 144262306a36Sopenharmony_ci /// let mut dict_length = 0; 144362306a36Sopenharmony_ci /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that: 144462306a36Sopenharmony_ci /// // 1. `dict_length` elements were initialized. 144562306a36Sopenharmony_ci /// // 2. `dict_length` <= the capacity (32_768) 144662306a36Sopenharmony_ci /// // which makes `set_len` safe to call. 144762306a36Sopenharmony_ci /// unsafe { 144862306a36Sopenharmony_ci /// // Make the FFI call... 144962306a36Sopenharmony_ci /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length); 145062306a36Sopenharmony_ci /// if r == Z_OK { 145162306a36Sopenharmony_ci /// // ...and update the length to what was initialized. 145262306a36Sopenharmony_ci /// dict.set_len(dict_length); 145362306a36Sopenharmony_ci /// Some(dict) 145462306a36Sopenharmony_ci /// } else { 145562306a36Sopenharmony_ci /// None 145662306a36Sopenharmony_ci /// } 145762306a36Sopenharmony_ci /// } 145862306a36Sopenharmony_ci /// } 145962306a36Sopenharmony_ci /// # } 146062306a36Sopenharmony_ci /// ``` 146162306a36Sopenharmony_ci /// 146262306a36Sopenharmony_ci /// While the following example is sound, there is a memory leak since 146362306a36Sopenharmony_ci /// the inner vectors were not freed prior to the `set_len` call: 146462306a36Sopenharmony_ci /// 146562306a36Sopenharmony_ci /// ``` 146662306a36Sopenharmony_ci /// let mut vec = vec![vec![1, 0, 0], 146762306a36Sopenharmony_ci /// vec![0, 1, 0], 146862306a36Sopenharmony_ci /// vec![0, 0, 1]]; 146962306a36Sopenharmony_ci /// // SAFETY: 147062306a36Sopenharmony_ci /// // 1. `old_len..0` is empty so no elements need to be initialized. 147162306a36Sopenharmony_ci /// // 2. `0 <= capacity` always holds whatever `capacity` is. 147262306a36Sopenharmony_ci /// unsafe { 147362306a36Sopenharmony_ci /// vec.set_len(0); 147462306a36Sopenharmony_ci /// } 147562306a36Sopenharmony_ci /// ``` 147662306a36Sopenharmony_ci /// 147762306a36Sopenharmony_ci /// Normally, here, one would use [`clear`] instead to correctly drop 147862306a36Sopenharmony_ci /// the contents and thus not leak memory. 147962306a36Sopenharmony_ci #[inline] 148062306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 148162306a36Sopenharmony_ci pub unsafe fn set_len(&mut self, new_len: usize) { 148262306a36Sopenharmony_ci debug_assert!(new_len <= self.capacity()); 148362306a36Sopenharmony_ci 148462306a36Sopenharmony_ci self.len = new_len; 148562306a36Sopenharmony_ci } 148662306a36Sopenharmony_ci 148762306a36Sopenharmony_ci /// Removes an element from the vector and returns it. 148862306a36Sopenharmony_ci /// 148962306a36Sopenharmony_ci /// The removed element is replaced by the last element of the vector. 149062306a36Sopenharmony_ci /// 149162306a36Sopenharmony_ci /// This does not preserve ordering, but is *O*(1). 149262306a36Sopenharmony_ci /// If you need to preserve the element order, use [`remove`] instead. 149362306a36Sopenharmony_ci /// 149462306a36Sopenharmony_ci /// [`remove`]: Vec::remove 149562306a36Sopenharmony_ci /// 149662306a36Sopenharmony_ci /// # Panics 149762306a36Sopenharmony_ci /// 149862306a36Sopenharmony_ci /// Panics if `index` is out of bounds. 149962306a36Sopenharmony_ci /// 150062306a36Sopenharmony_ci /// # Examples 150162306a36Sopenharmony_ci /// 150262306a36Sopenharmony_ci /// ``` 150362306a36Sopenharmony_ci /// let mut v = vec!["foo", "bar", "baz", "qux"]; 150462306a36Sopenharmony_ci /// 150562306a36Sopenharmony_ci /// assert_eq!(v.swap_remove(1), "bar"); 150662306a36Sopenharmony_ci /// assert_eq!(v, ["foo", "qux", "baz"]); 150762306a36Sopenharmony_ci /// 150862306a36Sopenharmony_ci /// assert_eq!(v.swap_remove(0), "foo"); 150962306a36Sopenharmony_ci /// assert_eq!(v, ["baz", "qux"]); 151062306a36Sopenharmony_ci /// ``` 151162306a36Sopenharmony_ci #[inline] 151262306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 151362306a36Sopenharmony_ci pub fn swap_remove(&mut self, index: usize) -> T { 151462306a36Sopenharmony_ci #[cold] 151562306a36Sopenharmony_ci #[inline(never)] 151662306a36Sopenharmony_ci fn assert_failed(index: usize, len: usize) -> ! { 151762306a36Sopenharmony_ci panic!("swap_remove index (is {index}) should be < len (is {len})"); 151862306a36Sopenharmony_ci } 151962306a36Sopenharmony_ci 152062306a36Sopenharmony_ci let len = self.len(); 152162306a36Sopenharmony_ci if index >= len { 152262306a36Sopenharmony_ci assert_failed(index, len); 152362306a36Sopenharmony_ci } 152462306a36Sopenharmony_ci unsafe { 152562306a36Sopenharmony_ci // We replace self[index] with the last element. Note that if the 152662306a36Sopenharmony_ci // bounds check above succeeds there must be a last element (which 152762306a36Sopenharmony_ci // can be self[index] itself). 152862306a36Sopenharmony_ci let value = ptr::read(self.as_ptr().add(index)); 152962306a36Sopenharmony_ci let base_ptr = self.as_mut_ptr(); 153062306a36Sopenharmony_ci ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); 153162306a36Sopenharmony_ci self.set_len(len - 1); 153262306a36Sopenharmony_ci value 153362306a36Sopenharmony_ci } 153462306a36Sopenharmony_ci } 153562306a36Sopenharmony_ci 153662306a36Sopenharmony_ci /// Inserts an element at position `index` within the vector, shifting all 153762306a36Sopenharmony_ci /// elements after it to the right. 153862306a36Sopenharmony_ci /// 153962306a36Sopenharmony_ci /// # Panics 154062306a36Sopenharmony_ci /// 154162306a36Sopenharmony_ci /// Panics if `index > len`. 154262306a36Sopenharmony_ci /// 154362306a36Sopenharmony_ci /// # Examples 154462306a36Sopenharmony_ci /// 154562306a36Sopenharmony_ci /// ``` 154662306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3]; 154762306a36Sopenharmony_ci /// vec.insert(1, 4); 154862306a36Sopenharmony_ci /// assert_eq!(vec, [1, 4, 2, 3]); 154962306a36Sopenharmony_ci /// vec.insert(4, 5); 155062306a36Sopenharmony_ci /// assert_eq!(vec, [1, 4, 2, 3, 5]); 155162306a36Sopenharmony_ci /// ``` 155262306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 155362306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 155462306a36Sopenharmony_ci pub fn insert(&mut self, index: usize, element: T) { 155562306a36Sopenharmony_ci #[cold] 155662306a36Sopenharmony_ci #[inline(never)] 155762306a36Sopenharmony_ci fn assert_failed(index: usize, len: usize) -> ! { 155862306a36Sopenharmony_ci panic!("insertion index (is {index}) should be <= len (is {len})"); 155962306a36Sopenharmony_ci } 156062306a36Sopenharmony_ci 156162306a36Sopenharmony_ci let len = self.len(); 156262306a36Sopenharmony_ci 156362306a36Sopenharmony_ci // space for the new element 156462306a36Sopenharmony_ci if len == self.buf.capacity() { 156562306a36Sopenharmony_ci self.reserve(1); 156662306a36Sopenharmony_ci } 156762306a36Sopenharmony_ci 156862306a36Sopenharmony_ci unsafe { 156962306a36Sopenharmony_ci // infallible 157062306a36Sopenharmony_ci // The spot to put the new value 157162306a36Sopenharmony_ci { 157262306a36Sopenharmony_ci let p = self.as_mut_ptr().add(index); 157362306a36Sopenharmony_ci if index < len { 157462306a36Sopenharmony_ci // Shift everything over to make space. (Duplicating the 157562306a36Sopenharmony_ci // `index`th element into two consecutive places.) 157662306a36Sopenharmony_ci ptr::copy(p, p.add(1), len - index); 157762306a36Sopenharmony_ci } else if index == len { 157862306a36Sopenharmony_ci // No elements need shifting. 157962306a36Sopenharmony_ci } else { 158062306a36Sopenharmony_ci assert_failed(index, len); 158162306a36Sopenharmony_ci } 158262306a36Sopenharmony_ci // Write it in, overwriting the first copy of the `index`th 158362306a36Sopenharmony_ci // element. 158462306a36Sopenharmony_ci ptr::write(p, element); 158562306a36Sopenharmony_ci } 158662306a36Sopenharmony_ci self.set_len(len + 1); 158762306a36Sopenharmony_ci } 158862306a36Sopenharmony_ci } 158962306a36Sopenharmony_ci 159062306a36Sopenharmony_ci /// Removes and returns the element at position `index` within the vector, 159162306a36Sopenharmony_ci /// shifting all elements after it to the left. 159262306a36Sopenharmony_ci /// 159362306a36Sopenharmony_ci /// Note: Because this shifts over the remaining elements, it has a 159462306a36Sopenharmony_ci /// worst-case performance of *O*(*n*). If you don't need the order of elements 159562306a36Sopenharmony_ci /// to be preserved, use [`swap_remove`] instead. If you'd like to remove 159662306a36Sopenharmony_ci /// elements from the beginning of the `Vec`, consider using 159762306a36Sopenharmony_ci /// [`VecDeque::pop_front`] instead. 159862306a36Sopenharmony_ci /// 159962306a36Sopenharmony_ci /// [`swap_remove`]: Vec::swap_remove 160062306a36Sopenharmony_ci /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front 160162306a36Sopenharmony_ci /// 160262306a36Sopenharmony_ci /// # Panics 160362306a36Sopenharmony_ci /// 160462306a36Sopenharmony_ci /// Panics if `index` is out of bounds. 160562306a36Sopenharmony_ci /// 160662306a36Sopenharmony_ci /// # Examples 160762306a36Sopenharmony_ci /// 160862306a36Sopenharmony_ci /// ``` 160962306a36Sopenharmony_ci /// let mut v = vec![1, 2, 3]; 161062306a36Sopenharmony_ci /// assert_eq!(v.remove(1), 2); 161162306a36Sopenharmony_ci /// assert_eq!(v, [1, 3]); 161262306a36Sopenharmony_ci /// ``` 161362306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 161462306a36Sopenharmony_ci #[track_caller] 161562306a36Sopenharmony_ci pub fn remove(&mut self, index: usize) -> T { 161662306a36Sopenharmony_ci #[cold] 161762306a36Sopenharmony_ci #[inline(never)] 161862306a36Sopenharmony_ci #[track_caller] 161962306a36Sopenharmony_ci fn assert_failed(index: usize, len: usize) -> ! { 162062306a36Sopenharmony_ci panic!("removal index (is {index}) should be < len (is {len})"); 162162306a36Sopenharmony_ci } 162262306a36Sopenharmony_ci 162362306a36Sopenharmony_ci let len = self.len(); 162462306a36Sopenharmony_ci if index >= len { 162562306a36Sopenharmony_ci assert_failed(index, len); 162662306a36Sopenharmony_ci } 162762306a36Sopenharmony_ci unsafe { 162862306a36Sopenharmony_ci // infallible 162962306a36Sopenharmony_ci let ret; 163062306a36Sopenharmony_ci { 163162306a36Sopenharmony_ci // the place we are taking from. 163262306a36Sopenharmony_ci let ptr = self.as_mut_ptr().add(index); 163362306a36Sopenharmony_ci // copy it out, unsafely having a copy of the value on 163462306a36Sopenharmony_ci // the stack and in the vector at the same time. 163562306a36Sopenharmony_ci ret = ptr::read(ptr); 163662306a36Sopenharmony_ci 163762306a36Sopenharmony_ci // Shift everything down to fill in that spot. 163862306a36Sopenharmony_ci ptr::copy(ptr.add(1), ptr, len - index - 1); 163962306a36Sopenharmony_ci } 164062306a36Sopenharmony_ci self.set_len(len - 1); 164162306a36Sopenharmony_ci ret 164262306a36Sopenharmony_ci } 164362306a36Sopenharmony_ci } 164462306a36Sopenharmony_ci 164562306a36Sopenharmony_ci /// Retains only the elements specified by the predicate. 164662306a36Sopenharmony_ci /// 164762306a36Sopenharmony_ci /// In other words, remove all elements `e` for which `f(&e)` returns `false`. 164862306a36Sopenharmony_ci /// This method operates in place, visiting each element exactly once in the 164962306a36Sopenharmony_ci /// original order, and preserves the order of the retained elements. 165062306a36Sopenharmony_ci /// 165162306a36Sopenharmony_ci /// # Examples 165262306a36Sopenharmony_ci /// 165362306a36Sopenharmony_ci /// ``` 165462306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3, 4]; 165562306a36Sopenharmony_ci /// vec.retain(|&x| x % 2 == 0); 165662306a36Sopenharmony_ci /// assert_eq!(vec, [2, 4]); 165762306a36Sopenharmony_ci /// ``` 165862306a36Sopenharmony_ci /// 165962306a36Sopenharmony_ci /// Because the elements are visited exactly once in the original order, 166062306a36Sopenharmony_ci /// external state may be used to decide which elements to keep. 166162306a36Sopenharmony_ci /// 166262306a36Sopenharmony_ci /// ``` 166362306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3, 4, 5]; 166462306a36Sopenharmony_ci /// let keep = [false, true, true, false, true]; 166562306a36Sopenharmony_ci /// let mut iter = keep.iter(); 166662306a36Sopenharmony_ci /// vec.retain(|_| *iter.next().unwrap()); 166762306a36Sopenharmony_ci /// assert_eq!(vec, [2, 3, 5]); 166862306a36Sopenharmony_ci /// ``` 166962306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 167062306a36Sopenharmony_ci pub fn retain<F>(&mut self, mut f: F) 167162306a36Sopenharmony_ci where 167262306a36Sopenharmony_ci F: FnMut(&T) -> bool, 167362306a36Sopenharmony_ci { 167462306a36Sopenharmony_ci self.retain_mut(|elem| f(elem)); 167562306a36Sopenharmony_ci } 167662306a36Sopenharmony_ci 167762306a36Sopenharmony_ci /// Retains only the elements specified by the predicate, passing a mutable reference to it. 167862306a36Sopenharmony_ci /// 167962306a36Sopenharmony_ci /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. 168062306a36Sopenharmony_ci /// This method operates in place, visiting each element exactly once in the 168162306a36Sopenharmony_ci /// original order, and preserves the order of the retained elements. 168262306a36Sopenharmony_ci /// 168362306a36Sopenharmony_ci /// # Examples 168462306a36Sopenharmony_ci /// 168562306a36Sopenharmony_ci /// ``` 168662306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3, 4]; 168762306a36Sopenharmony_ci /// vec.retain_mut(|x| if *x <= 3 { 168862306a36Sopenharmony_ci /// *x += 1; 168962306a36Sopenharmony_ci /// true 169062306a36Sopenharmony_ci /// } else { 169162306a36Sopenharmony_ci /// false 169262306a36Sopenharmony_ci /// }); 169362306a36Sopenharmony_ci /// assert_eq!(vec, [2, 3, 4]); 169462306a36Sopenharmony_ci /// ``` 169562306a36Sopenharmony_ci #[stable(feature = "vec_retain_mut", since = "1.61.0")] 169662306a36Sopenharmony_ci pub fn retain_mut<F>(&mut self, mut f: F) 169762306a36Sopenharmony_ci where 169862306a36Sopenharmony_ci F: FnMut(&mut T) -> bool, 169962306a36Sopenharmony_ci { 170062306a36Sopenharmony_ci let original_len = self.len(); 170162306a36Sopenharmony_ci // Avoid double drop if the drop guard is not executed, 170262306a36Sopenharmony_ci // since we may make some holes during the process. 170362306a36Sopenharmony_ci unsafe { self.set_len(0) }; 170462306a36Sopenharmony_ci 170562306a36Sopenharmony_ci // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked] 170662306a36Sopenharmony_ci // |<- processed len ->| ^- next to check 170762306a36Sopenharmony_ci // |<- deleted cnt ->| 170862306a36Sopenharmony_ci // |<- original_len ->| 170962306a36Sopenharmony_ci // Kept: Elements which predicate returns true on. 171062306a36Sopenharmony_ci // Hole: Moved or dropped element slot. 171162306a36Sopenharmony_ci // Unchecked: Unchecked valid elements. 171262306a36Sopenharmony_ci // 171362306a36Sopenharmony_ci // This drop guard will be invoked when predicate or `drop` of element panicked. 171462306a36Sopenharmony_ci // It shifts unchecked elements to cover holes and `set_len` to the correct length. 171562306a36Sopenharmony_ci // In cases when predicate and `drop` never panick, it will be optimized out. 171662306a36Sopenharmony_ci struct BackshiftOnDrop<'a, T, A: Allocator> { 171762306a36Sopenharmony_ci v: &'a mut Vec<T, A>, 171862306a36Sopenharmony_ci processed_len: usize, 171962306a36Sopenharmony_ci deleted_cnt: usize, 172062306a36Sopenharmony_ci original_len: usize, 172162306a36Sopenharmony_ci } 172262306a36Sopenharmony_ci 172362306a36Sopenharmony_ci impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> { 172462306a36Sopenharmony_ci fn drop(&mut self) { 172562306a36Sopenharmony_ci if self.deleted_cnt > 0 { 172662306a36Sopenharmony_ci // SAFETY: Trailing unchecked items must be valid since we never touch them. 172762306a36Sopenharmony_ci unsafe { 172862306a36Sopenharmony_ci ptr::copy( 172962306a36Sopenharmony_ci self.v.as_ptr().add(self.processed_len), 173062306a36Sopenharmony_ci self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), 173162306a36Sopenharmony_ci self.original_len - self.processed_len, 173262306a36Sopenharmony_ci ); 173362306a36Sopenharmony_ci } 173462306a36Sopenharmony_ci } 173562306a36Sopenharmony_ci // SAFETY: After filling holes, all items are in contiguous memory. 173662306a36Sopenharmony_ci unsafe { 173762306a36Sopenharmony_ci self.v.set_len(self.original_len - self.deleted_cnt); 173862306a36Sopenharmony_ci } 173962306a36Sopenharmony_ci } 174062306a36Sopenharmony_ci } 174162306a36Sopenharmony_ci 174262306a36Sopenharmony_ci let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; 174362306a36Sopenharmony_ci 174462306a36Sopenharmony_ci fn process_loop<F, T, A: Allocator, const DELETED: bool>( 174562306a36Sopenharmony_ci original_len: usize, 174662306a36Sopenharmony_ci f: &mut F, 174762306a36Sopenharmony_ci g: &mut BackshiftOnDrop<'_, T, A>, 174862306a36Sopenharmony_ci ) where 174962306a36Sopenharmony_ci F: FnMut(&mut T) -> bool, 175062306a36Sopenharmony_ci { 175162306a36Sopenharmony_ci while g.processed_len != original_len { 175262306a36Sopenharmony_ci // SAFETY: Unchecked element must be valid. 175362306a36Sopenharmony_ci let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; 175462306a36Sopenharmony_ci if !f(cur) { 175562306a36Sopenharmony_ci // Advance early to avoid double drop if `drop_in_place` panicked. 175662306a36Sopenharmony_ci g.processed_len += 1; 175762306a36Sopenharmony_ci g.deleted_cnt += 1; 175862306a36Sopenharmony_ci // SAFETY: We never touch this element again after dropped. 175962306a36Sopenharmony_ci unsafe { ptr::drop_in_place(cur) }; 176062306a36Sopenharmony_ci // We already advanced the counter. 176162306a36Sopenharmony_ci if DELETED { 176262306a36Sopenharmony_ci continue; 176362306a36Sopenharmony_ci } else { 176462306a36Sopenharmony_ci break; 176562306a36Sopenharmony_ci } 176662306a36Sopenharmony_ci } 176762306a36Sopenharmony_ci if DELETED { 176862306a36Sopenharmony_ci // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element. 176962306a36Sopenharmony_ci // We use copy for move, and never touch this element again. 177062306a36Sopenharmony_ci unsafe { 177162306a36Sopenharmony_ci let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); 177262306a36Sopenharmony_ci ptr::copy_nonoverlapping(cur, hole_slot, 1); 177362306a36Sopenharmony_ci } 177462306a36Sopenharmony_ci } 177562306a36Sopenharmony_ci g.processed_len += 1; 177662306a36Sopenharmony_ci } 177762306a36Sopenharmony_ci } 177862306a36Sopenharmony_ci 177962306a36Sopenharmony_ci // Stage 1: Nothing was deleted. 178062306a36Sopenharmony_ci process_loop::<F, T, A, false>(original_len, &mut f, &mut g); 178162306a36Sopenharmony_ci 178262306a36Sopenharmony_ci // Stage 2: Some elements were deleted. 178362306a36Sopenharmony_ci process_loop::<F, T, A, true>(original_len, &mut f, &mut g); 178462306a36Sopenharmony_ci 178562306a36Sopenharmony_ci // All item are processed. This can be optimized to `set_len` by LLVM. 178662306a36Sopenharmony_ci drop(g); 178762306a36Sopenharmony_ci } 178862306a36Sopenharmony_ci 178962306a36Sopenharmony_ci /// Removes all but the first of consecutive elements in the vector that resolve to the same 179062306a36Sopenharmony_ci /// key. 179162306a36Sopenharmony_ci /// 179262306a36Sopenharmony_ci /// If the vector is sorted, this removes all duplicates. 179362306a36Sopenharmony_ci /// 179462306a36Sopenharmony_ci /// # Examples 179562306a36Sopenharmony_ci /// 179662306a36Sopenharmony_ci /// ``` 179762306a36Sopenharmony_ci /// let mut vec = vec![10, 20, 21, 30, 20]; 179862306a36Sopenharmony_ci /// 179962306a36Sopenharmony_ci /// vec.dedup_by_key(|i| *i / 10); 180062306a36Sopenharmony_ci /// 180162306a36Sopenharmony_ci /// assert_eq!(vec, [10, 20, 30, 20]); 180262306a36Sopenharmony_ci /// ``` 180362306a36Sopenharmony_ci #[stable(feature = "dedup_by", since = "1.16.0")] 180462306a36Sopenharmony_ci #[inline] 180562306a36Sopenharmony_ci pub fn dedup_by_key<F, K>(&mut self, mut key: F) 180662306a36Sopenharmony_ci where 180762306a36Sopenharmony_ci F: FnMut(&mut T) -> K, 180862306a36Sopenharmony_ci K: PartialEq, 180962306a36Sopenharmony_ci { 181062306a36Sopenharmony_ci self.dedup_by(|a, b| key(a) == key(b)) 181162306a36Sopenharmony_ci } 181262306a36Sopenharmony_ci 181362306a36Sopenharmony_ci /// Removes all but the first of consecutive elements in the vector satisfying a given equality 181462306a36Sopenharmony_ci /// relation. 181562306a36Sopenharmony_ci /// 181662306a36Sopenharmony_ci /// The `same_bucket` function is passed references to two elements from the vector and 181762306a36Sopenharmony_ci /// must determine if the elements compare equal. The elements are passed in opposite order 181862306a36Sopenharmony_ci /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed. 181962306a36Sopenharmony_ci /// 182062306a36Sopenharmony_ci /// If the vector is sorted, this removes all duplicates. 182162306a36Sopenharmony_ci /// 182262306a36Sopenharmony_ci /// # Examples 182362306a36Sopenharmony_ci /// 182462306a36Sopenharmony_ci /// ``` 182562306a36Sopenharmony_ci /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; 182662306a36Sopenharmony_ci /// 182762306a36Sopenharmony_ci /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); 182862306a36Sopenharmony_ci /// 182962306a36Sopenharmony_ci /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); 183062306a36Sopenharmony_ci /// ``` 183162306a36Sopenharmony_ci #[stable(feature = "dedup_by", since = "1.16.0")] 183262306a36Sopenharmony_ci pub fn dedup_by<F>(&mut self, mut same_bucket: F) 183362306a36Sopenharmony_ci where 183462306a36Sopenharmony_ci F: FnMut(&mut T, &mut T) -> bool, 183562306a36Sopenharmony_ci { 183662306a36Sopenharmony_ci let len = self.len(); 183762306a36Sopenharmony_ci if len <= 1 { 183862306a36Sopenharmony_ci return; 183962306a36Sopenharmony_ci } 184062306a36Sopenharmony_ci 184162306a36Sopenharmony_ci /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */ 184262306a36Sopenharmony_ci struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { 184362306a36Sopenharmony_ci /* Offset of the element we want to check if it is duplicate */ 184462306a36Sopenharmony_ci read: usize, 184562306a36Sopenharmony_ci 184662306a36Sopenharmony_ci /* Offset of the place where we want to place the non-duplicate 184762306a36Sopenharmony_ci * when we find it. */ 184862306a36Sopenharmony_ci write: usize, 184962306a36Sopenharmony_ci 185062306a36Sopenharmony_ci /* The Vec that would need correction if `same_bucket` panicked */ 185162306a36Sopenharmony_ci vec: &'a mut Vec<T, A>, 185262306a36Sopenharmony_ci } 185362306a36Sopenharmony_ci 185462306a36Sopenharmony_ci impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> { 185562306a36Sopenharmony_ci fn drop(&mut self) { 185662306a36Sopenharmony_ci /* This code gets executed when `same_bucket` panics */ 185762306a36Sopenharmony_ci 185862306a36Sopenharmony_ci /* SAFETY: invariant guarantees that `read - write` 185962306a36Sopenharmony_ci * and `len - read` never overflow and that the copy is always 186062306a36Sopenharmony_ci * in-bounds. */ 186162306a36Sopenharmony_ci unsafe { 186262306a36Sopenharmony_ci let ptr = self.vec.as_mut_ptr(); 186362306a36Sopenharmony_ci let len = self.vec.len(); 186462306a36Sopenharmony_ci 186562306a36Sopenharmony_ci /* How many items were left when `same_bucket` panicked. 186662306a36Sopenharmony_ci * Basically vec[read..].len() */ 186762306a36Sopenharmony_ci let items_left = len.wrapping_sub(self.read); 186862306a36Sopenharmony_ci 186962306a36Sopenharmony_ci /* Pointer to first item in vec[write..write+items_left] slice */ 187062306a36Sopenharmony_ci let dropped_ptr = ptr.add(self.write); 187162306a36Sopenharmony_ci /* Pointer to first item in vec[read..] slice */ 187262306a36Sopenharmony_ci let valid_ptr = ptr.add(self.read); 187362306a36Sopenharmony_ci 187462306a36Sopenharmony_ci /* Copy `vec[read..]` to `vec[write..write+items_left]`. 187562306a36Sopenharmony_ci * The slices can overlap, so `copy_nonoverlapping` cannot be used */ 187662306a36Sopenharmony_ci ptr::copy(valid_ptr, dropped_ptr, items_left); 187762306a36Sopenharmony_ci 187862306a36Sopenharmony_ci /* How many items have been already dropped 187962306a36Sopenharmony_ci * Basically vec[read..write].len() */ 188062306a36Sopenharmony_ci let dropped = self.read.wrapping_sub(self.write); 188162306a36Sopenharmony_ci 188262306a36Sopenharmony_ci self.vec.set_len(len - dropped); 188362306a36Sopenharmony_ci } 188462306a36Sopenharmony_ci } 188562306a36Sopenharmony_ci } 188662306a36Sopenharmony_ci 188762306a36Sopenharmony_ci let mut gap = FillGapOnDrop { read: 1, write: 1, vec: self }; 188862306a36Sopenharmony_ci let ptr = gap.vec.as_mut_ptr(); 188962306a36Sopenharmony_ci 189062306a36Sopenharmony_ci /* Drop items while going through Vec, it should be more efficient than 189162306a36Sopenharmony_ci * doing slice partition_dedup + truncate */ 189262306a36Sopenharmony_ci 189362306a36Sopenharmony_ci /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr 189462306a36Sopenharmony_ci * are always in-bounds and read_ptr never aliases prev_ptr */ 189562306a36Sopenharmony_ci unsafe { 189662306a36Sopenharmony_ci while gap.read < len { 189762306a36Sopenharmony_ci let read_ptr = ptr.add(gap.read); 189862306a36Sopenharmony_ci let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); 189962306a36Sopenharmony_ci 190062306a36Sopenharmony_ci if same_bucket(&mut *read_ptr, &mut *prev_ptr) { 190162306a36Sopenharmony_ci // Increase `gap.read` now since the drop may panic. 190262306a36Sopenharmony_ci gap.read += 1; 190362306a36Sopenharmony_ci /* We have found duplicate, drop it in-place */ 190462306a36Sopenharmony_ci ptr::drop_in_place(read_ptr); 190562306a36Sopenharmony_ci } else { 190662306a36Sopenharmony_ci let write_ptr = ptr.add(gap.write); 190762306a36Sopenharmony_ci 190862306a36Sopenharmony_ci /* Because `read_ptr` can be equal to `write_ptr`, we either 190962306a36Sopenharmony_ci * have to use `copy` or conditional `copy_nonoverlapping`. 191062306a36Sopenharmony_ci * Looks like the first option is faster. */ 191162306a36Sopenharmony_ci ptr::copy(read_ptr, write_ptr, 1); 191262306a36Sopenharmony_ci 191362306a36Sopenharmony_ci /* We have filled that place, so go further */ 191462306a36Sopenharmony_ci gap.write += 1; 191562306a36Sopenharmony_ci gap.read += 1; 191662306a36Sopenharmony_ci } 191762306a36Sopenharmony_ci } 191862306a36Sopenharmony_ci 191962306a36Sopenharmony_ci /* Technically we could let `gap` clean up with its Drop, but 192062306a36Sopenharmony_ci * when `same_bucket` is guaranteed to not panic, this bloats a little 192162306a36Sopenharmony_ci * the codegen, so we just do it manually */ 192262306a36Sopenharmony_ci gap.vec.set_len(gap.write); 192362306a36Sopenharmony_ci mem::forget(gap); 192462306a36Sopenharmony_ci } 192562306a36Sopenharmony_ci } 192662306a36Sopenharmony_ci 192762306a36Sopenharmony_ci /// Appends an element to the back of a collection. 192862306a36Sopenharmony_ci /// 192962306a36Sopenharmony_ci /// # Panics 193062306a36Sopenharmony_ci /// 193162306a36Sopenharmony_ci /// Panics if the new capacity exceeds `isize::MAX` bytes. 193262306a36Sopenharmony_ci /// 193362306a36Sopenharmony_ci /// # Examples 193462306a36Sopenharmony_ci /// 193562306a36Sopenharmony_ci /// ``` 193662306a36Sopenharmony_ci /// let mut vec = vec![1, 2]; 193762306a36Sopenharmony_ci /// vec.push(3); 193862306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2, 3]); 193962306a36Sopenharmony_ci /// ``` 194062306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 194162306a36Sopenharmony_ci #[inline] 194262306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 194362306a36Sopenharmony_ci pub fn push(&mut self, value: T) { 194462306a36Sopenharmony_ci // This will panic or abort if we would allocate > isize::MAX bytes 194562306a36Sopenharmony_ci // or if the length increment would overflow for zero-sized types. 194662306a36Sopenharmony_ci if self.len == self.buf.capacity() { 194762306a36Sopenharmony_ci self.buf.reserve_for_push(self.len); 194862306a36Sopenharmony_ci } 194962306a36Sopenharmony_ci unsafe { 195062306a36Sopenharmony_ci let end = self.as_mut_ptr().add(self.len); 195162306a36Sopenharmony_ci ptr::write(end, value); 195262306a36Sopenharmony_ci self.len += 1; 195362306a36Sopenharmony_ci } 195462306a36Sopenharmony_ci } 195562306a36Sopenharmony_ci 195662306a36Sopenharmony_ci /// Tries to append an element to the back of a collection. 195762306a36Sopenharmony_ci /// 195862306a36Sopenharmony_ci /// # Examples 195962306a36Sopenharmony_ci /// 196062306a36Sopenharmony_ci /// ``` 196162306a36Sopenharmony_ci /// let mut vec = vec![1, 2]; 196262306a36Sopenharmony_ci /// vec.try_push(3).unwrap(); 196362306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2, 3]); 196462306a36Sopenharmony_ci /// ``` 196562306a36Sopenharmony_ci #[inline] 196662306a36Sopenharmony_ci #[stable(feature = "kernel", since = "1.0.0")] 196762306a36Sopenharmony_ci pub fn try_push(&mut self, value: T) -> Result<(), TryReserveError> { 196862306a36Sopenharmony_ci if self.len == self.buf.capacity() { 196962306a36Sopenharmony_ci self.buf.try_reserve_for_push(self.len)?; 197062306a36Sopenharmony_ci } 197162306a36Sopenharmony_ci unsafe { 197262306a36Sopenharmony_ci let end = self.as_mut_ptr().add(self.len); 197362306a36Sopenharmony_ci ptr::write(end, value); 197462306a36Sopenharmony_ci self.len += 1; 197562306a36Sopenharmony_ci } 197662306a36Sopenharmony_ci Ok(()) 197762306a36Sopenharmony_ci } 197862306a36Sopenharmony_ci 197962306a36Sopenharmony_ci /// Appends an element if there is sufficient spare capacity, otherwise an error is returned 198062306a36Sopenharmony_ci /// with the element. 198162306a36Sopenharmony_ci /// 198262306a36Sopenharmony_ci /// Unlike [`push`] this method will not reallocate when there's insufficient capacity. 198362306a36Sopenharmony_ci /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity. 198462306a36Sopenharmony_ci /// 198562306a36Sopenharmony_ci /// [`push`]: Vec::push 198662306a36Sopenharmony_ci /// [`reserve`]: Vec::reserve 198762306a36Sopenharmony_ci /// [`try_reserve`]: Vec::try_reserve 198862306a36Sopenharmony_ci /// 198962306a36Sopenharmony_ci /// # Examples 199062306a36Sopenharmony_ci /// 199162306a36Sopenharmony_ci /// A manual, panic-free alternative to [`FromIterator`]: 199262306a36Sopenharmony_ci /// 199362306a36Sopenharmony_ci /// ``` 199462306a36Sopenharmony_ci /// #![feature(vec_push_within_capacity)] 199562306a36Sopenharmony_ci /// 199662306a36Sopenharmony_ci /// use std::collections::TryReserveError; 199762306a36Sopenharmony_ci /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> { 199862306a36Sopenharmony_ci /// let mut vec = Vec::new(); 199962306a36Sopenharmony_ci /// for value in iter { 200062306a36Sopenharmony_ci /// if let Err(value) = vec.push_within_capacity(value) { 200162306a36Sopenharmony_ci /// vec.try_reserve(1)?; 200262306a36Sopenharmony_ci /// // this cannot fail, the previous line either returned or added at least 1 free slot 200362306a36Sopenharmony_ci /// let _ = vec.push_within_capacity(value); 200462306a36Sopenharmony_ci /// } 200562306a36Sopenharmony_ci /// } 200662306a36Sopenharmony_ci /// Ok(vec) 200762306a36Sopenharmony_ci /// } 200862306a36Sopenharmony_ci /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100))); 200962306a36Sopenharmony_ci /// ``` 201062306a36Sopenharmony_ci #[inline] 201162306a36Sopenharmony_ci #[unstable(feature = "vec_push_within_capacity", issue = "100486")] 201262306a36Sopenharmony_ci pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> { 201362306a36Sopenharmony_ci if self.len == self.buf.capacity() { 201462306a36Sopenharmony_ci return Err(value); 201562306a36Sopenharmony_ci } 201662306a36Sopenharmony_ci unsafe { 201762306a36Sopenharmony_ci let end = self.as_mut_ptr().add(self.len); 201862306a36Sopenharmony_ci ptr::write(end, value); 201962306a36Sopenharmony_ci self.len += 1; 202062306a36Sopenharmony_ci } 202162306a36Sopenharmony_ci Ok(()) 202262306a36Sopenharmony_ci } 202362306a36Sopenharmony_ci 202462306a36Sopenharmony_ci /// Removes the last element from a vector and returns it, or [`None`] if it 202562306a36Sopenharmony_ci /// is empty. 202662306a36Sopenharmony_ci /// 202762306a36Sopenharmony_ci /// If you'd like to pop the first element, consider using 202862306a36Sopenharmony_ci /// [`VecDeque::pop_front`] instead. 202962306a36Sopenharmony_ci /// 203062306a36Sopenharmony_ci /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front 203162306a36Sopenharmony_ci /// 203262306a36Sopenharmony_ci /// # Examples 203362306a36Sopenharmony_ci /// 203462306a36Sopenharmony_ci /// ``` 203562306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3]; 203662306a36Sopenharmony_ci /// assert_eq!(vec.pop(), Some(3)); 203762306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2]); 203862306a36Sopenharmony_ci /// ``` 203962306a36Sopenharmony_ci #[inline] 204062306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 204162306a36Sopenharmony_ci pub fn pop(&mut self) -> Option<T> { 204262306a36Sopenharmony_ci if self.len == 0 { 204362306a36Sopenharmony_ci None 204462306a36Sopenharmony_ci } else { 204562306a36Sopenharmony_ci unsafe { 204662306a36Sopenharmony_ci self.len -= 1; 204762306a36Sopenharmony_ci Some(ptr::read(self.as_ptr().add(self.len()))) 204862306a36Sopenharmony_ci } 204962306a36Sopenharmony_ci } 205062306a36Sopenharmony_ci } 205162306a36Sopenharmony_ci 205262306a36Sopenharmony_ci /// Moves all the elements of `other` into `self`, leaving `other` empty. 205362306a36Sopenharmony_ci /// 205462306a36Sopenharmony_ci /// # Panics 205562306a36Sopenharmony_ci /// 205662306a36Sopenharmony_ci /// Panics if the new capacity exceeds `isize::MAX` bytes. 205762306a36Sopenharmony_ci /// 205862306a36Sopenharmony_ci /// # Examples 205962306a36Sopenharmony_ci /// 206062306a36Sopenharmony_ci /// ``` 206162306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3]; 206262306a36Sopenharmony_ci /// let mut vec2 = vec![4, 5, 6]; 206362306a36Sopenharmony_ci /// vec.append(&mut vec2); 206462306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); 206562306a36Sopenharmony_ci /// assert_eq!(vec2, []); 206662306a36Sopenharmony_ci /// ``` 206762306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 206862306a36Sopenharmony_ci #[inline] 206962306a36Sopenharmony_ci #[stable(feature = "append", since = "1.4.0")] 207062306a36Sopenharmony_ci pub fn append(&mut self, other: &mut Self) { 207162306a36Sopenharmony_ci unsafe { 207262306a36Sopenharmony_ci self.append_elements(other.as_slice() as _); 207362306a36Sopenharmony_ci other.set_len(0); 207462306a36Sopenharmony_ci } 207562306a36Sopenharmony_ci } 207662306a36Sopenharmony_ci 207762306a36Sopenharmony_ci /// Appends elements to `self` from other buffer. 207862306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 207962306a36Sopenharmony_ci #[inline] 208062306a36Sopenharmony_ci unsafe fn append_elements(&mut self, other: *const [T]) { 208162306a36Sopenharmony_ci let count = unsafe { (*other).len() }; 208262306a36Sopenharmony_ci self.reserve(count); 208362306a36Sopenharmony_ci let len = self.len(); 208462306a36Sopenharmony_ci unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 208562306a36Sopenharmony_ci self.len += count; 208662306a36Sopenharmony_ci } 208762306a36Sopenharmony_ci 208862306a36Sopenharmony_ci /// Tries to append elements to `self` from other buffer. 208962306a36Sopenharmony_ci #[inline] 209062306a36Sopenharmony_ci unsafe fn try_append_elements(&mut self, other: *const [T]) -> Result<(), TryReserveError> { 209162306a36Sopenharmony_ci let count = unsafe { (*other).len() }; 209262306a36Sopenharmony_ci self.try_reserve(count)?; 209362306a36Sopenharmony_ci let len = self.len(); 209462306a36Sopenharmony_ci unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 209562306a36Sopenharmony_ci self.len += count; 209662306a36Sopenharmony_ci Ok(()) 209762306a36Sopenharmony_ci } 209862306a36Sopenharmony_ci 209962306a36Sopenharmony_ci /// Removes the specified range from the vector in bulk, returning all 210062306a36Sopenharmony_ci /// removed elements as an iterator. If the iterator is dropped before 210162306a36Sopenharmony_ci /// being fully consumed, it drops the remaining removed elements. 210262306a36Sopenharmony_ci /// 210362306a36Sopenharmony_ci /// The returned iterator keeps a mutable borrow on the vector to optimize 210462306a36Sopenharmony_ci /// its implementation. 210562306a36Sopenharmony_ci /// 210662306a36Sopenharmony_ci /// # Panics 210762306a36Sopenharmony_ci /// 210862306a36Sopenharmony_ci /// Panics if the starting point is greater than the end point or if 210962306a36Sopenharmony_ci /// the end point is greater than the length of the vector. 211062306a36Sopenharmony_ci /// 211162306a36Sopenharmony_ci /// # Leaking 211262306a36Sopenharmony_ci /// 211362306a36Sopenharmony_ci /// If the returned iterator goes out of scope without being dropped (due to 211462306a36Sopenharmony_ci /// [`mem::forget`], for example), the vector may have lost and leaked 211562306a36Sopenharmony_ci /// elements arbitrarily, including elements outside the range. 211662306a36Sopenharmony_ci /// 211762306a36Sopenharmony_ci /// # Examples 211862306a36Sopenharmony_ci /// 211962306a36Sopenharmony_ci /// ``` 212062306a36Sopenharmony_ci /// let mut v = vec![1, 2, 3]; 212162306a36Sopenharmony_ci /// let u: Vec<_> = v.drain(1..).collect(); 212262306a36Sopenharmony_ci /// assert_eq!(v, &[1]); 212362306a36Sopenharmony_ci /// assert_eq!(u, &[2, 3]); 212462306a36Sopenharmony_ci /// 212562306a36Sopenharmony_ci /// // A full range clears the vector, like `clear()` does 212662306a36Sopenharmony_ci /// v.drain(..); 212762306a36Sopenharmony_ci /// assert_eq!(v, &[]); 212862306a36Sopenharmony_ci /// ``` 212962306a36Sopenharmony_ci #[stable(feature = "drain", since = "1.6.0")] 213062306a36Sopenharmony_ci pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> 213162306a36Sopenharmony_ci where 213262306a36Sopenharmony_ci R: RangeBounds<usize>, 213362306a36Sopenharmony_ci { 213462306a36Sopenharmony_ci // Memory safety 213562306a36Sopenharmony_ci // 213662306a36Sopenharmony_ci // When the Drain is first created, it shortens the length of 213762306a36Sopenharmony_ci // the source vector to make sure no uninitialized or moved-from elements 213862306a36Sopenharmony_ci // are accessible at all if the Drain's destructor never gets to run. 213962306a36Sopenharmony_ci // 214062306a36Sopenharmony_ci // Drain will ptr::read out the values to remove. 214162306a36Sopenharmony_ci // When finished, remaining tail of the vec is copied back to cover 214262306a36Sopenharmony_ci // the hole, and the vector length is restored to the new length. 214362306a36Sopenharmony_ci // 214462306a36Sopenharmony_ci let len = self.len(); 214562306a36Sopenharmony_ci let Range { start, end } = slice::range(range, ..len); 214662306a36Sopenharmony_ci 214762306a36Sopenharmony_ci unsafe { 214862306a36Sopenharmony_ci // set self.vec length's to start, to be safe in case Drain is leaked 214962306a36Sopenharmony_ci self.set_len(start); 215062306a36Sopenharmony_ci let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start); 215162306a36Sopenharmony_ci Drain { 215262306a36Sopenharmony_ci tail_start: end, 215362306a36Sopenharmony_ci tail_len: len - end, 215462306a36Sopenharmony_ci iter: range_slice.iter(), 215562306a36Sopenharmony_ci vec: NonNull::from(self), 215662306a36Sopenharmony_ci } 215762306a36Sopenharmony_ci } 215862306a36Sopenharmony_ci } 215962306a36Sopenharmony_ci 216062306a36Sopenharmony_ci /// Clears the vector, removing all values. 216162306a36Sopenharmony_ci /// 216262306a36Sopenharmony_ci /// Note that this method has no effect on the allocated capacity 216362306a36Sopenharmony_ci /// of the vector. 216462306a36Sopenharmony_ci /// 216562306a36Sopenharmony_ci /// # Examples 216662306a36Sopenharmony_ci /// 216762306a36Sopenharmony_ci /// ``` 216862306a36Sopenharmony_ci /// let mut v = vec![1, 2, 3]; 216962306a36Sopenharmony_ci /// 217062306a36Sopenharmony_ci /// v.clear(); 217162306a36Sopenharmony_ci /// 217262306a36Sopenharmony_ci /// assert!(v.is_empty()); 217362306a36Sopenharmony_ci /// ``` 217462306a36Sopenharmony_ci #[inline] 217562306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 217662306a36Sopenharmony_ci pub fn clear(&mut self) { 217762306a36Sopenharmony_ci let elems: *mut [T] = self.as_mut_slice(); 217862306a36Sopenharmony_ci 217962306a36Sopenharmony_ci // SAFETY: 218062306a36Sopenharmony_ci // - `elems` comes directly from `as_mut_slice` and is therefore valid. 218162306a36Sopenharmony_ci // - Setting `self.len` before calling `drop_in_place` means that, 218262306a36Sopenharmony_ci // if an element's `Drop` impl panics, the vector's `Drop` impl will 218362306a36Sopenharmony_ci // do nothing (leaking the rest of the elements) instead of dropping 218462306a36Sopenharmony_ci // some twice. 218562306a36Sopenharmony_ci unsafe { 218662306a36Sopenharmony_ci self.len = 0; 218762306a36Sopenharmony_ci ptr::drop_in_place(elems); 218862306a36Sopenharmony_ci } 218962306a36Sopenharmony_ci } 219062306a36Sopenharmony_ci 219162306a36Sopenharmony_ci /// Returns the number of elements in the vector, also referred to 219262306a36Sopenharmony_ci /// as its 'length'. 219362306a36Sopenharmony_ci /// 219462306a36Sopenharmony_ci /// # Examples 219562306a36Sopenharmony_ci /// 219662306a36Sopenharmony_ci /// ``` 219762306a36Sopenharmony_ci /// let a = vec![1, 2, 3]; 219862306a36Sopenharmony_ci /// assert_eq!(a.len(), 3); 219962306a36Sopenharmony_ci /// ``` 220062306a36Sopenharmony_ci #[inline] 220162306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 220262306a36Sopenharmony_ci pub fn len(&self) -> usize { 220362306a36Sopenharmony_ci self.len 220462306a36Sopenharmony_ci } 220562306a36Sopenharmony_ci 220662306a36Sopenharmony_ci /// Returns `true` if the vector contains no elements. 220762306a36Sopenharmony_ci /// 220862306a36Sopenharmony_ci /// # Examples 220962306a36Sopenharmony_ci /// 221062306a36Sopenharmony_ci /// ``` 221162306a36Sopenharmony_ci /// let mut v = Vec::new(); 221262306a36Sopenharmony_ci /// assert!(v.is_empty()); 221362306a36Sopenharmony_ci /// 221462306a36Sopenharmony_ci /// v.push(1); 221562306a36Sopenharmony_ci /// assert!(!v.is_empty()); 221662306a36Sopenharmony_ci /// ``` 221762306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 221862306a36Sopenharmony_ci pub fn is_empty(&self) -> bool { 221962306a36Sopenharmony_ci self.len() == 0 222062306a36Sopenharmony_ci } 222162306a36Sopenharmony_ci 222262306a36Sopenharmony_ci /// Splits the collection into two at the given index. 222362306a36Sopenharmony_ci /// 222462306a36Sopenharmony_ci /// Returns a newly allocated vector containing the elements in the range 222562306a36Sopenharmony_ci /// `[at, len)`. After the call, the original vector will be left containing 222662306a36Sopenharmony_ci /// the elements `[0, at)` with its previous capacity unchanged. 222762306a36Sopenharmony_ci /// 222862306a36Sopenharmony_ci /// # Panics 222962306a36Sopenharmony_ci /// 223062306a36Sopenharmony_ci /// Panics if `at > len`. 223162306a36Sopenharmony_ci /// 223262306a36Sopenharmony_ci /// # Examples 223362306a36Sopenharmony_ci /// 223462306a36Sopenharmony_ci /// ``` 223562306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3]; 223662306a36Sopenharmony_ci /// let vec2 = vec.split_off(1); 223762306a36Sopenharmony_ci /// assert_eq!(vec, [1]); 223862306a36Sopenharmony_ci /// assert_eq!(vec2, [2, 3]); 223962306a36Sopenharmony_ci /// ``` 224062306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 224162306a36Sopenharmony_ci #[inline] 224262306a36Sopenharmony_ci #[must_use = "use `.truncate()` if you don't need the other half"] 224362306a36Sopenharmony_ci #[stable(feature = "split_off", since = "1.4.0")] 224462306a36Sopenharmony_ci pub fn split_off(&mut self, at: usize) -> Self 224562306a36Sopenharmony_ci where 224662306a36Sopenharmony_ci A: Clone, 224762306a36Sopenharmony_ci { 224862306a36Sopenharmony_ci #[cold] 224962306a36Sopenharmony_ci #[inline(never)] 225062306a36Sopenharmony_ci fn assert_failed(at: usize, len: usize) -> ! { 225162306a36Sopenharmony_ci panic!("`at` split index (is {at}) should be <= len (is {len})"); 225262306a36Sopenharmony_ci } 225362306a36Sopenharmony_ci 225462306a36Sopenharmony_ci if at > self.len() { 225562306a36Sopenharmony_ci assert_failed(at, self.len()); 225662306a36Sopenharmony_ci } 225762306a36Sopenharmony_ci 225862306a36Sopenharmony_ci if at == 0 { 225962306a36Sopenharmony_ci // the new vector can take over the original buffer and avoid the copy 226062306a36Sopenharmony_ci return mem::replace( 226162306a36Sopenharmony_ci self, 226262306a36Sopenharmony_ci Vec::with_capacity_in(self.capacity(), self.allocator().clone()), 226362306a36Sopenharmony_ci ); 226462306a36Sopenharmony_ci } 226562306a36Sopenharmony_ci 226662306a36Sopenharmony_ci let other_len = self.len - at; 226762306a36Sopenharmony_ci let mut other = Vec::with_capacity_in(other_len, self.allocator().clone()); 226862306a36Sopenharmony_ci 226962306a36Sopenharmony_ci // Unsafely `set_len` and copy items to `other`. 227062306a36Sopenharmony_ci unsafe { 227162306a36Sopenharmony_ci self.set_len(at); 227262306a36Sopenharmony_ci other.set_len(other_len); 227362306a36Sopenharmony_ci 227462306a36Sopenharmony_ci ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len()); 227562306a36Sopenharmony_ci } 227662306a36Sopenharmony_ci other 227762306a36Sopenharmony_ci } 227862306a36Sopenharmony_ci 227962306a36Sopenharmony_ci /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. 228062306a36Sopenharmony_ci /// 228162306a36Sopenharmony_ci /// If `new_len` is greater than `len`, the `Vec` is extended by the 228262306a36Sopenharmony_ci /// difference, with each additional slot filled with the result of 228362306a36Sopenharmony_ci /// calling the closure `f`. The return values from `f` will end up 228462306a36Sopenharmony_ci /// in the `Vec` in the order they have been generated. 228562306a36Sopenharmony_ci /// 228662306a36Sopenharmony_ci /// If `new_len` is less than `len`, the `Vec` is simply truncated. 228762306a36Sopenharmony_ci /// 228862306a36Sopenharmony_ci /// This method uses a closure to create new values on every push. If 228962306a36Sopenharmony_ci /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you 229062306a36Sopenharmony_ci /// want to use the [`Default`] trait to generate values, you can 229162306a36Sopenharmony_ci /// pass [`Default::default`] as the second argument. 229262306a36Sopenharmony_ci /// 229362306a36Sopenharmony_ci /// # Examples 229462306a36Sopenharmony_ci /// 229562306a36Sopenharmony_ci /// ``` 229662306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3]; 229762306a36Sopenharmony_ci /// vec.resize_with(5, Default::default); 229862306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2, 3, 0, 0]); 229962306a36Sopenharmony_ci /// 230062306a36Sopenharmony_ci /// let mut vec = vec![]; 230162306a36Sopenharmony_ci /// let mut p = 1; 230262306a36Sopenharmony_ci /// vec.resize_with(4, || { p *= 2; p }); 230362306a36Sopenharmony_ci /// assert_eq!(vec, [2, 4, 8, 16]); 230462306a36Sopenharmony_ci /// ``` 230562306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 230662306a36Sopenharmony_ci #[stable(feature = "vec_resize_with", since = "1.33.0")] 230762306a36Sopenharmony_ci pub fn resize_with<F>(&mut self, new_len: usize, f: F) 230862306a36Sopenharmony_ci where 230962306a36Sopenharmony_ci F: FnMut() -> T, 231062306a36Sopenharmony_ci { 231162306a36Sopenharmony_ci let len = self.len(); 231262306a36Sopenharmony_ci if new_len > len { 231362306a36Sopenharmony_ci self.extend_trusted(iter::repeat_with(f).take(new_len - len)); 231462306a36Sopenharmony_ci } else { 231562306a36Sopenharmony_ci self.truncate(new_len); 231662306a36Sopenharmony_ci } 231762306a36Sopenharmony_ci } 231862306a36Sopenharmony_ci 231962306a36Sopenharmony_ci /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, 232062306a36Sopenharmony_ci /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime 232162306a36Sopenharmony_ci /// `'a`. If the type has only static references, or none at all, then this 232262306a36Sopenharmony_ci /// may be chosen to be `'static`. 232362306a36Sopenharmony_ci /// 232462306a36Sopenharmony_ci /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, 232562306a36Sopenharmony_ci /// so the leaked allocation may include unused capacity that is not part 232662306a36Sopenharmony_ci /// of the returned slice. 232762306a36Sopenharmony_ci /// 232862306a36Sopenharmony_ci /// This function is mainly useful for data that lives for the remainder of 232962306a36Sopenharmony_ci /// the program's life. Dropping the returned reference will cause a memory 233062306a36Sopenharmony_ci /// leak. 233162306a36Sopenharmony_ci /// 233262306a36Sopenharmony_ci /// # Examples 233362306a36Sopenharmony_ci /// 233462306a36Sopenharmony_ci /// Simple usage: 233562306a36Sopenharmony_ci /// 233662306a36Sopenharmony_ci /// ``` 233762306a36Sopenharmony_ci /// let x = vec![1, 2, 3]; 233862306a36Sopenharmony_ci /// let static_ref: &'static mut [usize] = x.leak(); 233962306a36Sopenharmony_ci /// static_ref[0] += 1; 234062306a36Sopenharmony_ci /// assert_eq!(static_ref, &[2, 2, 3]); 234162306a36Sopenharmony_ci /// ``` 234262306a36Sopenharmony_ci #[stable(feature = "vec_leak", since = "1.47.0")] 234362306a36Sopenharmony_ci #[inline] 234462306a36Sopenharmony_ci pub fn leak<'a>(self) -> &'a mut [T] 234562306a36Sopenharmony_ci where 234662306a36Sopenharmony_ci A: 'a, 234762306a36Sopenharmony_ci { 234862306a36Sopenharmony_ci let mut me = ManuallyDrop::new(self); 234962306a36Sopenharmony_ci unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) } 235062306a36Sopenharmony_ci } 235162306a36Sopenharmony_ci 235262306a36Sopenharmony_ci /// Returns the remaining spare capacity of the vector as a slice of 235362306a36Sopenharmony_ci /// `MaybeUninit<T>`. 235462306a36Sopenharmony_ci /// 235562306a36Sopenharmony_ci /// The returned slice can be used to fill the vector with data (e.g. by 235662306a36Sopenharmony_ci /// reading from a file) before marking the data as initialized using the 235762306a36Sopenharmony_ci /// [`set_len`] method. 235862306a36Sopenharmony_ci /// 235962306a36Sopenharmony_ci /// [`set_len`]: Vec::set_len 236062306a36Sopenharmony_ci /// 236162306a36Sopenharmony_ci /// # Examples 236262306a36Sopenharmony_ci /// 236362306a36Sopenharmony_ci /// ``` 236462306a36Sopenharmony_ci /// // Allocate vector big enough for 10 elements. 236562306a36Sopenharmony_ci /// let mut v = Vec::with_capacity(10); 236662306a36Sopenharmony_ci /// 236762306a36Sopenharmony_ci /// // Fill in the first 3 elements. 236862306a36Sopenharmony_ci /// let uninit = v.spare_capacity_mut(); 236962306a36Sopenharmony_ci /// uninit[0].write(0); 237062306a36Sopenharmony_ci /// uninit[1].write(1); 237162306a36Sopenharmony_ci /// uninit[2].write(2); 237262306a36Sopenharmony_ci /// 237362306a36Sopenharmony_ci /// // Mark the first 3 elements of the vector as being initialized. 237462306a36Sopenharmony_ci /// unsafe { 237562306a36Sopenharmony_ci /// v.set_len(3); 237662306a36Sopenharmony_ci /// } 237762306a36Sopenharmony_ci /// 237862306a36Sopenharmony_ci /// assert_eq!(&v, &[0, 1, 2]); 237962306a36Sopenharmony_ci /// ``` 238062306a36Sopenharmony_ci #[stable(feature = "vec_spare_capacity", since = "1.60.0")] 238162306a36Sopenharmony_ci #[inline] 238262306a36Sopenharmony_ci pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { 238362306a36Sopenharmony_ci // Note: 238462306a36Sopenharmony_ci // This method is not implemented in terms of `split_at_spare_mut`, 238562306a36Sopenharmony_ci // to prevent invalidation of pointers to the buffer. 238662306a36Sopenharmony_ci unsafe { 238762306a36Sopenharmony_ci slice::from_raw_parts_mut( 238862306a36Sopenharmony_ci self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>, 238962306a36Sopenharmony_ci self.buf.capacity() - self.len, 239062306a36Sopenharmony_ci ) 239162306a36Sopenharmony_ci } 239262306a36Sopenharmony_ci } 239362306a36Sopenharmony_ci 239462306a36Sopenharmony_ci /// Returns vector content as a slice of `T`, along with the remaining spare 239562306a36Sopenharmony_ci /// capacity of the vector as a slice of `MaybeUninit<T>`. 239662306a36Sopenharmony_ci /// 239762306a36Sopenharmony_ci /// The returned spare capacity slice can be used to fill the vector with data 239862306a36Sopenharmony_ci /// (e.g. by reading from a file) before marking the data as initialized using 239962306a36Sopenharmony_ci /// the [`set_len`] method. 240062306a36Sopenharmony_ci /// 240162306a36Sopenharmony_ci /// [`set_len`]: Vec::set_len 240262306a36Sopenharmony_ci /// 240362306a36Sopenharmony_ci /// Note that this is a low-level API, which should be used with care for 240462306a36Sopenharmony_ci /// optimization purposes. If you need to append data to a `Vec` 240562306a36Sopenharmony_ci /// you can use [`push`], [`extend`], [`extend_from_slice`], 240662306a36Sopenharmony_ci /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or 240762306a36Sopenharmony_ci /// [`resize_with`], depending on your exact needs. 240862306a36Sopenharmony_ci /// 240962306a36Sopenharmony_ci /// [`push`]: Vec::push 241062306a36Sopenharmony_ci /// [`extend`]: Vec::extend 241162306a36Sopenharmony_ci /// [`extend_from_slice`]: Vec::extend_from_slice 241262306a36Sopenharmony_ci /// [`extend_from_within`]: Vec::extend_from_within 241362306a36Sopenharmony_ci /// [`insert`]: Vec::insert 241462306a36Sopenharmony_ci /// [`append`]: Vec::append 241562306a36Sopenharmony_ci /// [`resize`]: Vec::resize 241662306a36Sopenharmony_ci /// [`resize_with`]: Vec::resize_with 241762306a36Sopenharmony_ci /// 241862306a36Sopenharmony_ci /// # Examples 241962306a36Sopenharmony_ci /// 242062306a36Sopenharmony_ci /// ``` 242162306a36Sopenharmony_ci /// #![feature(vec_split_at_spare)] 242262306a36Sopenharmony_ci /// 242362306a36Sopenharmony_ci /// let mut v = vec![1, 1, 2]; 242462306a36Sopenharmony_ci /// 242562306a36Sopenharmony_ci /// // Reserve additional space big enough for 10 elements. 242662306a36Sopenharmony_ci /// v.reserve(10); 242762306a36Sopenharmony_ci /// 242862306a36Sopenharmony_ci /// let (init, uninit) = v.split_at_spare_mut(); 242962306a36Sopenharmony_ci /// let sum = init.iter().copied().sum::<u32>(); 243062306a36Sopenharmony_ci /// 243162306a36Sopenharmony_ci /// // Fill in the next 4 elements. 243262306a36Sopenharmony_ci /// uninit[0].write(sum); 243362306a36Sopenharmony_ci /// uninit[1].write(sum * 2); 243462306a36Sopenharmony_ci /// uninit[2].write(sum * 3); 243562306a36Sopenharmony_ci /// uninit[3].write(sum * 4); 243662306a36Sopenharmony_ci /// 243762306a36Sopenharmony_ci /// // Mark the 4 elements of the vector as being initialized. 243862306a36Sopenharmony_ci /// unsafe { 243962306a36Sopenharmony_ci /// let len = v.len(); 244062306a36Sopenharmony_ci /// v.set_len(len + 4); 244162306a36Sopenharmony_ci /// } 244262306a36Sopenharmony_ci /// 244362306a36Sopenharmony_ci /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]); 244462306a36Sopenharmony_ci /// ``` 244562306a36Sopenharmony_ci #[unstable(feature = "vec_split_at_spare", issue = "81944")] 244662306a36Sopenharmony_ci #[inline] 244762306a36Sopenharmony_ci pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) { 244862306a36Sopenharmony_ci // SAFETY: 244962306a36Sopenharmony_ci // - len is ignored and so never changed 245062306a36Sopenharmony_ci let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() }; 245162306a36Sopenharmony_ci (init, spare) 245262306a36Sopenharmony_ci } 245362306a36Sopenharmony_ci 245462306a36Sopenharmony_ci /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`. 245562306a36Sopenharmony_ci /// 245662306a36Sopenharmony_ci /// This method provides unique access to all vec parts at once in `extend_from_within`. 245762306a36Sopenharmony_ci unsafe fn split_at_spare_mut_with_len( 245862306a36Sopenharmony_ci &mut self, 245962306a36Sopenharmony_ci ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) { 246062306a36Sopenharmony_ci let ptr = self.as_mut_ptr(); 246162306a36Sopenharmony_ci // SAFETY: 246262306a36Sopenharmony_ci // - `ptr` is guaranteed to be valid for `self.len` elements 246362306a36Sopenharmony_ci // - but the allocation extends out to `self.buf.capacity()` elements, possibly 246462306a36Sopenharmony_ci // uninitialized 246562306a36Sopenharmony_ci let spare_ptr = unsafe { ptr.add(self.len) }; 246662306a36Sopenharmony_ci let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>(); 246762306a36Sopenharmony_ci let spare_len = self.buf.capacity() - self.len; 246862306a36Sopenharmony_ci 246962306a36Sopenharmony_ci // SAFETY: 247062306a36Sopenharmony_ci // - `ptr` is guaranteed to be valid for `self.len` elements 247162306a36Sopenharmony_ci // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized` 247262306a36Sopenharmony_ci unsafe { 247362306a36Sopenharmony_ci let initialized = slice::from_raw_parts_mut(ptr, self.len); 247462306a36Sopenharmony_ci let spare = slice::from_raw_parts_mut(spare_ptr, spare_len); 247562306a36Sopenharmony_ci 247662306a36Sopenharmony_ci (initialized, spare, &mut self.len) 247762306a36Sopenharmony_ci } 247862306a36Sopenharmony_ci } 247962306a36Sopenharmony_ci} 248062306a36Sopenharmony_ci 248162306a36Sopenharmony_ciimpl<T: Clone, A: Allocator> Vec<T, A> { 248262306a36Sopenharmony_ci /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. 248362306a36Sopenharmony_ci /// 248462306a36Sopenharmony_ci /// If `new_len` is greater than `len`, the `Vec` is extended by the 248562306a36Sopenharmony_ci /// difference, with each additional slot filled with `value`. 248662306a36Sopenharmony_ci /// If `new_len` is less than `len`, the `Vec` is simply truncated. 248762306a36Sopenharmony_ci /// 248862306a36Sopenharmony_ci /// This method requires `T` to implement [`Clone`], 248962306a36Sopenharmony_ci /// in order to be able to clone the passed value. 249062306a36Sopenharmony_ci /// If you need more flexibility (or want to rely on [`Default`] instead of 249162306a36Sopenharmony_ci /// [`Clone`]), use [`Vec::resize_with`]. 249262306a36Sopenharmony_ci /// If you only need to resize to a smaller size, use [`Vec::truncate`]. 249362306a36Sopenharmony_ci /// 249462306a36Sopenharmony_ci /// # Examples 249562306a36Sopenharmony_ci /// 249662306a36Sopenharmony_ci /// ``` 249762306a36Sopenharmony_ci /// let mut vec = vec!["hello"]; 249862306a36Sopenharmony_ci /// vec.resize(3, "world"); 249962306a36Sopenharmony_ci /// assert_eq!(vec, ["hello", "world", "world"]); 250062306a36Sopenharmony_ci /// 250162306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3, 4]; 250262306a36Sopenharmony_ci /// vec.resize(2, 0); 250362306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2]); 250462306a36Sopenharmony_ci /// ``` 250562306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 250662306a36Sopenharmony_ci #[stable(feature = "vec_resize", since = "1.5.0")] 250762306a36Sopenharmony_ci pub fn resize(&mut self, new_len: usize, value: T) { 250862306a36Sopenharmony_ci let len = self.len(); 250962306a36Sopenharmony_ci 251062306a36Sopenharmony_ci if new_len > len { 251162306a36Sopenharmony_ci self.extend_with(new_len - len, value) 251262306a36Sopenharmony_ci } else { 251362306a36Sopenharmony_ci self.truncate(new_len); 251462306a36Sopenharmony_ci } 251562306a36Sopenharmony_ci } 251662306a36Sopenharmony_ci 251762306a36Sopenharmony_ci /// Tries to resize the `Vec` in-place so that `len` is equal to `new_len`. 251862306a36Sopenharmony_ci /// 251962306a36Sopenharmony_ci /// If `new_len` is greater than `len`, the `Vec` is extended by the 252062306a36Sopenharmony_ci /// difference, with each additional slot filled with `value`. 252162306a36Sopenharmony_ci /// If `new_len` is less than `len`, the `Vec` is simply truncated. 252262306a36Sopenharmony_ci /// 252362306a36Sopenharmony_ci /// This method requires `T` to implement [`Clone`], 252462306a36Sopenharmony_ci /// in order to be able to clone the passed value. 252562306a36Sopenharmony_ci /// If you need more flexibility (or want to rely on [`Default`] instead of 252662306a36Sopenharmony_ci /// [`Clone`]), use [`Vec::resize_with`]. 252762306a36Sopenharmony_ci /// If you only need to resize to a smaller size, use [`Vec::truncate`]. 252862306a36Sopenharmony_ci /// 252962306a36Sopenharmony_ci /// # Examples 253062306a36Sopenharmony_ci /// 253162306a36Sopenharmony_ci /// ``` 253262306a36Sopenharmony_ci /// let mut vec = vec!["hello"]; 253362306a36Sopenharmony_ci /// vec.try_resize(3, "world").unwrap(); 253462306a36Sopenharmony_ci /// assert_eq!(vec, ["hello", "world", "world"]); 253562306a36Sopenharmony_ci /// 253662306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 3, 4]; 253762306a36Sopenharmony_ci /// vec.try_resize(2, 0).unwrap(); 253862306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2]); 253962306a36Sopenharmony_ci /// 254062306a36Sopenharmony_ci /// let mut vec = vec![42]; 254162306a36Sopenharmony_ci /// let result = vec.try_resize(usize::MAX, 0); 254262306a36Sopenharmony_ci /// assert!(result.is_err()); 254362306a36Sopenharmony_ci /// ``` 254462306a36Sopenharmony_ci #[stable(feature = "kernel", since = "1.0.0")] 254562306a36Sopenharmony_ci pub fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError> { 254662306a36Sopenharmony_ci let len = self.len(); 254762306a36Sopenharmony_ci 254862306a36Sopenharmony_ci if new_len > len { 254962306a36Sopenharmony_ci self.try_extend_with(new_len - len, value) 255062306a36Sopenharmony_ci } else { 255162306a36Sopenharmony_ci self.truncate(new_len); 255262306a36Sopenharmony_ci Ok(()) 255362306a36Sopenharmony_ci } 255462306a36Sopenharmony_ci } 255562306a36Sopenharmony_ci 255662306a36Sopenharmony_ci /// Clones and appends all elements in a slice to the `Vec`. 255762306a36Sopenharmony_ci /// 255862306a36Sopenharmony_ci /// Iterates over the slice `other`, clones each element, and then appends 255962306a36Sopenharmony_ci /// it to this `Vec`. The `other` slice is traversed in-order. 256062306a36Sopenharmony_ci /// 256162306a36Sopenharmony_ci /// Note that this function is same as [`extend`] except that it is 256262306a36Sopenharmony_ci /// specialized to work with slices instead. If and when Rust gets 256362306a36Sopenharmony_ci /// specialization this function will likely be deprecated (but still 256462306a36Sopenharmony_ci /// available). 256562306a36Sopenharmony_ci /// 256662306a36Sopenharmony_ci /// # Examples 256762306a36Sopenharmony_ci /// 256862306a36Sopenharmony_ci /// ``` 256962306a36Sopenharmony_ci /// let mut vec = vec![1]; 257062306a36Sopenharmony_ci /// vec.extend_from_slice(&[2, 3, 4]); 257162306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2, 3, 4]); 257262306a36Sopenharmony_ci /// ``` 257362306a36Sopenharmony_ci /// 257462306a36Sopenharmony_ci /// [`extend`]: Vec::extend 257562306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 257662306a36Sopenharmony_ci #[stable(feature = "vec_extend_from_slice", since = "1.6.0")] 257762306a36Sopenharmony_ci pub fn extend_from_slice(&mut self, other: &[T]) { 257862306a36Sopenharmony_ci self.spec_extend(other.iter()) 257962306a36Sopenharmony_ci } 258062306a36Sopenharmony_ci 258162306a36Sopenharmony_ci /// Tries to clone and append all elements in a slice to the `Vec`. 258262306a36Sopenharmony_ci /// 258362306a36Sopenharmony_ci /// Iterates over the slice `other`, clones each element, and then appends 258462306a36Sopenharmony_ci /// it to this `Vec`. The `other` slice is traversed in-order. 258562306a36Sopenharmony_ci /// 258662306a36Sopenharmony_ci /// Note that this function is same as [`extend`] except that it is 258762306a36Sopenharmony_ci /// specialized to work with slices instead. If and when Rust gets 258862306a36Sopenharmony_ci /// specialization this function will likely be deprecated (but still 258962306a36Sopenharmony_ci /// available). 259062306a36Sopenharmony_ci /// 259162306a36Sopenharmony_ci /// # Examples 259262306a36Sopenharmony_ci /// 259362306a36Sopenharmony_ci /// ``` 259462306a36Sopenharmony_ci /// let mut vec = vec![1]; 259562306a36Sopenharmony_ci /// vec.try_extend_from_slice(&[2, 3, 4]).unwrap(); 259662306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2, 3, 4]); 259762306a36Sopenharmony_ci /// ``` 259862306a36Sopenharmony_ci /// 259962306a36Sopenharmony_ci /// [`extend`]: Vec::extend 260062306a36Sopenharmony_ci #[stable(feature = "kernel", since = "1.0.0")] 260162306a36Sopenharmony_ci pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), TryReserveError> { 260262306a36Sopenharmony_ci self.try_spec_extend(other.iter()) 260362306a36Sopenharmony_ci } 260462306a36Sopenharmony_ci 260562306a36Sopenharmony_ci /// Copies elements from `src` range to the end of the vector. 260662306a36Sopenharmony_ci /// 260762306a36Sopenharmony_ci /// # Panics 260862306a36Sopenharmony_ci /// 260962306a36Sopenharmony_ci /// Panics if the starting point is greater than the end point or if 261062306a36Sopenharmony_ci /// the end point is greater than the length of the vector. 261162306a36Sopenharmony_ci /// 261262306a36Sopenharmony_ci /// # Examples 261362306a36Sopenharmony_ci /// 261462306a36Sopenharmony_ci /// ``` 261562306a36Sopenharmony_ci /// let mut vec = vec![0, 1, 2, 3, 4]; 261662306a36Sopenharmony_ci /// 261762306a36Sopenharmony_ci /// vec.extend_from_within(2..); 261862306a36Sopenharmony_ci /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]); 261962306a36Sopenharmony_ci /// 262062306a36Sopenharmony_ci /// vec.extend_from_within(..2); 262162306a36Sopenharmony_ci /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]); 262262306a36Sopenharmony_ci /// 262362306a36Sopenharmony_ci /// vec.extend_from_within(4..8); 262462306a36Sopenharmony_ci /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]); 262562306a36Sopenharmony_ci /// ``` 262662306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 262762306a36Sopenharmony_ci #[stable(feature = "vec_extend_from_within", since = "1.53.0")] 262862306a36Sopenharmony_ci pub fn extend_from_within<R>(&mut self, src: R) 262962306a36Sopenharmony_ci where 263062306a36Sopenharmony_ci R: RangeBounds<usize>, 263162306a36Sopenharmony_ci { 263262306a36Sopenharmony_ci let range = slice::range(src, ..self.len()); 263362306a36Sopenharmony_ci self.reserve(range.len()); 263462306a36Sopenharmony_ci 263562306a36Sopenharmony_ci // SAFETY: 263662306a36Sopenharmony_ci // - `slice::range` guarantees that the given range is valid for indexing self 263762306a36Sopenharmony_ci unsafe { 263862306a36Sopenharmony_ci self.spec_extend_from_within(range); 263962306a36Sopenharmony_ci } 264062306a36Sopenharmony_ci } 264162306a36Sopenharmony_ci} 264262306a36Sopenharmony_ci 264362306a36Sopenharmony_ciimpl<T, A: Allocator, const N: usize> Vec<[T; N], A> { 264462306a36Sopenharmony_ci /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`. 264562306a36Sopenharmony_ci /// 264662306a36Sopenharmony_ci /// # Panics 264762306a36Sopenharmony_ci /// 264862306a36Sopenharmony_ci /// Panics if the length of the resulting vector would overflow a `usize`. 264962306a36Sopenharmony_ci /// 265062306a36Sopenharmony_ci /// This is only possible when flattening a vector of arrays of zero-sized 265162306a36Sopenharmony_ci /// types, and thus tends to be irrelevant in practice. If 265262306a36Sopenharmony_ci /// `size_of::<T>() > 0`, this will never panic. 265362306a36Sopenharmony_ci /// 265462306a36Sopenharmony_ci /// # Examples 265562306a36Sopenharmony_ci /// 265662306a36Sopenharmony_ci /// ``` 265762306a36Sopenharmony_ci /// #![feature(slice_flatten)] 265862306a36Sopenharmony_ci /// 265962306a36Sopenharmony_ci /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]]; 266062306a36Sopenharmony_ci /// assert_eq!(vec.pop(), Some([7, 8, 9])); 266162306a36Sopenharmony_ci /// 266262306a36Sopenharmony_ci /// let mut flattened = vec.into_flattened(); 266362306a36Sopenharmony_ci /// assert_eq!(flattened.pop(), Some(6)); 266462306a36Sopenharmony_ci /// ``` 266562306a36Sopenharmony_ci #[unstable(feature = "slice_flatten", issue = "95629")] 266662306a36Sopenharmony_ci pub fn into_flattened(self) -> Vec<T, A> { 266762306a36Sopenharmony_ci let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc(); 266862306a36Sopenharmony_ci let (new_len, new_cap) = if T::IS_ZST { 266962306a36Sopenharmony_ci (len.checked_mul(N).expect("vec len overflow"), usize::MAX) 267062306a36Sopenharmony_ci } else { 267162306a36Sopenharmony_ci // SAFETY: 267262306a36Sopenharmony_ci // - `cap * N` cannot overflow because the allocation is already in 267362306a36Sopenharmony_ci // the address space. 267462306a36Sopenharmony_ci // - Each `[T; N]` has `N` valid elements, so there are `len * N` 267562306a36Sopenharmony_ci // valid elements in the allocation. 267662306a36Sopenharmony_ci unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) } 267762306a36Sopenharmony_ci }; 267862306a36Sopenharmony_ci // SAFETY: 267962306a36Sopenharmony_ci // - `ptr` was allocated by `self` 268062306a36Sopenharmony_ci // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`. 268162306a36Sopenharmony_ci // - `new_cap` refers to the same sized allocation as `cap` because 268262306a36Sopenharmony_ci // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()` 268362306a36Sopenharmony_ci // - `len` <= `cap`, so `len * N` <= `cap * N`. 268462306a36Sopenharmony_ci unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) } 268562306a36Sopenharmony_ci } 268662306a36Sopenharmony_ci} 268762306a36Sopenharmony_ci 268862306a36Sopenharmony_ciimpl<T: Clone, A: Allocator> Vec<T, A> { 268962306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 269062306a36Sopenharmony_ci /// Extend the vector by `n` clones of value. 269162306a36Sopenharmony_ci fn extend_with(&mut self, n: usize, value: T) { 269262306a36Sopenharmony_ci self.reserve(n); 269362306a36Sopenharmony_ci 269462306a36Sopenharmony_ci unsafe { 269562306a36Sopenharmony_ci let mut ptr = self.as_mut_ptr().add(self.len()); 269662306a36Sopenharmony_ci // Use SetLenOnDrop to work around bug where compiler 269762306a36Sopenharmony_ci // might not realize the store through `ptr` through self.set_len() 269862306a36Sopenharmony_ci // don't alias. 269962306a36Sopenharmony_ci let mut local_len = SetLenOnDrop::new(&mut self.len); 270062306a36Sopenharmony_ci 270162306a36Sopenharmony_ci // Write all elements except the last one 270262306a36Sopenharmony_ci for _ in 1..n { 270362306a36Sopenharmony_ci ptr::write(ptr, value.clone()); 270462306a36Sopenharmony_ci ptr = ptr.add(1); 270562306a36Sopenharmony_ci // Increment the length in every step in case clone() panics 270662306a36Sopenharmony_ci local_len.increment_len(1); 270762306a36Sopenharmony_ci } 270862306a36Sopenharmony_ci 270962306a36Sopenharmony_ci if n > 0 { 271062306a36Sopenharmony_ci // We can write the last element directly without cloning needlessly 271162306a36Sopenharmony_ci ptr::write(ptr, value); 271262306a36Sopenharmony_ci local_len.increment_len(1); 271362306a36Sopenharmony_ci } 271462306a36Sopenharmony_ci 271562306a36Sopenharmony_ci // len set by scope guard 271662306a36Sopenharmony_ci } 271762306a36Sopenharmony_ci } 271862306a36Sopenharmony_ci 271962306a36Sopenharmony_ci /// Try to extend the vector by `n` clones of value. 272062306a36Sopenharmony_ci fn try_extend_with(&mut self, n: usize, value: T) -> Result<(), TryReserveError> { 272162306a36Sopenharmony_ci self.try_reserve(n)?; 272262306a36Sopenharmony_ci 272362306a36Sopenharmony_ci unsafe { 272462306a36Sopenharmony_ci let mut ptr = self.as_mut_ptr().add(self.len()); 272562306a36Sopenharmony_ci // Use SetLenOnDrop to work around bug where compiler 272662306a36Sopenharmony_ci // might not realize the store through `ptr` through self.set_len() 272762306a36Sopenharmony_ci // don't alias. 272862306a36Sopenharmony_ci let mut local_len = SetLenOnDrop::new(&mut self.len); 272962306a36Sopenharmony_ci 273062306a36Sopenharmony_ci // Write all elements except the last one 273162306a36Sopenharmony_ci for _ in 1..n { 273262306a36Sopenharmony_ci ptr::write(ptr, value.clone()); 273362306a36Sopenharmony_ci ptr = ptr.add(1); 273462306a36Sopenharmony_ci // Increment the length in every step in case clone() panics 273562306a36Sopenharmony_ci local_len.increment_len(1); 273662306a36Sopenharmony_ci } 273762306a36Sopenharmony_ci 273862306a36Sopenharmony_ci if n > 0 { 273962306a36Sopenharmony_ci // We can write the last element directly without cloning needlessly 274062306a36Sopenharmony_ci ptr::write(ptr, value); 274162306a36Sopenharmony_ci local_len.increment_len(1); 274262306a36Sopenharmony_ci } 274362306a36Sopenharmony_ci 274462306a36Sopenharmony_ci // len set by scope guard 274562306a36Sopenharmony_ci Ok(()) 274662306a36Sopenharmony_ci } 274762306a36Sopenharmony_ci } 274862306a36Sopenharmony_ci} 274962306a36Sopenharmony_ci 275062306a36Sopenharmony_ciimpl<T: PartialEq, A: Allocator> Vec<T, A> { 275162306a36Sopenharmony_ci /// Removes consecutive repeated elements in the vector according to the 275262306a36Sopenharmony_ci /// [`PartialEq`] trait implementation. 275362306a36Sopenharmony_ci /// 275462306a36Sopenharmony_ci /// If the vector is sorted, this removes all duplicates. 275562306a36Sopenharmony_ci /// 275662306a36Sopenharmony_ci /// # Examples 275762306a36Sopenharmony_ci /// 275862306a36Sopenharmony_ci /// ``` 275962306a36Sopenharmony_ci /// let mut vec = vec![1, 2, 2, 3, 2]; 276062306a36Sopenharmony_ci /// 276162306a36Sopenharmony_ci /// vec.dedup(); 276262306a36Sopenharmony_ci /// 276362306a36Sopenharmony_ci /// assert_eq!(vec, [1, 2, 3, 2]); 276462306a36Sopenharmony_ci /// ``` 276562306a36Sopenharmony_ci #[stable(feature = "rust1", since = "1.0.0")] 276662306a36Sopenharmony_ci #[inline] 276762306a36Sopenharmony_ci pub fn dedup(&mut self) { 276862306a36Sopenharmony_ci self.dedup_by(|a, b| a == b) 276962306a36Sopenharmony_ci } 277062306a36Sopenharmony_ci} 277162306a36Sopenharmony_ci 277262306a36Sopenharmony_ci//////////////////////////////////////////////////////////////////////////////// 277362306a36Sopenharmony_ci// Internal methods and functions 277462306a36Sopenharmony_ci//////////////////////////////////////////////////////////////////////////////// 277562306a36Sopenharmony_ci 277662306a36Sopenharmony_ci#[doc(hidden)] 277762306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 277862306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 277962306a36Sopenharmony_cipub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> { 278062306a36Sopenharmony_ci <T as SpecFromElem>::from_elem(elem, n, Global) 278162306a36Sopenharmony_ci} 278262306a36Sopenharmony_ci 278362306a36Sopenharmony_ci#[doc(hidden)] 278462306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 278562306a36Sopenharmony_ci#[unstable(feature = "allocator_api", issue = "32838")] 278662306a36Sopenharmony_cipub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> { 278762306a36Sopenharmony_ci <T as SpecFromElem>::from_elem(elem, n, alloc) 278862306a36Sopenharmony_ci} 278962306a36Sopenharmony_ci 279062306a36Sopenharmony_citrait ExtendFromWithinSpec { 279162306a36Sopenharmony_ci /// # Safety 279262306a36Sopenharmony_ci /// 279362306a36Sopenharmony_ci /// - `src` needs to be valid index 279462306a36Sopenharmony_ci /// - `self.capacity() - self.len()` must be `>= src.len()` 279562306a36Sopenharmony_ci unsafe fn spec_extend_from_within(&mut self, src: Range<usize>); 279662306a36Sopenharmony_ci} 279762306a36Sopenharmony_ci 279862306a36Sopenharmony_ciimpl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> { 279962306a36Sopenharmony_ci default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) { 280062306a36Sopenharmony_ci // SAFETY: 280162306a36Sopenharmony_ci // - len is increased only after initializing elements 280262306a36Sopenharmony_ci let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() }; 280362306a36Sopenharmony_ci 280462306a36Sopenharmony_ci // SAFETY: 280562306a36Sopenharmony_ci // - caller guarantees that src is a valid index 280662306a36Sopenharmony_ci let to_clone = unsafe { this.get_unchecked(src) }; 280762306a36Sopenharmony_ci 280862306a36Sopenharmony_ci iter::zip(to_clone, spare) 280962306a36Sopenharmony_ci .map(|(src, dst)| dst.write(src.clone())) 281062306a36Sopenharmony_ci // Note: 281162306a36Sopenharmony_ci // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len 281262306a36Sopenharmony_ci // - len is increased after each element to prevent leaks (see issue #82533) 281362306a36Sopenharmony_ci .for_each(|_| *len += 1); 281462306a36Sopenharmony_ci } 281562306a36Sopenharmony_ci} 281662306a36Sopenharmony_ci 281762306a36Sopenharmony_ciimpl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> { 281862306a36Sopenharmony_ci unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) { 281962306a36Sopenharmony_ci let count = src.len(); 282062306a36Sopenharmony_ci { 282162306a36Sopenharmony_ci let (init, spare) = self.split_at_spare_mut(); 282262306a36Sopenharmony_ci 282362306a36Sopenharmony_ci // SAFETY: 282462306a36Sopenharmony_ci // - caller guarantees that `src` is a valid index 282562306a36Sopenharmony_ci let source = unsafe { init.get_unchecked(src) }; 282662306a36Sopenharmony_ci 282762306a36Sopenharmony_ci // SAFETY: 282862306a36Sopenharmony_ci // - Both pointers are created from unique slice references (`&mut [_]`) 282962306a36Sopenharmony_ci // so they are valid and do not overlap. 283062306a36Sopenharmony_ci // - Elements are :Copy so it's OK to copy them, without doing 283162306a36Sopenharmony_ci // anything with the original values 283262306a36Sopenharmony_ci // - `count` is equal to the len of `source`, so source is valid for 283362306a36Sopenharmony_ci // `count` reads 283462306a36Sopenharmony_ci // - `.reserve(count)` guarantees that `spare.len() >= count` so spare 283562306a36Sopenharmony_ci // is valid for `count` writes 283662306a36Sopenharmony_ci unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) }; 283762306a36Sopenharmony_ci } 283862306a36Sopenharmony_ci 283962306a36Sopenharmony_ci // SAFETY: 284062306a36Sopenharmony_ci // - The elements were just initialized by `copy_nonoverlapping` 284162306a36Sopenharmony_ci self.len += count; 284262306a36Sopenharmony_ci } 284362306a36Sopenharmony_ci} 284462306a36Sopenharmony_ci 284562306a36Sopenharmony_ci//////////////////////////////////////////////////////////////////////////////// 284662306a36Sopenharmony_ci// Common trait implementations for Vec 284762306a36Sopenharmony_ci//////////////////////////////////////////////////////////////////////////////// 284862306a36Sopenharmony_ci 284962306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 285062306a36Sopenharmony_ciimpl<T, A: Allocator> ops::Deref for Vec<T, A> { 285162306a36Sopenharmony_ci type Target = [T]; 285262306a36Sopenharmony_ci 285362306a36Sopenharmony_ci #[inline] 285462306a36Sopenharmony_ci fn deref(&self) -> &[T] { 285562306a36Sopenharmony_ci unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 285662306a36Sopenharmony_ci } 285762306a36Sopenharmony_ci} 285862306a36Sopenharmony_ci 285962306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 286062306a36Sopenharmony_ciimpl<T, A: Allocator> ops::DerefMut for Vec<T, A> { 286162306a36Sopenharmony_ci #[inline] 286262306a36Sopenharmony_ci fn deref_mut(&mut self) -> &mut [T] { 286362306a36Sopenharmony_ci unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } 286462306a36Sopenharmony_ci } 286562306a36Sopenharmony_ci} 286662306a36Sopenharmony_ci 286762306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 286862306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 286962306a36Sopenharmony_ciimpl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> { 287062306a36Sopenharmony_ci #[cfg(not(test))] 287162306a36Sopenharmony_ci fn clone(&self) -> Self { 287262306a36Sopenharmony_ci let alloc = self.allocator().clone(); 287362306a36Sopenharmony_ci <[T]>::to_vec_in(&**self, alloc) 287462306a36Sopenharmony_ci } 287562306a36Sopenharmony_ci 287662306a36Sopenharmony_ci // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is 287762306a36Sopenharmony_ci // required for this method definition, is not available. Instead use the 287862306a36Sopenharmony_ci // `slice::to_vec` function which is only available with cfg(test) 287962306a36Sopenharmony_ci // NB see the slice::hack module in slice.rs for more information 288062306a36Sopenharmony_ci #[cfg(test)] 288162306a36Sopenharmony_ci fn clone(&self) -> Self { 288262306a36Sopenharmony_ci let alloc = self.allocator().clone(); 288362306a36Sopenharmony_ci crate::slice::to_vec(&**self, alloc) 288462306a36Sopenharmony_ci } 288562306a36Sopenharmony_ci 288662306a36Sopenharmony_ci fn clone_from(&mut self, other: &Self) { 288762306a36Sopenharmony_ci crate::slice::SpecCloneIntoVec::clone_into(other.as_slice(), self); 288862306a36Sopenharmony_ci } 288962306a36Sopenharmony_ci} 289062306a36Sopenharmony_ci 289162306a36Sopenharmony_ci/// The hash of a vector is the same as that of the corresponding slice, 289262306a36Sopenharmony_ci/// as required by the `core::borrow::Borrow` implementation. 289362306a36Sopenharmony_ci/// 289462306a36Sopenharmony_ci/// ``` 289562306a36Sopenharmony_ci/// use std::hash::BuildHasher; 289662306a36Sopenharmony_ci/// 289762306a36Sopenharmony_ci/// let b = std::collections::hash_map::RandomState::new(); 289862306a36Sopenharmony_ci/// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09]; 289962306a36Sopenharmony_ci/// let s: &[u8] = &[0xa8, 0x3c, 0x09]; 290062306a36Sopenharmony_ci/// assert_eq!(b.hash_one(v), b.hash_one(s)); 290162306a36Sopenharmony_ci/// ``` 290262306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 290362306a36Sopenharmony_ciimpl<T: Hash, A: Allocator> Hash for Vec<T, A> { 290462306a36Sopenharmony_ci #[inline] 290562306a36Sopenharmony_ci fn hash<H: Hasher>(&self, state: &mut H) { 290662306a36Sopenharmony_ci Hash::hash(&**self, state) 290762306a36Sopenharmony_ci } 290862306a36Sopenharmony_ci} 290962306a36Sopenharmony_ci 291062306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 291162306a36Sopenharmony_ci#[rustc_on_unimplemented( 291262306a36Sopenharmony_ci message = "vector indices are of type `usize` or ranges of `usize`", 291362306a36Sopenharmony_ci label = "vector indices are of type `usize` or ranges of `usize`" 291462306a36Sopenharmony_ci)] 291562306a36Sopenharmony_ciimpl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> { 291662306a36Sopenharmony_ci type Output = I::Output; 291762306a36Sopenharmony_ci 291862306a36Sopenharmony_ci #[inline] 291962306a36Sopenharmony_ci fn index(&self, index: I) -> &Self::Output { 292062306a36Sopenharmony_ci Index::index(&**self, index) 292162306a36Sopenharmony_ci } 292262306a36Sopenharmony_ci} 292362306a36Sopenharmony_ci 292462306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 292562306a36Sopenharmony_ci#[rustc_on_unimplemented( 292662306a36Sopenharmony_ci message = "vector indices are of type `usize` or ranges of `usize`", 292762306a36Sopenharmony_ci label = "vector indices are of type `usize` or ranges of `usize`" 292862306a36Sopenharmony_ci)] 292962306a36Sopenharmony_ciimpl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> { 293062306a36Sopenharmony_ci #[inline] 293162306a36Sopenharmony_ci fn index_mut(&mut self, index: I) -> &mut Self::Output { 293262306a36Sopenharmony_ci IndexMut::index_mut(&mut **self, index) 293362306a36Sopenharmony_ci } 293462306a36Sopenharmony_ci} 293562306a36Sopenharmony_ci 293662306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 293762306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 293862306a36Sopenharmony_ciimpl<T> FromIterator<T> for Vec<T> { 293962306a36Sopenharmony_ci #[inline] 294062306a36Sopenharmony_ci fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> { 294162306a36Sopenharmony_ci <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter()) 294262306a36Sopenharmony_ci } 294362306a36Sopenharmony_ci} 294462306a36Sopenharmony_ci 294562306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 294662306a36Sopenharmony_ciimpl<T, A: Allocator> IntoIterator for Vec<T, A> { 294762306a36Sopenharmony_ci type Item = T; 294862306a36Sopenharmony_ci type IntoIter = IntoIter<T, A>; 294962306a36Sopenharmony_ci 295062306a36Sopenharmony_ci /// Creates a consuming iterator, that is, one that moves each value out of 295162306a36Sopenharmony_ci /// the vector (from start to end). The vector cannot be used after calling 295262306a36Sopenharmony_ci /// this. 295362306a36Sopenharmony_ci /// 295462306a36Sopenharmony_ci /// # Examples 295562306a36Sopenharmony_ci /// 295662306a36Sopenharmony_ci /// ``` 295762306a36Sopenharmony_ci /// let v = vec!["a".to_string(), "b".to_string()]; 295862306a36Sopenharmony_ci /// let mut v_iter = v.into_iter(); 295962306a36Sopenharmony_ci /// 296062306a36Sopenharmony_ci /// let first_element: Option<String> = v_iter.next(); 296162306a36Sopenharmony_ci /// 296262306a36Sopenharmony_ci /// assert_eq!(first_element, Some("a".to_string())); 296362306a36Sopenharmony_ci /// assert_eq!(v_iter.next(), Some("b".to_string())); 296462306a36Sopenharmony_ci /// assert_eq!(v_iter.next(), None); 296562306a36Sopenharmony_ci /// ``` 296662306a36Sopenharmony_ci #[inline] 296762306a36Sopenharmony_ci fn into_iter(self) -> Self::IntoIter { 296862306a36Sopenharmony_ci unsafe { 296962306a36Sopenharmony_ci let mut me = ManuallyDrop::new(self); 297062306a36Sopenharmony_ci let alloc = ManuallyDrop::new(ptr::read(me.allocator())); 297162306a36Sopenharmony_ci let begin = me.as_mut_ptr(); 297262306a36Sopenharmony_ci let end = if T::IS_ZST { 297362306a36Sopenharmony_ci begin.wrapping_byte_add(me.len()) 297462306a36Sopenharmony_ci } else { 297562306a36Sopenharmony_ci begin.add(me.len()) as *const T 297662306a36Sopenharmony_ci }; 297762306a36Sopenharmony_ci let cap = me.buf.capacity(); 297862306a36Sopenharmony_ci IntoIter { 297962306a36Sopenharmony_ci buf: NonNull::new_unchecked(begin), 298062306a36Sopenharmony_ci phantom: PhantomData, 298162306a36Sopenharmony_ci cap, 298262306a36Sopenharmony_ci alloc, 298362306a36Sopenharmony_ci ptr: begin, 298462306a36Sopenharmony_ci end, 298562306a36Sopenharmony_ci } 298662306a36Sopenharmony_ci } 298762306a36Sopenharmony_ci } 298862306a36Sopenharmony_ci} 298962306a36Sopenharmony_ci 299062306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 299162306a36Sopenharmony_ciimpl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> { 299262306a36Sopenharmony_ci type Item = &'a T; 299362306a36Sopenharmony_ci type IntoIter = slice::Iter<'a, T>; 299462306a36Sopenharmony_ci 299562306a36Sopenharmony_ci fn into_iter(self) -> Self::IntoIter { 299662306a36Sopenharmony_ci self.iter() 299762306a36Sopenharmony_ci } 299862306a36Sopenharmony_ci} 299962306a36Sopenharmony_ci 300062306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 300162306a36Sopenharmony_ciimpl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> { 300262306a36Sopenharmony_ci type Item = &'a mut T; 300362306a36Sopenharmony_ci type IntoIter = slice::IterMut<'a, T>; 300462306a36Sopenharmony_ci 300562306a36Sopenharmony_ci fn into_iter(self) -> Self::IntoIter { 300662306a36Sopenharmony_ci self.iter_mut() 300762306a36Sopenharmony_ci } 300862306a36Sopenharmony_ci} 300962306a36Sopenharmony_ci 301062306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 301162306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 301262306a36Sopenharmony_ciimpl<T, A: Allocator> Extend<T> for Vec<T, A> { 301362306a36Sopenharmony_ci #[inline] 301462306a36Sopenharmony_ci fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { 301562306a36Sopenharmony_ci <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter()) 301662306a36Sopenharmony_ci } 301762306a36Sopenharmony_ci 301862306a36Sopenharmony_ci #[inline] 301962306a36Sopenharmony_ci fn extend_one(&mut self, item: T) { 302062306a36Sopenharmony_ci self.push(item); 302162306a36Sopenharmony_ci } 302262306a36Sopenharmony_ci 302362306a36Sopenharmony_ci #[inline] 302462306a36Sopenharmony_ci fn extend_reserve(&mut self, additional: usize) { 302562306a36Sopenharmony_ci self.reserve(additional); 302662306a36Sopenharmony_ci } 302762306a36Sopenharmony_ci} 302862306a36Sopenharmony_ci 302962306a36Sopenharmony_ciimpl<T, A: Allocator> Vec<T, A> { 303062306a36Sopenharmony_ci // leaf method to which various SpecFrom/SpecExtend implementations delegate when 303162306a36Sopenharmony_ci // they have no further optimizations to apply 303262306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 303362306a36Sopenharmony_ci fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) { 303462306a36Sopenharmony_ci // This is the case for a general iterator. 303562306a36Sopenharmony_ci // 303662306a36Sopenharmony_ci // This function should be the moral equivalent of: 303762306a36Sopenharmony_ci // 303862306a36Sopenharmony_ci // for item in iterator { 303962306a36Sopenharmony_ci // self.push(item); 304062306a36Sopenharmony_ci // } 304162306a36Sopenharmony_ci while let Some(element) = iterator.next() { 304262306a36Sopenharmony_ci let len = self.len(); 304362306a36Sopenharmony_ci if len == self.capacity() { 304462306a36Sopenharmony_ci let (lower, _) = iterator.size_hint(); 304562306a36Sopenharmony_ci self.reserve(lower.saturating_add(1)); 304662306a36Sopenharmony_ci } 304762306a36Sopenharmony_ci unsafe { 304862306a36Sopenharmony_ci ptr::write(self.as_mut_ptr().add(len), element); 304962306a36Sopenharmony_ci // Since next() executes user code which can panic we have to bump the length 305062306a36Sopenharmony_ci // after each step. 305162306a36Sopenharmony_ci // NB can't overflow since we would have had to alloc the address space 305262306a36Sopenharmony_ci self.set_len(len + 1); 305362306a36Sopenharmony_ci } 305462306a36Sopenharmony_ci } 305562306a36Sopenharmony_ci } 305662306a36Sopenharmony_ci 305762306a36Sopenharmony_ci // leaf method to which various SpecFrom/SpecExtend implementations delegate when 305862306a36Sopenharmony_ci // they have no further optimizations to apply 305962306a36Sopenharmony_ci fn try_extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) -> Result<(), TryReserveError> { 306062306a36Sopenharmony_ci // This is the case for a general iterator. 306162306a36Sopenharmony_ci // 306262306a36Sopenharmony_ci // This function should be the moral equivalent of: 306362306a36Sopenharmony_ci // 306462306a36Sopenharmony_ci // for item in iterator { 306562306a36Sopenharmony_ci // self.push(item); 306662306a36Sopenharmony_ci // } 306762306a36Sopenharmony_ci while let Some(element) = iterator.next() { 306862306a36Sopenharmony_ci let len = self.len(); 306962306a36Sopenharmony_ci if len == self.capacity() { 307062306a36Sopenharmony_ci let (lower, _) = iterator.size_hint(); 307162306a36Sopenharmony_ci self.try_reserve(lower.saturating_add(1))?; 307262306a36Sopenharmony_ci } 307362306a36Sopenharmony_ci unsafe { 307462306a36Sopenharmony_ci ptr::write(self.as_mut_ptr().add(len), element); 307562306a36Sopenharmony_ci // Since next() executes user code which can panic we have to bump the length 307662306a36Sopenharmony_ci // after each step. 307762306a36Sopenharmony_ci // NB can't overflow since we would have had to alloc the address space 307862306a36Sopenharmony_ci self.set_len(len + 1); 307962306a36Sopenharmony_ci } 308062306a36Sopenharmony_ci } 308162306a36Sopenharmony_ci 308262306a36Sopenharmony_ci Ok(()) 308362306a36Sopenharmony_ci } 308462306a36Sopenharmony_ci 308562306a36Sopenharmony_ci // specific extend for `TrustedLen` iterators, called both by the specializations 308662306a36Sopenharmony_ci // and internal places where resolving specialization makes compilation slower 308762306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 308862306a36Sopenharmony_ci fn extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) { 308962306a36Sopenharmony_ci let (low, high) = iterator.size_hint(); 309062306a36Sopenharmony_ci if let Some(additional) = high { 309162306a36Sopenharmony_ci debug_assert_eq!( 309262306a36Sopenharmony_ci low, 309362306a36Sopenharmony_ci additional, 309462306a36Sopenharmony_ci "TrustedLen iterator's size hint is not exact: {:?}", 309562306a36Sopenharmony_ci (low, high) 309662306a36Sopenharmony_ci ); 309762306a36Sopenharmony_ci self.reserve(additional); 309862306a36Sopenharmony_ci unsafe { 309962306a36Sopenharmony_ci let ptr = self.as_mut_ptr(); 310062306a36Sopenharmony_ci let mut local_len = SetLenOnDrop::new(&mut self.len); 310162306a36Sopenharmony_ci iterator.for_each(move |element| { 310262306a36Sopenharmony_ci ptr::write(ptr.add(local_len.current_len()), element); 310362306a36Sopenharmony_ci // Since the loop executes user code which can panic we have to update 310462306a36Sopenharmony_ci // the length every step to correctly drop what we've written. 310562306a36Sopenharmony_ci // NB can't overflow since we would have had to alloc the address space 310662306a36Sopenharmony_ci local_len.increment_len(1); 310762306a36Sopenharmony_ci }); 310862306a36Sopenharmony_ci } 310962306a36Sopenharmony_ci } else { 311062306a36Sopenharmony_ci // Per TrustedLen contract a `None` upper bound means that the iterator length 311162306a36Sopenharmony_ci // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway. 311262306a36Sopenharmony_ci // Since the other branch already panics eagerly (via `reserve()`) we do the same here. 311362306a36Sopenharmony_ci // This avoids additional codegen for a fallback code path which would eventually 311462306a36Sopenharmony_ci // panic anyway. 311562306a36Sopenharmony_ci panic!("capacity overflow"); 311662306a36Sopenharmony_ci } 311762306a36Sopenharmony_ci } 311862306a36Sopenharmony_ci 311962306a36Sopenharmony_ci // specific extend for `TrustedLen` iterators, called both by the specializations 312062306a36Sopenharmony_ci // and internal places where resolving specialization makes compilation slower 312162306a36Sopenharmony_ci fn try_extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) -> Result<(), TryReserveError> { 312262306a36Sopenharmony_ci let (low, high) = iterator.size_hint(); 312362306a36Sopenharmony_ci if let Some(additional) = high { 312462306a36Sopenharmony_ci debug_assert_eq!( 312562306a36Sopenharmony_ci low, 312662306a36Sopenharmony_ci additional, 312762306a36Sopenharmony_ci "TrustedLen iterator's size hint is not exact: {:?}", 312862306a36Sopenharmony_ci (low, high) 312962306a36Sopenharmony_ci ); 313062306a36Sopenharmony_ci self.try_reserve(additional)?; 313162306a36Sopenharmony_ci unsafe { 313262306a36Sopenharmony_ci let ptr = self.as_mut_ptr(); 313362306a36Sopenharmony_ci let mut local_len = SetLenOnDrop::new(&mut self.len); 313462306a36Sopenharmony_ci iterator.for_each(move |element| { 313562306a36Sopenharmony_ci ptr::write(ptr.add(local_len.current_len()), element); 313662306a36Sopenharmony_ci // Since the loop executes user code which can panic we have to update 313762306a36Sopenharmony_ci // the length every step to correctly drop what we've written. 313862306a36Sopenharmony_ci // NB can't overflow since we would have had to alloc the address space 313962306a36Sopenharmony_ci local_len.increment_len(1); 314062306a36Sopenharmony_ci }); 314162306a36Sopenharmony_ci } 314262306a36Sopenharmony_ci Ok(()) 314362306a36Sopenharmony_ci } else { 314462306a36Sopenharmony_ci Err(TryReserveErrorKind::CapacityOverflow.into()) 314562306a36Sopenharmony_ci } 314662306a36Sopenharmony_ci } 314762306a36Sopenharmony_ci 314862306a36Sopenharmony_ci /// Creates a splicing iterator that replaces the specified range in the vector 314962306a36Sopenharmony_ci /// with the given `replace_with` iterator and yields the removed items. 315062306a36Sopenharmony_ci /// `replace_with` does not need to be the same length as `range`. 315162306a36Sopenharmony_ci /// 315262306a36Sopenharmony_ci /// `range` is removed even if the iterator is not consumed until the end. 315362306a36Sopenharmony_ci /// 315462306a36Sopenharmony_ci /// It is unspecified how many elements are removed from the vector 315562306a36Sopenharmony_ci /// if the `Splice` value is leaked. 315662306a36Sopenharmony_ci /// 315762306a36Sopenharmony_ci /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped. 315862306a36Sopenharmony_ci /// 315962306a36Sopenharmony_ci /// This is optimal if: 316062306a36Sopenharmony_ci /// 316162306a36Sopenharmony_ci /// * The tail (elements in the vector after `range`) is empty, 316262306a36Sopenharmony_ci /// * or `replace_with` yields fewer or equal elements than `range`’s length 316362306a36Sopenharmony_ci /// * or the lower bound of its `size_hint()` is exact. 316462306a36Sopenharmony_ci /// 316562306a36Sopenharmony_ci /// Otherwise, a temporary vector is allocated and the tail is moved twice. 316662306a36Sopenharmony_ci /// 316762306a36Sopenharmony_ci /// # Panics 316862306a36Sopenharmony_ci /// 316962306a36Sopenharmony_ci /// Panics if the starting point is greater than the end point or if 317062306a36Sopenharmony_ci /// the end point is greater than the length of the vector. 317162306a36Sopenharmony_ci /// 317262306a36Sopenharmony_ci /// # Examples 317362306a36Sopenharmony_ci /// 317462306a36Sopenharmony_ci /// ``` 317562306a36Sopenharmony_ci /// let mut v = vec![1, 2, 3, 4]; 317662306a36Sopenharmony_ci /// let new = [7, 8, 9]; 317762306a36Sopenharmony_ci /// let u: Vec<_> = v.splice(1..3, new).collect(); 317862306a36Sopenharmony_ci /// assert_eq!(v, &[1, 7, 8, 9, 4]); 317962306a36Sopenharmony_ci /// assert_eq!(u, &[2, 3]); 318062306a36Sopenharmony_ci /// ``` 318162306a36Sopenharmony_ci #[cfg(not(no_global_oom_handling))] 318262306a36Sopenharmony_ci #[inline] 318362306a36Sopenharmony_ci #[stable(feature = "vec_splice", since = "1.21.0")] 318462306a36Sopenharmony_ci pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> 318562306a36Sopenharmony_ci where 318662306a36Sopenharmony_ci R: RangeBounds<usize>, 318762306a36Sopenharmony_ci I: IntoIterator<Item = T>, 318862306a36Sopenharmony_ci { 318962306a36Sopenharmony_ci Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } 319062306a36Sopenharmony_ci } 319162306a36Sopenharmony_ci 319262306a36Sopenharmony_ci /// Creates an iterator which uses a closure to determine if an element should be removed. 319362306a36Sopenharmony_ci /// 319462306a36Sopenharmony_ci /// If the closure returns true, then the element is removed and yielded. 319562306a36Sopenharmony_ci /// If the closure returns false, the element will remain in the vector and will not be yielded 319662306a36Sopenharmony_ci /// by the iterator. 319762306a36Sopenharmony_ci /// 319862306a36Sopenharmony_ci /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating 319962306a36Sopenharmony_ci /// or the iteration short-circuits, then the remaining elements will be retained. 320062306a36Sopenharmony_ci /// Use [`retain`] with a negated predicate if you do not need the returned iterator. 320162306a36Sopenharmony_ci /// 320262306a36Sopenharmony_ci /// [`retain`]: Vec::retain 320362306a36Sopenharmony_ci /// 320462306a36Sopenharmony_ci /// Using this method is equivalent to the following code: 320562306a36Sopenharmony_ci /// 320662306a36Sopenharmony_ci /// ``` 320762306a36Sopenharmony_ci /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 }; 320862306a36Sopenharmony_ci /// # let mut vec = vec![1, 2, 3, 4, 5, 6]; 320962306a36Sopenharmony_ci /// let mut i = 0; 321062306a36Sopenharmony_ci /// while i < vec.len() { 321162306a36Sopenharmony_ci /// if some_predicate(&mut vec[i]) { 321262306a36Sopenharmony_ci /// let val = vec.remove(i); 321362306a36Sopenharmony_ci /// // your code here 321462306a36Sopenharmony_ci /// } else { 321562306a36Sopenharmony_ci /// i += 1; 321662306a36Sopenharmony_ci /// } 321762306a36Sopenharmony_ci /// } 321862306a36Sopenharmony_ci /// 321962306a36Sopenharmony_ci /// # assert_eq!(vec, vec![1, 4, 5]); 322062306a36Sopenharmony_ci /// ``` 322162306a36Sopenharmony_ci /// 322262306a36Sopenharmony_ci /// But `extract_if` is easier to use. `extract_if` is also more efficient, 322362306a36Sopenharmony_ci /// because it can backshift the elements of the array in bulk. 322462306a36Sopenharmony_ci /// 322562306a36Sopenharmony_ci /// Note that `extract_if` also lets you mutate every element in the filter closure, 322662306a36Sopenharmony_ci /// regardless of whether you choose to keep or remove it. 322762306a36Sopenharmony_ci /// 322862306a36Sopenharmony_ci /// # Examples 322962306a36Sopenharmony_ci /// 323062306a36Sopenharmony_ci /// Splitting an array into evens and odds, reusing the original allocation: 323162306a36Sopenharmony_ci /// 323262306a36Sopenharmony_ci /// ``` 323362306a36Sopenharmony_ci /// #![feature(extract_if)] 323462306a36Sopenharmony_ci /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]; 323562306a36Sopenharmony_ci /// 323662306a36Sopenharmony_ci /// let evens = numbers.extract_if(|x| *x % 2 == 0).collect::<Vec<_>>(); 323762306a36Sopenharmony_ci /// let odds = numbers; 323862306a36Sopenharmony_ci /// 323962306a36Sopenharmony_ci /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); 324062306a36Sopenharmony_ci /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); 324162306a36Sopenharmony_ci /// ``` 324262306a36Sopenharmony_ci #[unstable(feature = "extract_if", reason = "recently added", issue = "43244")] 324362306a36Sopenharmony_ci pub fn extract_if<F>(&mut self, filter: F) -> ExtractIf<'_, T, F, A> 324462306a36Sopenharmony_ci where 324562306a36Sopenharmony_ci F: FnMut(&mut T) -> bool, 324662306a36Sopenharmony_ci { 324762306a36Sopenharmony_ci let old_len = self.len(); 324862306a36Sopenharmony_ci 324962306a36Sopenharmony_ci // Guard against us getting leaked (leak amplification) 325062306a36Sopenharmony_ci unsafe { 325162306a36Sopenharmony_ci self.set_len(0); 325262306a36Sopenharmony_ci } 325362306a36Sopenharmony_ci 325462306a36Sopenharmony_ci ExtractIf { vec: self, idx: 0, del: 0, old_len, pred: filter } 325562306a36Sopenharmony_ci } 325662306a36Sopenharmony_ci} 325762306a36Sopenharmony_ci 325862306a36Sopenharmony_ci/// Extend implementation that copies elements out of references before pushing them onto the Vec. 325962306a36Sopenharmony_ci/// 326062306a36Sopenharmony_ci/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to 326162306a36Sopenharmony_ci/// append the entire slice at once. 326262306a36Sopenharmony_ci/// 326362306a36Sopenharmony_ci/// [`copy_from_slice`]: slice::copy_from_slice 326462306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 326562306a36Sopenharmony_ci#[stable(feature = "extend_ref", since = "1.2.0")] 326662306a36Sopenharmony_ciimpl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec<T, A> { 326762306a36Sopenharmony_ci fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { 326862306a36Sopenharmony_ci self.spec_extend(iter.into_iter()) 326962306a36Sopenharmony_ci } 327062306a36Sopenharmony_ci 327162306a36Sopenharmony_ci #[inline] 327262306a36Sopenharmony_ci fn extend_one(&mut self, &item: &'a T) { 327362306a36Sopenharmony_ci self.push(item); 327462306a36Sopenharmony_ci } 327562306a36Sopenharmony_ci 327662306a36Sopenharmony_ci #[inline] 327762306a36Sopenharmony_ci fn extend_reserve(&mut self, additional: usize) { 327862306a36Sopenharmony_ci self.reserve(additional); 327962306a36Sopenharmony_ci } 328062306a36Sopenharmony_ci} 328162306a36Sopenharmony_ci 328262306a36Sopenharmony_ci/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison). 328362306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 328462306a36Sopenharmony_ciimpl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1> 328562306a36Sopenharmony_ciwhere 328662306a36Sopenharmony_ci T: PartialOrd, 328762306a36Sopenharmony_ci A1: Allocator, 328862306a36Sopenharmony_ci A2: Allocator, 328962306a36Sopenharmony_ci{ 329062306a36Sopenharmony_ci #[inline] 329162306a36Sopenharmony_ci fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering> { 329262306a36Sopenharmony_ci PartialOrd::partial_cmp(&**self, &**other) 329362306a36Sopenharmony_ci } 329462306a36Sopenharmony_ci} 329562306a36Sopenharmony_ci 329662306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 329762306a36Sopenharmony_ciimpl<T: Eq, A: Allocator> Eq for Vec<T, A> {} 329862306a36Sopenharmony_ci 329962306a36Sopenharmony_ci/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison). 330062306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 330162306a36Sopenharmony_ciimpl<T: Ord, A: Allocator> Ord for Vec<T, A> { 330262306a36Sopenharmony_ci #[inline] 330362306a36Sopenharmony_ci fn cmp(&self, other: &Self) -> Ordering { 330462306a36Sopenharmony_ci Ord::cmp(&**self, &**other) 330562306a36Sopenharmony_ci } 330662306a36Sopenharmony_ci} 330762306a36Sopenharmony_ci 330862306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 330962306a36Sopenharmony_ciunsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> { 331062306a36Sopenharmony_ci fn drop(&mut self) { 331162306a36Sopenharmony_ci unsafe { 331262306a36Sopenharmony_ci // use drop for [T] 331362306a36Sopenharmony_ci // use a raw slice to refer to the elements of the vector as weakest necessary type; 331462306a36Sopenharmony_ci // could avoid questions of validity in certain cases 331562306a36Sopenharmony_ci ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) 331662306a36Sopenharmony_ci } 331762306a36Sopenharmony_ci // RawVec handles deallocation 331862306a36Sopenharmony_ci } 331962306a36Sopenharmony_ci} 332062306a36Sopenharmony_ci 332162306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 332262306a36Sopenharmony_ciimpl<T> Default for Vec<T> { 332362306a36Sopenharmony_ci /// Creates an empty `Vec<T>`. 332462306a36Sopenharmony_ci /// 332562306a36Sopenharmony_ci /// The vector will not allocate until elements are pushed onto it. 332662306a36Sopenharmony_ci fn default() -> Vec<T> { 332762306a36Sopenharmony_ci Vec::new() 332862306a36Sopenharmony_ci } 332962306a36Sopenharmony_ci} 333062306a36Sopenharmony_ci 333162306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 333262306a36Sopenharmony_ciimpl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> { 333362306a36Sopenharmony_ci fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 333462306a36Sopenharmony_ci fmt::Debug::fmt(&**self, f) 333562306a36Sopenharmony_ci } 333662306a36Sopenharmony_ci} 333762306a36Sopenharmony_ci 333862306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 333962306a36Sopenharmony_ciimpl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> { 334062306a36Sopenharmony_ci fn as_ref(&self) -> &Vec<T, A> { 334162306a36Sopenharmony_ci self 334262306a36Sopenharmony_ci } 334362306a36Sopenharmony_ci} 334462306a36Sopenharmony_ci 334562306a36Sopenharmony_ci#[stable(feature = "vec_as_mut", since = "1.5.0")] 334662306a36Sopenharmony_ciimpl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> { 334762306a36Sopenharmony_ci fn as_mut(&mut self) -> &mut Vec<T, A> { 334862306a36Sopenharmony_ci self 334962306a36Sopenharmony_ci } 335062306a36Sopenharmony_ci} 335162306a36Sopenharmony_ci 335262306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 335362306a36Sopenharmony_ciimpl<T, A: Allocator> AsRef<[T]> for Vec<T, A> { 335462306a36Sopenharmony_ci fn as_ref(&self) -> &[T] { 335562306a36Sopenharmony_ci self 335662306a36Sopenharmony_ci } 335762306a36Sopenharmony_ci} 335862306a36Sopenharmony_ci 335962306a36Sopenharmony_ci#[stable(feature = "vec_as_mut", since = "1.5.0")] 336062306a36Sopenharmony_ciimpl<T, A: Allocator> AsMut<[T]> for Vec<T, A> { 336162306a36Sopenharmony_ci fn as_mut(&mut self) -> &mut [T] { 336262306a36Sopenharmony_ci self 336362306a36Sopenharmony_ci } 336462306a36Sopenharmony_ci} 336562306a36Sopenharmony_ci 336662306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 336762306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 336862306a36Sopenharmony_ciimpl<T: Clone> From<&[T]> for Vec<T> { 336962306a36Sopenharmony_ci /// Allocate a `Vec<T>` and fill it by cloning `s`'s items. 337062306a36Sopenharmony_ci /// 337162306a36Sopenharmony_ci /// # Examples 337262306a36Sopenharmony_ci /// 337362306a36Sopenharmony_ci /// ``` 337462306a36Sopenharmony_ci /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]); 337562306a36Sopenharmony_ci /// ``` 337662306a36Sopenharmony_ci #[cfg(not(test))] 337762306a36Sopenharmony_ci fn from(s: &[T]) -> Vec<T> { 337862306a36Sopenharmony_ci s.to_vec() 337962306a36Sopenharmony_ci } 338062306a36Sopenharmony_ci #[cfg(test)] 338162306a36Sopenharmony_ci fn from(s: &[T]) -> Vec<T> { 338262306a36Sopenharmony_ci crate::slice::to_vec(s, Global) 338362306a36Sopenharmony_ci } 338462306a36Sopenharmony_ci} 338562306a36Sopenharmony_ci 338662306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 338762306a36Sopenharmony_ci#[stable(feature = "vec_from_mut", since = "1.19.0")] 338862306a36Sopenharmony_ciimpl<T: Clone> From<&mut [T]> for Vec<T> { 338962306a36Sopenharmony_ci /// Allocate a `Vec<T>` and fill it by cloning `s`'s items. 339062306a36Sopenharmony_ci /// 339162306a36Sopenharmony_ci /// # Examples 339262306a36Sopenharmony_ci /// 339362306a36Sopenharmony_ci /// ``` 339462306a36Sopenharmony_ci /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]); 339562306a36Sopenharmony_ci /// ``` 339662306a36Sopenharmony_ci #[cfg(not(test))] 339762306a36Sopenharmony_ci fn from(s: &mut [T]) -> Vec<T> { 339862306a36Sopenharmony_ci s.to_vec() 339962306a36Sopenharmony_ci } 340062306a36Sopenharmony_ci #[cfg(test)] 340162306a36Sopenharmony_ci fn from(s: &mut [T]) -> Vec<T> { 340262306a36Sopenharmony_ci crate::slice::to_vec(s, Global) 340362306a36Sopenharmony_ci } 340462306a36Sopenharmony_ci} 340562306a36Sopenharmony_ci 340662306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 340762306a36Sopenharmony_ci#[stable(feature = "vec_from_array", since = "1.44.0")] 340862306a36Sopenharmony_ciimpl<T, const N: usize> From<[T; N]> for Vec<T> { 340962306a36Sopenharmony_ci /// Allocate a `Vec<T>` and move `s`'s items into it. 341062306a36Sopenharmony_ci /// 341162306a36Sopenharmony_ci /// # Examples 341262306a36Sopenharmony_ci /// 341362306a36Sopenharmony_ci /// ``` 341462306a36Sopenharmony_ci /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]); 341562306a36Sopenharmony_ci /// ``` 341662306a36Sopenharmony_ci #[cfg(not(test))] 341762306a36Sopenharmony_ci fn from(s: [T; N]) -> Vec<T> { 341862306a36Sopenharmony_ci <[T]>::into_vec(Box::new(s)) 341962306a36Sopenharmony_ci } 342062306a36Sopenharmony_ci 342162306a36Sopenharmony_ci #[cfg(test)] 342262306a36Sopenharmony_ci fn from(s: [T; N]) -> Vec<T> { 342362306a36Sopenharmony_ci crate::slice::into_vec(Box::new(s)) 342462306a36Sopenharmony_ci } 342562306a36Sopenharmony_ci} 342662306a36Sopenharmony_ci 342762306a36Sopenharmony_ci#[cfg(not(no_borrow))] 342862306a36Sopenharmony_ci#[stable(feature = "vec_from_cow_slice", since = "1.14.0")] 342962306a36Sopenharmony_ciimpl<'a, T> From<Cow<'a, [T]>> for Vec<T> 343062306a36Sopenharmony_ciwhere 343162306a36Sopenharmony_ci [T]: ToOwned<Owned = Vec<T>>, 343262306a36Sopenharmony_ci{ 343362306a36Sopenharmony_ci /// Convert a clone-on-write slice into a vector. 343462306a36Sopenharmony_ci /// 343562306a36Sopenharmony_ci /// If `s` already owns a `Vec<T>`, it will be returned directly. 343662306a36Sopenharmony_ci /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and 343762306a36Sopenharmony_ci /// filled by cloning `s`'s items into it. 343862306a36Sopenharmony_ci /// 343962306a36Sopenharmony_ci /// # Examples 344062306a36Sopenharmony_ci /// 344162306a36Sopenharmony_ci /// ``` 344262306a36Sopenharmony_ci /// # use std::borrow::Cow; 344362306a36Sopenharmony_ci /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]); 344462306a36Sopenharmony_ci /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]); 344562306a36Sopenharmony_ci /// assert_eq!(Vec::from(o), Vec::from(b)); 344662306a36Sopenharmony_ci /// ``` 344762306a36Sopenharmony_ci fn from(s: Cow<'a, [T]>) -> Vec<T> { 344862306a36Sopenharmony_ci s.into_owned() 344962306a36Sopenharmony_ci } 345062306a36Sopenharmony_ci} 345162306a36Sopenharmony_ci 345262306a36Sopenharmony_ci// note: test pulls in std, which causes errors here 345362306a36Sopenharmony_ci#[cfg(not(test))] 345462306a36Sopenharmony_ci#[stable(feature = "vec_from_box", since = "1.18.0")] 345562306a36Sopenharmony_ciimpl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> { 345662306a36Sopenharmony_ci /// Convert a boxed slice into a vector by transferring ownership of 345762306a36Sopenharmony_ci /// the existing heap allocation. 345862306a36Sopenharmony_ci /// 345962306a36Sopenharmony_ci /// # Examples 346062306a36Sopenharmony_ci /// 346162306a36Sopenharmony_ci /// ``` 346262306a36Sopenharmony_ci /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice(); 346362306a36Sopenharmony_ci /// assert_eq!(Vec::from(b), vec![1, 2, 3]); 346462306a36Sopenharmony_ci /// ``` 346562306a36Sopenharmony_ci fn from(s: Box<[T], A>) -> Self { 346662306a36Sopenharmony_ci s.into_vec() 346762306a36Sopenharmony_ci } 346862306a36Sopenharmony_ci} 346962306a36Sopenharmony_ci 347062306a36Sopenharmony_ci// note: test pulls in std, which causes errors here 347162306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 347262306a36Sopenharmony_ci#[cfg(not(test))] 347362306a36Sopenharmony_ci#[stable(feature = "box_from_vec", since = "1.20.0")] 347462306a36Sopenharmony_ciimpl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> { 347562306a36Sopenharmony_ci /// Convert a vector into a boxed slice. 347662306a36Sopenharmony_ci /// 347762306a36Sopenharmony_ci /// If `v` has excess capacity, its items will be moved into a 347862306a36Sopenharmony_ci /// newly-allocated buffer with exactly the right capacity. 347962306a36Sopenharmony_ci /// 348062306a36Sopenharmony_ci /// # Examples 348162306a36Sopenharmony_ci /// 348262306a36Sopenharmony_ci /// ``` 348362306a36Sopenharmony_ci /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); 348462306a36Sopenharmony_ci /// ``` 348562306a36Sopenharmony_ci /// 348662306a36Sopenharmony_ci /// Any excess capacity is removed: 348762306a36Sopenharmony_ci /// ``` 348862306a36Sopenharmony_ci /// let mut vec = Vec::with_capacity(10); 348962306a36Sopenharmony_ci /// vec.extend([1, 2, 3]); 349062306a36Sopenharmony_ci /// 349162306a36Sopenharmony_ci /// assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice()); 349262306a36Sopenharmony_ci /// ``` 349362306a36Sopenharmony_ci fn from(v: Vec<T, A>) -> Self { 349462306a36Sopenharmony_ci v.into_boxed_slice() 349562306a36Sopenharmony_ci } 349662306a36Sopenharmony_ci} 349762306a36Sopenharmony_ci 349862306a36Sopenharmony_ci#[cfg(not(no_global_oom_handling))] 349962306a36Sopenharmony_ci#[stable(feature = "rust1", since = "1.0.0")] 350062306a36Sopenharmony_ciimpl From<&str> for Vec<u8> { 350162306a36Sopenharmony_ci /// Allocate a `Vec<u8>` and fill it with a UTF-8 string. 350262306a36Sopenharmony_ci /// 350362306a36Sopenharmony_ci /// # Examples 350462306a36Sopenharmony_ci /// 350562306a36Sopenharmony_ci /// ``` 350662306a36Sopenharmony_ci /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']); 350762306a36Sopenharmony_ci /// ``` 350862306a36Sopenharmony_ci fn from(s: &str) -> Vec<u8> { 350962306a36Sopenharmony_ci From::from(s.as_bytes()) 351062306a36Sopenharmony_ci } 351162306a36Sopenharmony_ci} 351262306a36Sopenharmony_ci 351362306a36Sopenharmony_ci#[stable(feature = "array_try_from_vec", since = "1.48.0")] 351462306a36Sopenharmony_ciimpl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] { 351562306a36Sopenharmony_ci type Error = Vec<T, A>; 351662306a36Sopenharmony_ci 351762306a36Sopenharmony_ci /// Gets the entire contents of the `Vec<T>` as an array, 351862306a36Sopenharmony_ci /// if its size exactly matches that of the requested array. 351962306a36Sopenharmony_ci /// 352062306a36Sopenharmony_ci /// # Examples 352162306a36Sopenharmony_ci /// 352262306a36Sopenharmony_ci /// ``` 352362306a36Sopenharmony_ci /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3])); 352462306a36Sopenharmony_ci /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([])); 352562306a36Sopenharmony_ci /// ``` 352662306a36Sopenharmony_ci /// 352762306a36Sopenharmony_ci /// If the length doesn't match, the input comes back in `Err`: 352862306a36Sopenharmony_ci /// ``` 352962306a36Sopenharmony_ci /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into(); 353062306a36Sopenharmony_ci /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); 353162306a36Sopenharmony_ci /// ``` 353262306a36Sopenharmony_ci /// 353362306a36Sopenharmony_ci /// If you're fine with just getting a prefix of the `Vec<T>`, 353462306a36Sopenharmony_ci /// you can call [`.truncate(N)`](Vec::truncate) first. 353562306a36Sopenharmony_ci /// ``` 353662306a36Sopenharmony_ci /// let mut v = String::from("hello world").into_bytes(); 353762306a36Sopenharmony_ci /// v.sort(); 353862306a36Sopenharmony_ci /// v.truncate(2); 353962306a36Sopenharmony_ci /// let [a, b]: [_; 2] = v.try_into().unwrap(); 354062306a36Sopenharmony_ci /// assert_eq!(a, b' '); 354162306a36Sopenharmony_ci /// assert_eq!(b, b'd'); 354262306a36Sopenharmony_ci /// ``` 354362306a36Sopenharmony_ci fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> { 354462306a36Sopenharmony_ci if vec.len() != N { 354562306a36Sopenharmony_ci return Err(vec); 354662306a36Sopenharmony_ci } 354762306a36Sopenharmony_ci 354862306a36Sopenharmony_ci // SAFETY: `.set_len(0)` is always sound. 354962306a36Sopenharmony_ci unsafe { vec.set_len(0) }; 355062306a36Sopenharmony_ci 355162306a36Sopenharmony_ci // SAFETY: A `Vec`'s pointer is always aligned properly, and 355262306a36Sopenharmony_ci // the alignment the array needs is the same as the items. 355362306a36Sopenharmony_ci // We checked earlier that we have sufficient items. 355462306a36Sopenharmony_ci // The items will not double-drop as the `set_len` 355562306a36Sopenharmony_ci // tells the `Vec` not to also drop them. 355662306a36Sopenharmony_ci let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) }; 355762306a36Sopenharmony_ci Ok(array) 355862306a36Sopenharmony_ci } 355962306a36Sopenharmony_ci} 3560