about summary refs log tree commit diff
path: root/library/std/src
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2023-06-14 18:10:27 +0200
committerGitHub <noreply@github.com>2023-06-14 18:10:27 +0200
commit4efdb5c0015561bdaa6c00a79090a2080ef2c964 (patch)
tree8002841bf08d692f21735bfdfb0dac357e0d5da3 /library/std/src
parent7b0eac438ace0ba305b4633328b00474fbbf5120 (diff)
parente3a1a11ed2a1b081b229f1d873114aaf7f5f5137 (diff)
downloadrust-4efdb5c0015561bdaa6c00a79090a2080ef2c964.tar.gz
rust-4efdb5c0015561bdaa6c00a79090a2080ef2c964.zip
Rollup merge of #98202 - aticu:impl_tryfrom_osstr_for_str, r=Amanieu
Implement `TryFrom<&OsStr>` for `&str`

Recently when trying to work with `&OsStr` I was surprised to find this `impl` missing.

Since the `to_str` method already existed the actual implementation is fairly non-controversial, except for maybe the choice of the error type. I chose an opaque error here instead of something like `std::str::Utf8Error`, since that would already make a number of assumption about the underlying implementation of `OsStr`.

As this is a trait implementation, it is insta-stable, if I'm not mistaken?
Either way this will need an FCP.
I chose "1.64.0" as the version, since this is unlikely to land before the beta cut-off.

`@rustbot` modify labels: +T-libs-api

API Change Proposal: rust-lang/rust#99031 (accepted)
Diffstat (limited to 'library/std/src')
-rw-r--r--library/std/src/ffi/os_str.rs20
-rw-r--r--library/std/src/sys/unix/os_str.rs4
-rw-r--r--library/std/src/sys/windows/os_str.rs2
-rw-r--r--library/std/src/sys_common/wtf8.rs9
-rw-r--r--library/std/src/sys_common/wtf8/tests.rs6
5 files changed, 27 insertions, 14 deletions
diff --git a/library/std/src/ffi/os_str.rs b/library/std/src/ffi/os_str.rs
index bb577acf769..fbdf7f5ecac 100644
--- a/library/std/src/ffi/os_str.rs
+++ b/library/std/src/ffi/os_str.rs
@@ -745,7 +745,7 @@ impl OsStr {
                   without modifying the original"]
     #[inline]
     pub fn to_str(&self) -> Option<&str> {
-        self.inner.to_str()
+        self.inner.to_str().ok()
     }
 
     /// Converts an `OsStr` to a <code>[Cow]<[str]></code>.
@@ -1165,6 +1165,24 @@ impl<'a> From<Cow<'a, OsStr>> for OsString {
     }
 }
 
+#[stable(feature = "str_tryfrom_osstr_impl", since = "CURRENT_RUSTC_VERSION")]
+impl<'a> TryFrom<&'a OsStr> for &'a str {
+    type Error = crate::str::Utf8Error;
+
+    /// Tries to convert an `&OsStr` to a `&str`.
+    ///
+    /// ```
+    /// use std::ffi::OsStr;
+    ///
+    /// let os_str = OsStr::new("foo");
+    /// let as_str = <&str>::try_from(os_str).unwrap();
+    /// assert_eq!(as_str, "foo");
+    /// ```
+    fn try_from(value: &'a OsStr) -> Result<Self, Self::Error> {
+        value.inner.to_str()
+    }
+}
+
 #[stable(feature = "box_default_extra", since = "1.17.0")]
 impl Default for Box<OsStr> {
     #[inline]
diff --git a/library/std/src/sys/unix/os_str.rs b/library/std/src/sys/unix/os_str.rs
index 142fcb9ed0b..f7333fd5a1f 100644
--- a/library/std/src/sys/unix/os_str.rs
+++ b/library/std/src/sys/unix/os_str.rs
@@ -207,8 +207,8 @@ impl Slice {
         unsafe { Slice::from_os_str_bytes_unchecked(s.as_bytes()) }
     }
 
-    pub fn to_str(&self) -> Option<&str> {
-        str::from_utf8(&self.inner).ok()
+    pub fn to_str(&self) -> Result<&str, crate::str::Utf8Error> {
+        str::from_utf8(&self.inner)
     }
 
     pub fn to_string_lossy(&self) -> Cow<'_, str> {
diff --git a/library/std/src/sys/windows/os_str.rs b/library/std/src/sys/windows/os_str.rs
index 611f0d040f0..16c4f55c687 100644
--- a/library/std/src/sys/windows/os_str.rs
+++ b/library/std/src/sys/windows/os_str.rs
@@ -166,7 +166,7 @@ impl Slice {
         unsafe { mem::transmute(Wtf8::from_str(s)) }
     }
 
-    pub fn to_str(&self) -> Option<&str> {
+    pub fn to_str(&self) -> Result<&str, crate::str::Utf8Error> {
         self.inner.as_str()
     }
 
diff --git a/library/std/src/sys_common/wtf8.rs b/library/std/src/sys_common/wtf8.rs
index 31bb0ad25a6..c9d3e13cf0c 100644
--- a/library/std/src/sys_common/wtf8.rs
+++ b/library/std/src/sys_common/wtf8.rs
@@ -626,13 +626,8 @@ impl Wtf8 {
     ///
     /// This does not copy the data.
     #[inline]
-    pub fn as_str(&self) -> Option<&str> {
-        // Well-formed WTF-8 is also well-formed UTF-8
-        // if and only if it contains no surrogate.
-        match self.next_surrogate(0) {
-            None => Some(unsafe { str::from_utf8_unchecked(&self.bytes) }),
-            Some(_) => None,
-        }
+    pub fn as_str(&self) -> Result<&str, str::Utf8Error> {
+        str::from_utf8(&self.bytes)
     }
 
     /// Creates an owned `Wtf8Buf` from a borrowed `Wtf8`.
diff --git a/library/std/src/sys_common/wtf8/tests.rs b/library/std/src/sys_common/wtf8/tests.rs
index 1a302d64694..a07bbe6d7e4 100644
--- a/library/std/src/sys_common/wtf8/tests.rs
+++ b/library/std/src/sys_common/wtf8/tests.rs
@@ -521,11 +521,11 @@ fn wtf8_code_points() {
 
 #[test]
 fn wtf8_as_str() {
-    assert_eq!(Wtf8::from_str("").as_str(), Some(""));
-    assert_eq!(Wtf8::from_str("aé 💩").as_str(), Some("aé 💩"));
+    assert_eq!(Wtf8::from_str("").as_str(), Ok(""));
+    assert_eq!(Wtf8::from_str("aé 💩").as_str(), Ok("aé 💩"));
     let mut string = Wtf8Buf::new();
     string.push(CodePoint::from_u32(0xD800).unwrap());
-    assert_eq!(string.as_str(), None);
+    assert!(string.as_str().is_err());
 }
 
 #[test]