From 10fc01295e7cb2569ccd50aa79a599275fba0b9e Mon Sep 17 00:00:00 2001 From: Thalia Archibald Date: Thu, 16 Oct 2025 20:00:39 -0600 Subject: [PATCH] motor: Use UTF-8 guarantee for OS strings --- library/std/src/os/motor/ffi.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/library/std/src/os/motor/ffi.rs b/library/std/src/os/motor/ffi.rs index 509fe641bb353..5b342db7b6171 100644 --- a/library/std/src/os/motor/ffi.rs +++ b/library/std/src/os/motor/ffi.rs @@ -9,14 +9,18 @@ use crate::sealed::Sealed; /// This trait is sealed: it cannot be implemented outside the standard library. /// This is so that future additional methods are not breaking changes. pub trait OsStringExt: Sealed { - /// Motor OS strings are utf-8, and thus just strings. - fn as_str(&self) -> &str; + /// Yields the underlying UTF-8 string of this [`OsString`]. + fn into_string(self) -> String; } impl OsStringExt for OsString { #[inline] - fn as_str(&self) -> &str { - self.to_str().unwrap() + fn into_string(self) -> String { + // SAFETY: The platform encoding of Motor OS is UTF-8. As + // from_encoded_bytes_unchecked requires that the input bytes originate + // from OsStr::as_encoded_bytes and/or valid UTF-8, no OsString can + // contain invalid UTF-8. + unsafe { String::from_utf8_unchecked(self.into_encoded_bytes()) } } } @@ -25,13 +29,14 @@ impl OsStringExt for OsString { /// This trait is sealed: it cannot be implemented outside the standard library. /// This is so that future additional methods are not breaking changes. pub trait OsStrExt: Sealed { - /// Motor OS strings are utf-8, and thus just strings. + /// Gets the underlying UTF-8 string view of the [`OsStr`] slice. fn as_str(&self) -> &str; } impl OsStrExt for OsStr { #[inline] fn as_str(&self) -> &str { - self.to_str().unwrap() + // SAFETY: As above. + unsafe { str::from_utf8_unchecked(self.as_encoded_bytes()) } } }