Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(#102929) Implement String:leak #102941

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ use crate::boxed::Box;
use crate::collections::TryReserveError;
use crate::str::{self, Chars, Utf8Error};
#[cfg(not(no_global_oom_handling))]
use crate::str::{from_boxed_utf8_unchecked, FromStr};
use crate::str::{from_boxed_utf8_unchecked, from_utf8_unchecked_mut, FromStr};
use crate::vec::Vec;

/// A UTF-8–encoded, growable string.
Expand Down Expand Up @@ -1849,6 +1849,35 @@ impl String {
let slice = self.vec.into_boxed_slice();
unsafe { from_boxed_utf8_unchecked(slice) }
}

/// Consumes and leaks the `String`, returning a mutable reference to the contents,
/// `&'a mut str`.
///
finnbear marked this conversation as resolved.
Show resolved Hide resolved
/// This is mainly useful for data that lives for the remainder of
/// the program's life. Dropping the returned reference will cause a memory
/// leak.
///
/// It does not reallocate or shrink the `String`,
/// so the leaked allocation may include unused capacity that is not part
/// of the returned slice.
///
/// # Examples
///
/// Simple usage:
///
/// ```
/// #![feature(string_leak)]
///
/// let x = String::from("bucket");
/// let static_ref: &'static mut str = x.leak();
/// assert_eq!(static_ref, "bucket");
/// ```
#[unstable(feature = "string_leak", issue = "102929")]
#[inline]
pub fn leak(self) -> &'static mut str {
let slice = self.vec.leak();
unsafe { from_utf8_unchecked_mut(slice) }
}
}

impl FromUtf8Error {
Expand Down