about summary refs log tree commit diff
path: root/library/std/src/thread/mod.rs
diff options
context:
space:
mode:
authorChris Denton <chris@chrisdenton.dev>2024-07-18 18:13:11 +0000
committerChris Denton <chris@chrisdenton.dev>2024-07-18 19:53:09 +0000
commit9432955a01b989d3f4122887875643ef8dbea589 (patch)
tree0fbeed39297a7d9fd79ba4dce22e11682ff3280a /library/std/src/thread/mod.rs
parent8e4a9205e9fc0a86695799042e6fb70756bbfea2 (diff)
downloadrust-9432955a01b989d3f4122887875643ef8dbea589.tar.gz
rust-9432955a01b989d3f4122887875643ef8dbea589.zip
Move ThreadName conversions to &cstr/&str
Diffstat (limited to 'library/std/src/thread/mod.rs')
-rw-r--r--library/std/src/thread/mod.rs25
1 files changed, 19 insertions, 6 deletions
diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs
index f3d20026c27..0c908a5adae 100644
--- a/library/std/src/thread/mod.rs
+++ b/library/std/src/thread/mod.rs
@@ -1275,7 +1275,9 @@ enum ThreadName {
 
 // This module ensures private fields are kept private, which is necessary to enforce the safety requirements.
 mod thread_name_string {
+    use super::ThreadName;
     use crate::ffi::{CStr, CString};
+    use core::str;
 
     /// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated.
     pub(crate) struct ThreadNameString {
@@ -1294,6 +1296,21 @@ mod thread_name_string {
             }
         }
     }
+    impl ThreadName {
+        pub fn as_cstr(&self) -> Option<&CStr> {
+            match self {
+                ThreadName::Main => Some(c"main"),
+                ThreadName::Other(other) => Some(other),
+                ThreadName::Unnamed => None,
+            }
+        }
+
+        pub fn as_str(&self) -> Option<&str> {
+            // SAFETY: `as_cstr` can only return `Some` for a fixed CStr or a `ThreadNameString`,
+            // which is guaranteed to be UTF-8.
+            self.as_cstr().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
+        }
+    }
 }
 pub(crate) use thread_name_string::ThreadNameString;
 
@@ -1472,15 +1489,11 @@ impl Thread {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[must_use]
     pub fn name(&self) -> Option<&str> {
-        self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
+        self.inner.name.as_str()
     }
 
     fn cname(&self) -> Option<&CStr> {
-        match &self.inner.name {
-            ThreadName::Main => Some(c"main"),
-            ThreadName::Other(other) => Some(&other),
-            ThreadName::Unnamed => None,
-        }
+        self.inner.name.as_cstr()
     }
 }