mirror of
https://github.com/rust-lang/rust.git
synced 2025-06-04 19:29:07 +00:00
Move ThreadName conversions to &cstr/&str
This commit is contained in:
parent
8e4a9205e9
commit
9432955a01
@ -1275,7 +1275,9 @@ enum ThreadName {
|
|||||||
|
|
||||||
// This module ensures private fields are kept private, which is necessary to enforce the safety requirements.
|
// This module ensures private fields are kept private, which is necessary to enforce the safety requirements.
|
||||||
mod thread_name_string {
|
mod thread_name_string {
|
||||||
|
use super::ThreadName;
|
||||||
use crate::ffi::{CStr, CString};
|
use crate::ffi::{CStr, CString};
|
||||||
|
use core::str;
|
||||||
|
|
||||||
/// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated.
|
/// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated.
|
||||||
pub(crate) struct ThreadNameString {
|
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;
|
pub(crate) use thread_name_string::ThreadNameString;
|
||||||
|
|
||||||
@ -1472,15 +1489,11 @@ impl Thread {
|
|||||||
#[stable(feature = "rust1", since = "1.0.0")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn name(&self) -> Option<&str> {
|
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> {
|
fn cname(&self) -> Option<&CStr> {
|
||||||
match &self.inner.name {
|
self.inner.name.as_cstr()
|
||||||
ThreadName::Main => Some(c"main"),
|
|
||||||
ThreadName::Other(other) => Some(&other),
|
|
||||||
ThreadName::Unnamed => None,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user