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