1 // Copyright 2013 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.
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.
13 use alloc::boxed::Box;
17 /// Encapsulates some task-local data.
18 pub trait Local<Borrowed> {
19 fn put(value: Box<Self>);
20 fn take() -> Box<Self>;
21 fn try_take() -> Option<Box<Self>>;
22 fn exists(unused_value: Option<Self>) -> bool;
23 fn borrow(unused_value: Option<Self>) -> Borrowed;
24 unsafe fn unsafe_take() -> Box<Self>;
25 unsafe fn unsafe_borrow() -> *mut Self;
26 unsafe fn try_unsafe_borrow() -> Option<*mut Self>;
29 #[allow(visible_private_types)]
30 impl Local<local_ptr::Borrowed<Task>> for Task {
32 fn put(value: Box<Task>) { unsafe { local_ptr::put(value) } }
34 fn take() -> Box<Task> { unsafe { local_ptr::take() } }
36 fn try_take() -> Option<Box<Task>> { unsafe { local_ptr::try_take() } }
37 fn exists(_: Option<Task>) -> bool { local_ptr::exists() }
39 fn borrow(_: Option<Task>) -> local_ptr::Borrowed<Task> {
41 local_ptr::borrow::<Task>()
45 unsafe fn unsafe_take() -> Box<Task> { local_ptr::unsafe_take() }
47 unsafe fn unsafe_borrow() -> *mut Task { local_ptr::unsafe_borrow() }
49 unsafe fn try_unsafe_borrow() -> Option<*mut Task> {
50 local_ptr::try_unsafe_borrow()
57 use std::rt::thread::Thread;
62 fn thread_local_task_smoke_test() {
63 Thread::start(proc() {
64 let task = box Task::new();
66 let task: Box<Task> = Local::take();
72 fn thread_local_task_two_instances() {
73 Thread::start(proc() {
74 let task = box Task::new();
76 let task: Box<Task> = Local::take();
78 let task = box Task::new();
80 let task: Box<Task> = Local::take();
86 fn borrow_smoke_test() {
87 Thread::start(proc() {
88 let task = box Task::new();
92 let _task: *mut Task = Local::unsafe_borrow();
94 let task: Box<Task> = Local::take();
100 fn borrow_with_return() {
101 Thread::start(proc() {
102 let task = box Task::new();
106 let _ = Local::borrow(None::<Task>);
109 let task: Box<Task> = Local::take();
116 Thread::start(proc() {
117 let task = box Task::new();
120 let t: Box<Task> = Local::try_take().unwrap();
121 let u: Option<Box<Task>> = Local::try_take();
122 assert!(u.is_none());
128 fn cleanup_task(mut t: Box<Task>) {