Skip to content

Commit 265fef4

Browse files
committed
Auto merge of rust-lang#89337 - mbrubeck:vec-leak, r=m-ou-se
Avoid allocations and copying in Vec::leak The [`Vec::leak`] method (rust-lang#62195) is currently implemented by calling `Vec::into_boxed_slice` and `Box::leak`. This shrinks the vector before leaking it, which potentially causes a reallocation and copies the vector's contents. By avoiding the conversion to `Box`, we can instead leak the vector without any expensive operations, just by returning a slice reference and forgetting the `Vec`. Users who *want* to shrink the vector first can still do so by calling `shrink_to_fit` explicitly. **Note:** This could break code that uses `Box::from_raw` to “un-leak” the slice returned by `Vec::leak`. However, the `Vec::leak` docs explicitly forbid this, so such code is already incorrect. [`Vec::leak`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.leak
2 parents af9b508 + df15b28 commit 265fef4

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

library/alloc/src/vec/mod.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -1973,8 +1973,9 @@ impl<T, A: Allocator> Vec<T, A> {
19731973
/// `'a`. If the type has only static references, or none at all, then this
19741974
/// may be chosen to be `'static`.
19751975
///
1976-
/// This function is similar to the [`leak`][Box::leak] function on [`Box`]
1977-
/// except that there is no way to recover the leaked memory.
1976+
/// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
1977+
/// so the leaked allocation may include unused capacity that is not part
1978+
/// of the returned slice.
19781979
///
19791980
/// This function is mainly useful for data that lives for the remainder of
19801981
/// the program's life. Dropping the returned reference will cause a memory
@@ -1997,7 +1998,8 @@ impl<T, A: Allocator> Vec<T, A> {
19971998
where
19981999
A: 'a,
19992000
{
2000-
Box::leak(self.into_boxed_slice())
2001+
let mut me = ManuallyDrop::new(self);
2002+
unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
20012003
}
20022004

20032005
/// Returns the remaining spare capacity of the vector as a slice of

0 commit comments

Comments
 (0)