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