]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys_common/thread_info.rs
Rollup merge of #98334 - JohnTitor:issue-73727, r=compiler-errors
[rust.git] / library / std / src / sys_common / thread_info.rs
1 #![allow(dead_code)] // stack_guard isn't used right now on all platforms
2 #![allow(unused_unsafe)] // thread_local with `const {}` triggers this liny
3
4 use crate::cell::RefCell;
5 use crate::sys::thread::guard::Guard;
6 use crate::thread::Thread;
7
8 struct ThreadInfo {
9     stack_guard: Option<Guard>,
10     thread: Thread,
11 }
12
13 thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = const { RefCell::new(None) } }
14
15 impl ThreadInfo {
16     fn with<R, F>(f: F) -> Option<R>
17     where
18         F: FnOnce(&mut ThreadInfo) -> R,
19     {
20         THREAD_INFO
21             .try_with(move |thread_info| {
22                 let mut thread_info = thread_info.borrow_mut();
23                 let thread_info = thread_info.get_or_insert_with(|| ThreadInfo {
24                     stack_guard: None,
25                     thread: Thread::new(None),
26                 });
27                 f(thread_info)
28             })
29             .ok()
30     }
31 }
32
33 pub fn current_thread() -> Option<Thread> {
34     ThreadInfo::with(|info| info.thread.clone())
35 }
36
37 pub fn stack_guard() -> Option<Guard> {
38     ThreadInfo::with(|info| info.stack_guard.clone()).and_then(|o| o)
39 }
40
41 pub fn set(stack_guard: Option<Guard>, thread: Thread) {
42     THREAD_INFO.with(move |thread_info| {
43         let mut thread_info = thread_info.borrow_mut();
44         rtassert!(thread_info.is_none());
45         *thread_info = Some(ThreadInfo { stack_guard, thread });
46     });
47 }