]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread_local/scoped.rs
rollup merge of #20482: kmcallister/macro-reform
[rust.git] / src / libstd / thread_local / scoped.rs
1 // Copyright 2014-2015 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 //! Scoped thread-local storage
12 //!
13 //! This module provides the ability to generate *scoped* thread-local
14 //! variables. In this sense, scoped indicates that thread local storage
15 //! actually stores a reference to a value, and this reference is only placed
16 //! in storage for a scoped amount of time.
17 //!
18 //! There are no restrictions on what types can be placed into a scoped
19 //! variable, but all scoped variables are initialized to the equivalent of
20 //! null. Scoped thread local storage is useful when a value is present for a known
21 //! period of time and it is not required to relinquish ownership of the
22 //! contents.
23 //!
24 //! # Example
25 //!
26 //! ```
27 //! scoped_thread_local!(static FOO: uint);
28 //!
29 //! // Initially each scoped slot is empty.
30 //! assert!(!FOO.is_set());
31 //!
32 //! // When inserting a value, the value is only in place for the duration
33 //! // of the closure specified.
34 //! FOO.set(&1, || {
35 //!     FOO.with(|slot| {
36 //!         assert_eq!(*slot, 1);
37 //!     });
38 //! });
39 //! ```
40
41 #![unstable = "scoped TLS has yet to have wide enough use to fully consider \
42                stabilizing its interface"]
43
44 use prelude::v1::*;
45
46 // macro hygiene sure would be nice, wouldn't it?
47 #[doc(hidden)]
48 pub mod __impl {
49     pub use super::imp::KeyInner;
50     pub use sys_common::thread_local::INIT as OS_INIT;
51 }
52
53 /// Type representing a thread local storage key corresponding to a reference
54 /// to the type parameter `T`.
55 ///
56 /// Keys are statically allocated and can contain a reference to an instance of
57 /// type `T` scoped to a particular lifetime. Keys provides two methods, `set`
58 /// and `with`, both of which currently use closures to control the scope of
59 /// their contents.
60 pub struct Key<T> { #[doc(hidden)] pub inner: __impl::KeyInner<T> }
61
62 /// Declare a new scoped thread local storage key.
63 ///
64 /// This macro declares a `static` item on which methods are used to get and
65 /// set the value stored within.
66 #[macro_export]
67 macro_rules! scoped_thread_local {
68     (static $name:ident: $t:ty) => (
69         __scoped_thread_local_inner!(static $name: $t);
70     );
71     (pub static $name:ident: $t:ty) => (
72         __scoped_thread_local_inner!(pub static $name: $t);
73     );
74 }
75
76 #[macro_export]
77 #[doc(hidden)]
78 macro_rules! __scoped_thread_local_inner {
79     (static $name:ident: $t:ty) => (
80         #[cfg_attr(not(any(windows,
81                            target_os = "android",
82                            target_os = "ios",
83                            target_arch = "aarch64")),
84                    thread_local)]
85         static $name: ::std::thread_local::scoped::Key<$t> =
86             __scoped_thread_local_inner!($t);
87     );
88     (pub static $name:ident: $t:ty) => (
89         #[cfg_attr(not(any(windows,
90                            target_os = "android",
91                            target_os = "ios",
92                            target_arch = "aarch64")),
93                    thread_local)]
94         pub static $name: ::std::thread_local::scoped::Key<$t> =
95             __scoped_thread_local_inner!($t);
96     );
97     ($t:ty) => ({
98         use std::thread_local::scoped::Key as __Key;
99
100         #[cfg(not(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64")))]
101         const _INIT: __Key<$t> = __Key {
102             inner: ::std::thread_local::scoped::__impl::KeyInner {
103                 inner: ::std::cell::UnsafeCell { value: 0 as *mut _ },
104             }
105         };
106
107         #[cfg(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64"))]
108         const _INIT: __Key<$t> = __Key {
109             inner: ::std::thread_local::scoped::__impl::KeyInner {
110                 inner: ::std::thread_local::scoped::__impl::OS_INIT,
111                 marker: ::std::kinds::marker::InvariantType,
112             }
113         };
114
115         _INIT
116     })
117 }
118
119 impl<T> Key<T> {
120     /// Insert a value into this scoped thread local storage slot for a
121     /// duration of a closure.
122     ///
123     /// While `cb` is running, the value `t` will be returned by `get` unless
124     /// this function is called recursively inside of `cb`.
125     ///
126     /// Upon return, this function will restore the previous value, if any
127     /// was available.
128     ///
129     /// # Example
130     ///
131     /// ```
132     /// scoped_thread_local!(static FOO: uint);
133     ///
134     /// FOO.set(&100, || {
135     ///     let val = FOO.with(|v| *v);
136     ///     assert_eq!(val, 100);
137     ///
138     ///     // set can be called recursively
139     ///     FOO.set(&101, || {
140     ///         // ...
141     ///     });
142     ///
143     ///     // Recursive calls restore the previous value.
144     ///     let val = FOO.with(|v| *v);
145     ///     assert_eq!(val, 100);
146     /// });
147     /// ```
148     pub fn set<R, F>(&'static self, t: &T, cb: F) -> R where
149         F: FnOnce() -> R,
150     {
151         struct Reset<'a, T: 'a> {
152             key: &'a __impl::KeyInner<T>,
153             val: *mut T,
154         }
155         #[unsafe_destructor]
156         impl<'a, T> Drop for Reset<'a, T> {
157             fn drop(&mut self) {
158                 unsafe { self.key.set(self.val) }
159             }
160         }
161
162         let prev = unsafe {
163             let prev = self.inner.get();
164             self.inner.set(t as *const T as *mut T);
165             prev
166         };
167
168         let _reset = Reset { key: &self.inner, val: prev };
169         cb()
170     }
171
172     /// Get a value out of this scoped variable.
173     ///
174     /// This function takes a closure which receives the value of this
175     /// variable.
176     ///
177     /// # Panics
178     ///
179     /// This function will panic if `set` has not previously been called.
180     ///
181     /// # Example
182     ///
183     /// ```no_run
184     /// scoped_thread_local!(static FOO: uint);
185     ///
186     /// FOO.with(|slot| {
187     ///     // work with `slot`
188     /// });
189     /// ```
190     pub fn with<R, F>(&'static self, cb: F) -> R where
191         F: FnOnce(&T) -> R
192     {
193         unsafe {
194             let ptr = self.inner.get();
195             assert!(!ptr.is_null(), "cannot access a scoped thread local \
196                                      variable without calling `set` first");
197             cb(&*ptr)
198         }
199     }
200
201     /// Test whether this TLS key has been `set` for the current thread.
202     pub fn is_set(&'static self) -> bool {
203         unsafe { !self.inner.get().is_null() }
204     }
205 }
206
207 #[cfg(not(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64")))]
208 mod imp {
209     use std::cell::UnsafeCell;
210
211     #[doc(hidden)]
212     pub struct KeyInner<T> { pub inner: UnsafeCell<*mut T> }
213
214     unsafe impl<T> ::kinds::Sync for KeyInner<T> { }
215
216     #[doc(hidden)]
217     impl<T> KeyInner<T> {
218         #[doc(hidden)]
219         pub unsafe fn set(&self, ptr: *mut T) { *self.inner.get() = ptr; }
220         #[doc(hidden)]
221         pub unsafe fn get(&self) -> *mut T { *self.inner.get() }
222     }
223 }
224
225 #[cfg(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64"))]
226 mod imp {
227     use kinds::marker;
228     use sys_common::thread_local::StaticKey as OsStaticKey;
229
230     #[doc(hidden)]
231     pub struct KeyInner<T> {
232         pub inner: OsStaticKey,
233         pub marker: marker::InvariantType<T>,
234     }
235
236     unsafe impl<T> ::kinds::Sync for KeyInner<T> { }
237
238     #[doc(hidden)]
239     impl<T> KeyInner<T> {
240         #[doc(hidden)]
241         pub unsafe fn set(&self, ptr: *mut T) { self.inner.set(ptr as *mut _) }
242         #[doc(hidden)]
243         pub unsafe fn get(&self) -> *mut T { self.inner.get() as *mut _ }
244     }
245 }
246
247
248 #[cfg(test)]
249 mod tests {
250     use cell::Cell;
251     use prelude::v1::*;
252
253     scoped_thread_local!(static FOO: uint);
254
255     #[test]
256     fn smoke() {
257         scoped_thread_local!(static BAR: uint);
258
259         assert!(!BAR.is_set());
260         BAR.set(&1, || {
261             assert!(BAR.is_set());
262             BAR.with(|slot| {
263                 assert_eq!(*slot, 1);
264             });
265         });
266         assert!(!BAR.is_set());
267     }
268
269     #[test]
270     fn cell_allowed() {
271         scoped_thread_local!(static BAR: Cell<uint>);
272
273         BAR.set(&Cell::new(1), || {
274             BAR.with(|slot| {
275                 assert_eq!(slot.get(), 1);
276             });
277         });
278     }
279
280     #[test]
281     fn scope_item_allowed() {
282         assert!(!FOO.is_set());
283         FOO.set(&1, || {
284             assert!(FOO.is_set());
285             FOO.with(|slot| {
286                 assert_eq!(*slot, 1);
287             });
288         });
289         assert!(!FOO.is_set());
290     }
291 }