Move ThreadName conversions to &cstr/&str · model-checking/verify-rust-std@8378261 (original) (raw)

`@@ -1275,7 +1275,9 @@ enum ThreadName {

`

1275

1275

``

1276

1276

`// This module ensures private fields are kept private, which is necessary to enforce the safety requirements.

`

1277

1277

`mod thread_name_string {

`

``

1278

`+

use super::ThreadName;

`

1278

1279

`use crate::ffi::{CStr, CString};

`

``

1280

`+

use core::str;

`

1279

1281

``

1280

1282

`` /// Like a String it's guaranteed UTF-8 and like a CString it's null terminated.

``

1281

1283

`pub(crate) struct ThreadNameString {

`

`@@ -1294,6 +1296,21 @@ mod thread_name_string {

`

1294

1296

`}

`

1295

1297

`}

`

1296

1298

`}

`

``

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

`+

}

`

1297

1314

`}

`

1298

1315

`pub(crate) use thread_name_string::ThreadNameString;

`

1299

1316

``

`@@ -1472,15 +1489,11 @@ impl Thread {

`

1472

1489

`#[stable(feature = "rust1", since = "1.0.0")]

`

1473

1490

`#[must_use]

`

1474

1491

`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()

`

1476

1493

`}

`

1477

1494

``

1478

1495

`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()

`

1484

1497

`}

`

1485

1498

`}

`

1486

1499

``