Skip to content

Commit 4998b23

Browse files
committed
std::thread::AccessError: Add methods to determine source of error
1 parent f2ac4ef commit 4998b23

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

src/libstd/thread/local.rs

+34-4
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,33 @@ pub enum LocalKeyState {
276276
reason = "state querying was recently added",
277277
issue = "27716")]
278278
pub struct AccessError {
279-
_private: (),
279+
// whether the error was due to the key being in the Initializing
280+
// state - false means the key was in the Destroyed state
281+
init: bool,
282+
}
283+
284+
impl AccessError {
285+
/// Determines whether the `AccessError` was due to the key being initialized.
286+
///
287+
/// If `is_initializing` returns true, this `AccessError` was returned because
288+
/// the key was in the `Initializing` state when it was accessed.
289+
#[unstable(feature = "thread_local_state",
290+
reason = "state querying was recently added",
291+
issue = "27716")]
292+
pub fn is_initializing(&self) -> bool {
293+
self.init
294+
}
295+
296+
/// Determines whether the `AccessError` was due to the key being destroyed.
297+
///
298+
/// If `is_destroyed` returns true, this `AccessError` was returned because
299+
/// the key was in the `Destroyed` state when it was accessed.
300+
#[unstable(feature = "thread_local_state",
301+
reason = "state querying was recently added",
302+
issue = "27716")]
303+
pub fn is_destroyed(&self) -> bool {
304+
!self.init
305+
}
280306
}
281307

282308
#[unstable(feature = "thread_local_state",
@@ -293,7 +319,11 @@ impl fmt::Debug for AccessError {
293319
issue = "27716")]
294320
impl fmt::Display for AccessError {
295321
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
296-
fmt::Display::fmt("already destroyed", f)
322+
if self.init {
323+
fmt::Display::fmt("currently being initialized", f)
324+
} else {
325+
fmt::Display::fmt("already destroyed", f)
326+
}
297327
}
298328
}
299329

@@ -429,8 +459,8 @@ impl<T: 'static> LocalKey<T> {
429459
// not to enter this else block in the recursive call.
430460
self.try_with(f)
431461
}
432-
LocalKeyState::Initializing |
433-
LocalKeyState::Destroyed => Err(AccessError { _private: ()}),
462+
LocalKeyState::Initializing => Err(AccessError { init: true }),
463+
LocalKeyState::Destroyed => Err(AccessError { init: false }),
434464
LocalKeyState::Valid => unreachable!(),
435465
}
436466
}

0 commit comments

Comments
 (0)