Skip to content

Commit 248a9f4

Browse files
committed
impl String:leak.
1 parent cde693c commit 248a9f4

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

library/alloc/src/string.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ use crate::boxed::Box;
6969
use crate::collections::TryReserveError;
7070
use crate::str::{self, Chars, Utf8Error};
7171
#[cfg(not(no_global_oom_handling))]
72-
use crate::str::{from_boxed_utf8_unchecked, FromStr};
72+
use crate::str::{from_boxed_utf8_unchecked, from_utf8_unchecked_mut, FromStr};
7373
use crate::vec::Vec;
7474

7575
/// A UTF-8–encoded, growable string.
@@ -1849,6 +1849,30 @@ 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 function 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+
/// # Examples
1861+
///
1862+
/// Simple usage:
1863+
///
1864+
/// ```
1865+
/// let x = String::from("bucket");
1866+
/// let static_ref: &'static mut str = x.leak();
1867+
/// assert_eq!(static_ref, "bucket");
1868+
/// ```
1869+
#[cfg(not(no_global_oom_handling))]
1870+
#[unstable(feature = "string_leak", issue = "102929")]
1871+
#[inline]
1872+
pub fn leak<'a>(self) -> &'a mut str {
1873+
let slice = self.into_bytes().leak();
1874+
unsafe { from_utf8_unchecked_mut(slice) }
1875+
}
18521876
}
18531877

18541878
impl FromUtf8Error {

0 commit comments

Comments
 (0)