Skip to content

Commit 83407b8

Browse files
committed
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.
1 parent a8d78fe commit 83407b8

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

library/std/src/ffi/os_str.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -610,7 +610,30 @@ impl<T: ?Sized + AsRef<OsStr>> From<&T> for OsString {
610610
/// Copies any value implementing <code>[AsRef]&lt;[OsStr]&gt;</code>
611611
/// into a newly allocated [`OsString`].
612612
fn from(s: &T) -> OsString {
613-
s.as_ref().to_os_string()
613+
trait SpecToOsString {
614+
fn spec_to_os_string(&self) -> OsString;
615+
}
616+
617+
impl<T: AsRef<OsStr>> SpecToOsString for T {
618+
#[inline]
619+
default fn spec_to_os_string(&self) -> OsString {
620+
self.as_ref().to_os_string()
621+
}
622+
}
623+
624+
// Preserve the known-UTF-8 property for strings.
625+
macro spec_str($T:ty) {
626+
impl SpecToOsString for $T {
627+
#[inline]
628+
fn spec_to_os_string(&self) -> OsString {
629+
OsString::from(String::from(self))
630+
}
631+
}
632+
}
633+
spec_str!(str);
634+
spec_str!(String);
635+
636+
s.spec_to_os_string()
614637
}
615638
}
616639

0 commit comments

Comments
 (0)