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