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