Skip to content

Commit 8378261

Browse files
committed
Move ThreadName conversions to &cstr/&str
1 parent 68e2391 commit 8378261

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

std/src/thread/mod.rs

+19-6
Original file line numberDiff line numberDiff line change
@@ -1275,7 +1275,9 @@ enum ThreadName {
12751275

12761276
// This module ensures private fields are kept private, which is necessary to enforce the safety requirements.
12771277
mod thread_name_string {
1278+
use super::ThreadName;
12781279
use crate::ffi::{CStr, CString};
1280+
use core::str;
12791281

12801282
/// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated.
12811283
pub(crate) struct ThreadNameString {
@@ -1294,6 +1296,21 @@ mod thread_name_string {
12941296
}
12951297
}
12961298
}
1299+
impl ThreadName {
1300+
pub fn as_cstr(&self) -> Option<&CStr> {
1301+
match self {
1302+
ThreadName::Main => Some(c"main"),
1303+
ThreadName::Other(other) => Some(other),
1304+
ThreadName::Unnamed => None,
1305+
}
1306+
}
1307+
1308+
pub fn as_str(&self) -> Option<&str> {
1309+
// SAFETY: `as_cstr` can only return `Some` for a fixed CStr or a `ThreadNameString`,
1310+
// which is guaranteed to be UTF-8.
1311+
self.as_cstr().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
1312+
}
1313+
}
12971314
}
12981315
pub(crate) use thread_name_string::ThreadNameString;
12991316

@@ -1472,15 +1489,11 @@ impl Thread {
14721489
#[stable(feature = "rust1", since = "1.0.0")]
14731490
#[must_use]
14741491
pub fn name(&self) -> Option<&str> {
1475-
self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
1492+
self.inner.name.as_str()
14761493
}
14771494

14781495
fn cname(&self) -> Option<&CStr> {
1479-
match &self.inner.name {
1480-
ThreadName::Main => Some(c"main"),
1481-
ThreadName::Other(other) => Some(&other),
1482-
ThreadName::Unnamed => None,
1483-
}
1496+
self.inner.name.as_cstr()
14841497
}
14851498
}
14861499

0 commit comments

Comments
 (0)