Skip to content

Commit

Permalink
Rollup merge of rust-lang#103280 - finnbear:impl_string_leak_2, r=jos…
Browse files Browse the repository at this point in the history
…htriplett

(rust-lang#102929) Implement `String::leak` (attempt 2)

Implementation of `String::leak` (rust-lang#102929)

ACP: rust-lang/libs-team#109

Supersedes rust-lang#102941 (see previous reviews there)

`@rustbot` label +T-libs-api -T-libs
  • Loading branch information
Dylan-DPC authored Oct 22, 2022
2 parents 6529ccc + 4f44d62 commit 9e8a564
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ use core::str::Utf8Chunks;
use crate::borrow::{Cow, ToOwned};
use crate::boxed::Box;
use crate::collections::TryReserveError;
use crate::str::{self, Chars, Utf8Error};
use crate::str::{self, from_utf8_unchecked_mut, Chars, Utf8Error};
#[cfg(not(no_global_oom_handling))]
use crate::str::{from_boxed_utf8_unchecked, FromStr};
use crate::vec::Vec;
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`.
///
/// 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

0 comments on commit 9e8a564

Please sign in to comment.