diff options
| author | schvv31n <tim.kurdov@gmail.com> | 2024-06-04 11:53:59 +0100 |
|---|---|---|
| committer | schvv31n <tim.kurdov@gmail.com> | 2024-06-04 11:53:59 +0100 |
| commit | fd5777c4c5c8fbc54d33d15afb29479180c532be (patch) | |
| tree | 7ca803a02c33582b471e37d9acbe280e2d2df405 /library/std/src/ffi | |
| parent | eb5e2449c5a5215927834d67914ce41cccd3f3c9 (diff) | |
| download | rust-fd5777c4c5c8fbc54d33d15afb29479180c532be.tar.gz rust-fd5777c4c5c8fbc54d33d15afb29479180c532be.zip | |
impl OsString::leak & PathBuf::leak
Diffstat (limited to 'library/std/src/ffi')
| -rw-r--r-- | library/std/src/ffi/os_str.rs | 19 | ||||
| -rw-r--r-- | library/std/src/ffi/os_str/tests.rs | 7 |
2 files changed, 26 insertions, 0 deletions
diff --git a/library/std/src/ffi/os_str.rs b/library/std/src/ffi/os_str.rs index 9dd3d7d3fa1..f6b9de26c1c 100644 --- a/library/std/src/ffi/os_str.rs +++ b/library/std/src/ffi/os_str.rs @@ -533,6 +533,25 @@ impl OsString { unsafe { Box::from_raw(rw) } } + /// Consumes and leaks the `OsString`, returning a mutable reference to the contents, + /// `&'a mut OsStr`. + /// + /// The caller has free choice over the returned lifetime, including 'static. + /// Indeed, this function is ideally used for data that lives for the remainder of + /// the program’s life, as dropping the returned reference will cause a memory leak. + /// + /// It does not reallocate or shrink the `OsString`, so the leaked allocation may include + /// unused capacity that is not part of the returned slice. If you want to discard excess + /// capacity, call [`into_boxed_os_str`], and then [`Box::leak`] instead. + /// However, keep in mind that trimming the capacity may result in a reallocation and copy. + /// + /// [`into_boxed_os_str`]: Self::into_boxed_os_str + #[unstable(feature = "os_string_pathbuf_leak", issue = "125965")] + #[inline] + pub fn leak<'a>(self) -> &'a mut OsStr { + OsStr::from_inner_mut(self.inner.leak()) + } + /// Part of a hack to make PathBuf::push/pop more efficient. #[inline] pub(crate) fn as_mut_vec_for_path_buf(&mut self) -> &mut Vec<u8> { diff --git a/library/std/src/ffi/os_str/tests.rs b/library/std/src/ffi/os_str/tests.rs index b020e05eaab..2379f0ba489 100644 --- a/library/std/src/ffi/os_str/tests.rs +++ b/library/std/src/ffi/os_str/tests.rs @@ -24,6 +24,13 @@ fn test_os_string_clear() { } #[test] +fn test_os_string_leak() { + let os_string = OsString::from("have a cake"); + let leaked = os_string.leak(); + assert_eq!(leaked.as_encoded_bytes(), b"have a cake"); +} + +#[test] fn test_os_string_capacity() { let os_string = OsString::with_capacity(0); assert_eq!(0, os_string.capacity()); |
