Skip to content

Commit 3aad190

Browse files
committed
add Utf8PathBuf::leak
1 parent fbe5d79 commit 3aad190

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

build.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ fn main() {
1919
println!("cargo:rustc-check-cfg=cfg(shrink_to)");
2020
println!("cargo:rustc-check-cfg=cfg(try_reserve_2)");
2121
println!("cargo:rustc-check-cfg=cfg(os_str_bytes)");
22+
println!("cargo:rustc-check-cfg=cfg(os_string_pathbuf_leak)");
2223
println!("cargo:rustc-check-cfg=cfg(absolute_path)");
2324

2425
let compiler = match rustc_version() {
@@ -61,6 +62,11 @@ fn main() {
6162
{
6263
println!("cargo:rustc-cfg=absolute_path");
6364
}
65+
// os_string_pathbuf_leak was added in 1.89.
66+
if (compiler.minor >= 89 && compiler.channel == ReleaseChannel::Stable) || compiler.minor >= 90
67+
{
68+
println!("cargo:rustc-cfg=os_string_pathbuf_leak");
69+
}
6470

6571
// Catch situations where the actual features aren't enabled. Currently, they're only shown with
6672
// `-vv` output, but maybe that will be noticed.

src/lib.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,27 @@ impl Utf8PathBuf {
227227
unsafe { Utf8Path::assume_utf8(&self.0) }
228228
}
229229

230+
/// Consumes and leaks the `Utf8PathBuf`, returning a mutable reference to the contents,
231+
/// `&'a mut Utf8Path`.
232+
///
233+
/// The caller has free choice over the returned lifetime, including 'static.
234+
/// Indeed, this function is ideally used for data that lives for the remainder of
235+
/// the program’s life, as dropping the returned reference will cause a memory leak.
236+
///
237+
/// It does not reallocate or shrink the `Utf8PathBuf`, so the leaked allocation may include
238+
/// unused capacity that is not part of the returned slice. If you want to discard excess
239+
/// capacity, call [`into_boxed_path`], and then [`Box::leak`] instead.
240+
/// However, keep in mind that trimming the capacity may result in a reallocation and copy.
241+
///
242+
/// [`into_boxed_path`]: Self::into_boxed_path
243+
#[cfg(os_string_pathbuf_leak)]
244+
#[allow(clippy::incompatible_msrv)]
245+
#[inline]
246+
pub fn leak<'a>(self) -> &'a mut Utf8Path {
247+
// SAFETY: every Utf8PathBuf constructor ensures that self is valid UTF-8
248+
unsafe { Utf8Path::assume_utf8_mut(self.0.leak()) }
249+
}
250+
230251
/// Extends `self` with `path`.
231252
///
232253
/// If `path` is absolute, it replaces the current path.

0 commit comments

Comments
 (0)