Skip to content

Commit 72ad968

Browse files
authored
Rollup merge of #103280 - finnbear:impl_string_leak_2, r=joshtriplett
(#102929) Implement `String::leak` (attempt 2) Implementation of `String::leak` (#102929) ACP: rust-lang/libs-team#109 Supersedes #102941 (see previous reviews there) ```@rustbot``` label +T-libs-api -T-libs
2 parents 81f14f6 + 3c58e65 commit 72ad968

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

alloc/src/string.rs

+30-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ use core::str::Utf8Chunks;
6767
use crate::borrow::{Cow, ToOwned};
6868
use crate::boxed::Box;
6969
use crate::collections::TryReserveError;
70-
use crate::str::{self, Chars, Utf8Error};
70+
use crate::str::{self, from_utf8_unchecked_mut, Chars, Utf8Error};
7171
#[cfg(not(no_global_oom_handling))]
7272
use crate::str::{from_boxed_utf8_unchecked, FromStr};
7373
use crate::vec::Vec;
@@ -1849,6 +1849,35 @@ impl String {
18491849
let slice = self.vec.into_boxed_slice();
18501850
unsafe { from_boxed_utf8_unchecked(slice) }
18511851
}
1852+
1853+
/// Consumes and leaks the `String`, returning a mutable reference to the contents,
1854+
/// `&'a mut str`.
1855+
///
1856+
/// This is mainly useful for data that lives for the remainder of
1857+
/// the program's life. Dropping the returned reference will cause a memory
1858+
/// leak.
1859+
///
1860+
/// It does not reallocate or shrink the `String`,
1861+
/// so the leaked allocation may include unused capacity that is not part
1862+
/// of the returned slice.
1863+
///
1864+
/// # Examples
1865+
///
1866+
/// Simple usage:
1867+
///
1868+
/// ```
1869+
/// #![feature(string_leak)]
1870+
///
1871+
/// let x = String::from("bucket");
1872+
/// let static_ref: &'static mut str = x.leak();
1873+
/// assert_eq!(static_ref, "bucket");
1874+
/// ```
1875+
#[unstable(feature = "string_leak", issue = "102929")]
1876+
#[inline]
1877+
pub fn leak(self) -> &'static mut str {
1878+
let slice = self.vec.leak();
1879+
unsafe { from_utf8_unchecked_mut(slice) }
1880+
}
18521881
}
18531882

18541883
impl FromUtf8Error {

0 commit comments

Comments
 (0)