]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/thread_info.rs
Auto merge of #43651 - petrochenkov:foreign-life, r=eddyb
[rust.git] / src / libstd / sys_common / thread_info.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(dead_code)] // stack_guard isn't used right now on all platforms
12
13 use cell::RefCell;
14 use thread::Thread;
15
16 struct ThreadInfo {
17     stack_guard: Option<usize>,
18     thread: Thread,
19 }
20
21 thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = RefCell::new(None) }
22
23 impl ThreadInfo {
24     fn with<R, F>(f: F) -> Option<R> where F: FnOnce(&mut ThreadInfo) -> R {
25         THREAD_INFO.try_with(move |c| {
26             if c.borrow().is_none() {
27                 *c.borrow_mut() = Some(ThreadInfo {
28                     stack_guard: None,
29                     thread: Thread::new(None),
30                 })
31             }
32             f(c.borrow_mut().as_mut().unwrap())
33         }).ok()
34     }
35 }
36
37 pub fn current_thread() -> Option<Thread> {
38     ThreadInfo::with(|info| info.thread.clone())
39 }
40
41 pub fn stack_guard() -> Option<usize> {
42     ThreadInfo::with(|info| info.stack_guard).and_then(|o| o)
43 }
44
45 pub fn set(stack_guard: Option<usize>, thread: Thread) {
46     THREAD_INFO.with(|c| assert!(c.borrow().is_none()));
47     THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo{
48         stack_guard: stack_guard,
49         thread: thread,
50     }));
51 }