diff options
| author | Thalia Archibald <thalia@archibald.dev> | 2025-02-28 13:31:15 -0800 |
|---|---|---|
| committer | Thalia Archibald <thalia@archibald.dev> | 2025-02-28 13:50:31 -0800 |
| commit | 83407b828bcf5c883b2ab50b958edbcba0738f6a (patch) | |
| tree | cc88198d063fc6fe2d8f549f10f560281c9099e1 /library/std/src/ffi/os_str.rs | |
| parent | a8d78fec52aec04254ec602851c4fd7c8469c592 (diff) | |
| download | rust-83407b828bcf5c883b2ab50b958edbcba0738f6a.tar.gz rust-83407b828bcf5c883b2ab50b958edbcba0738f6a.zip | |
Specialize constructing OsString from strings
The WTF-8 version of `OsString` tracks whether it is known to be valid UTF-8 with its `is_known_utf8` field. Specialize `From<AsRef<OsStr>>` so this can be set for UTF-8 string types.
Diffstat (limited to 'library/std/src/ffi/os_str.rs')
| -rw-r--r-- | library/std/src/ffi/os_str.rs | 25 |
1 files changed, 24 insertions, 1 deletions
diff --git a/library/std/src/ffi/os_str.rs b/library/std/src/ffi/os_str.rs index c0e659db307..aa25ff5293c 100644 --- a/library/std/src/ffi/os_str.rs +++ b/library/std/src/ffi/os_str.rs @@ -610,7 +610,30 @@ impl<T: ?Sized + AsRef<OsStr>> From<&T> for OsString { /// Copies any value implementing <code>[AsRef]<[OsStr]></code> /// into a newly allocated [`OsString`]. fn from(s: &T) -> OsString { - s.as_ref().to_os_string() + trait SpecToOsString { + fn spec_to_os_string(&self) -> OsString; + } + + impl<T: AsRef<OsStr>> SpecToOsString for T { + #[inline] + default fn spec_to_os_string(&self) -> OsString { + self.as_ref().to_os_string() + } + } + + // Preserve the known-UTF-8 property for strings. + macro spec_str($T:ty) { + impl SpecToOsString for $T { + #[inline] + fn spec_to_os_string(&self) -> OsString { + OsString::from(String::from(self)) + } + } + } + spec_str!(str); + spec_str!(String); + + s.spec_to_os_string() } } |
