summary refs log tree commit diff
path: root/library/alloc/src/string.rs
diff options
context:
space:
mode:
authorFinn Bear <finnbearlabs@gmail.com>2022-10-19 19:07:45 -0700
committerFinn Bear <finnbearlabs@gmail.com>2022-10-19 19:07:45 -0700
commitf81cd87eeae2b02ebfcf309764cd9e648040b988 (patch)
treefbbee311ca09224d07017e1d2113195c5aa22e45 /library/alloc/src/string.rs
parent57781b24c54f9548722927ba88c343ff28da94ce (diff)
downloadrust-f81cd87eeae2b02ebfcf309764cd9e648040b988.tar.gz
rust-f81cd87eeae2b02ebfcf309764cd9e648040b988.zip
Copy of #102941.
Diffstat (limited to 'library/alloc/src/string.rs')
-rw-r--r--library/alloc/src/string.rs31
1 files changed, 30 insertions, 1 deletions
diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs
index 983376a282b..9bda7f5dc37 100644
--- a/library/alloc/src/string.rs
+++ b/library/alloc/src/string.rs
@@ -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;
@@ -2691,6 +2691,35 @@ impl From<String> for Box<str> {
     fn from(s: String) -> Box<str> {
         s.into_boxed_str()
     }
+
+    /// 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) }
+    }
 }
 
 #[cfg(not(no_global_oom_handling))]