]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread/local.rs
Auto merge of #43651 - petrochenkov:foreign-life, r=eddyb
[rust.git] / src / libstd / thread / local.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 //! Thread local storage
12
13 #![unstable(feature = "thread_local_internals", issue = "0")]
14
15 use cell::UnsafeCell;
16 use fmt;
17 use mem;
18
19 /// A thread local storage key which owns its contents.
20 ///
21 /// This key uses the fastest possible implementation available to it for the
22 /// target platform. It is instantiated with the [`thread_local!`] macro and the
23 /// primary method is the [`with`] method.
24 ///
25 /// The [`with`] method yields a reference to the contained value which cannot be
26 /// sent across threads or escape the given closure.
27 ///
28 /// # Initialization and Destruction
29 ///
30 /// Initialization is dynamically performed on the first call to [`with`]
31 /// within a thread, and values that implement [`Drop`] get destructed when a
32 /// thread exits. Some caveats apply, which are explained below.
33 ///
34 /// # Examples
35 ///
36 /// ```
37 /// use std::cell::RefCell;
38 /// use std::thread;
39 ///
40 /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
41 ///
42 /// FOO.with(|f| {
43 ///     assert_eq!(*f.borrow(), 1);
44 ///     *f.borrow_mut() = 2;
45 /// });
46 ///
47 /// // each thread starts out with the initial value of 1
48 /// thread::spawn(move|| {
49 ///     FOO.with(|f| {
50 ///         assert_eq!(*f.borrow(), 1);
51 ///         *f.borrow_mut() = 3;
52 ///     });
53 /// });
54 ///
55 /// // we retain our original value of 2 despite the child thread
56 /// FOO.with(|f| {
57 ///     assert_eq!(*f.borrow(), 2);
58 /// });
59 /// ```
60 ///
61 /// # Platform-specific behavior
62 ///
63 /// Note that a "best effort" is made to ensure that destructors for types
64 /// stored in thread local storage are run, but not all platforms can guarantee
65 /// that destructors will be run for all types in thread local storage. For
66 /// example, there are a number of known caveats where destructors are not run:
67 ///
68 /// 1. On Unix systems when pthread-based TLS is being used, destructors will
69 ///    not be run for TLS values on the main thread when it exits. Note that the
70 ///    application will exit immediately after the main thread exits as well.
71 /// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
72 ///    during destruction. Some platforms ensure that this cannot happen
73 ///    infinitely by preventing re-initialization of any slot that has been
74 ///    destroyed, but not all platforms have this guard. Those platforms that do
75 ///    not guard typically have a synthetic limit after which point no more
76 ///    destructors are run.
77 /// 3. On macOS, initializing TLS during destruction of other TLS slots can
78 ///    sometimes cancel *all* destructors for the current thread, whether or not
79 ///    the slots have already had their destructors run or not.
80 ///
81 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
82 /// [`thread_local!`]: ../../std/macro.thread_local.html
83 /// [`Drop`]: ../../std/ops/trait.Drop.html
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct LocalKey<T: 'static> {
86     // This outer `LocalKey<T>` type is what's going to be stored in statics,
87     // but actual data inside will sometimes be tagged with #[thread_local].
88     // It's not valid for a true static to reference a #[thread_local] static,
89     // so we get around that by exposing an accessor through a layer of function
90     // indirection (this thunk).
91     //
92     // Note that the thunk is itself unsafe because the returned lifetime of the
93     // slot where data lives, `'static`, is not actually valid. The lifetime
94     // here is actually slightly shorter than the currently running thread!
95     //
96     // Although this is an extra layer of indirection, it should in theory be
97     // trivially devirtualizable by LLVM because the value of `inner` never
98     // changes and the constant should be readonly within a crate. This mainly
99     // only runs into problems when TLS statics are exported across crates.
100     inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
101
102     // initialization routine to invoke to create a value
103     init: fn() -> T,
104 }
105
106 #[stable(feature = "std_debug", since = "1.16.0")]
107 impl<T: 'static> fmt::Debug for LocalKey<T> {
108     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109         f.pad("LocalKey { .. }")
110     }
111 }
112
113 /// Declare a new thread local storage key of type [`std::thread::LocalKey`].
114 ///
115 /// # Syntax
116 ///
117 /// The macro wraps any number of static declarations and makes them thread local.
118 /// Publicity and attributes for each static are allowed. Example:
119 ///
120 /// ```
121 /// use std::cell::RefCell;
122 /// thread_local! {
123 ///     pub static FOO: RefCell<u32> = RefCell::new(1);
124 ///
125 ///     #[allow(unused)]
126 ///     static BAR: RefCell<f32> = RefCell::new(1.0);
127 /// }
128 /// # fn main() {}
129 /// ```
130 ///
131 /// See [LocalKey documentation][`std::thread::LocalKey`] for more
132 /// information.
133 ///
134 /// [`std::thread::LocalKey`]: ../std/thread/struct.LocalKey.html
135 #[macro_export]
136 #[stable(feature = "rust1", since = "1.0.0")]
137 #[allow_internal_unstable]
138 macro_rules! thread_local {
139     // empty (base case for the recursion)
140     () => {};
141
142     // process multiple declarations
143     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
144         __thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
145         thread_local!($($rest)*);
146     );
147
148     // handle a single declaration
149     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
150         __thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
151     );
152 }
153
154 #[doc(hidden)]
155 #[unstable(feature = "thread_local_internals",
156            reason = "should not be necessary",
157            issue = "0")]
158 #[macro_export]
159 #[allow_internal_unstable]
160 #[cfg_attr(not(stage0), allow_internal_unsafe)]
161 macro_rules! __thread_local_inner {
162     ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
163         $(#[$attr])* $vis static $name: $crate::thread::LocalKey<$t> = {
164             fn __init() -> $t { $init }
165
166             unsafe fn __getit() -> $crate::option::Option<
167                 &'static $crate::cell::UnsafeCell<
168                     $crate::option::Option<$t>>>
169             {
170                 #[thread_local]
171                 #[cfg(target_thread_local)]
172                 static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
173                     $crate::thread::__FastLocalKeyInner::new();
174
175                 #[cfg(not(target_thread_local))]
176                 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
177                     $crate::thread::__OsLocalKeyInner::new();
178
179                 __KEY.get()
180             }
181
182             unsafe {
183                 $crate::thread::LocalKey::new(__getit, __init)
184             }
185         };
186     }
187 }
188
189 /// Indicator of the state of a thread local storage key.
190 #[unstable(feature = "thread_local_state",
191            reason = "state querying was recently added",
192            issue = "27716")]
193 #[derive(Debug, Eq, PartialEq, Copy, Clone)]
194 pub enum LocalKeyState {
195     /// All keys are in this state whenever a thread starts. Keys will
196     /// transition to the `Valid` state once the first call to [`with`] happens
197     /// and the initialization expression succeeds.
198     ///
199     /// Keys in the `Uninitialized` state will yield a reference to the closure
200     /// passed to [`with`] so long as the initialization routine does not panic.
201     ///
202     /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
203     Uninitialized,
204
205     /// Once a key has been accessed successfully, it will enter the `Valid`
206     /// state. Keys in the `Valid` state will remain so until the thread exits,
207     /// at which point the destructor will be run and the key will enter the
208     /// `Destroyed` state.
209     ///
210     /// Keys in the `Valid` state will be guaranteed to yield a reference to the
211     /// closure passed to [`with`].
212     ///
213     /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
214     Valid,
215
216     /// When a thread exits, the destructors for keys will be run (if
217     /// necessary). While a destructor is running, and possibly after a
218     /// destructor has run, a key is in the `Destroyed` state.
219     ///
220     /// Keys in the `Destroyed` states will trigger a panic when accessed via
221     /// [`with`].
222     ///
223     /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
224     Destroyed,
225 }
226
227 /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
228 #[unstable(feature = "thread_local_state",
229            reason = "state querying was recently added",
230            issue = "27716")]
231 pub struct AccessError {
232     _private: (),
233 }
234
235 #[unstable(feature = "thread_local_state",
236            reason = "state querying was recently added",
237            issue = "27716")]
238 impl fmt::Debug for AccessError {
239     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
240         f.debug_struct("AccessError").finish()
241     }
242 }
243
244 #[unstable(feature = "thread_local_state",
245            reason = "state querying was recently added",
246            issue = "27716")]
247 impl fmt::Display for AccessError {
248     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
249         fmt::Display::fmt("already destroyed", f)
250     }
251 }
252
253 impl<T: 'static> LocalKey<T> {
254     #[doc(hidden)]
255     #[unstable(feature = "thread_local_internals",
256                reason = "recently added to create a key",
257                issue = "0")]
258     pub const unsafe fn new(inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
259                             init: fn() -> T) -> LocalKey<T> {
260         LocalKey {
261             inner: inner,
262             init: init,
263         }
264     }
265
266     /// Acquires a reference to the value in this TLS key.
267     ///
268     /// This will lazily initialize the value if this thread has not referenced
269     /// this key yet.
270     ///
271     /// # Panics
272     ///
273     /// This function will `panic!()` if the key currently has its
274     /// destructor running, and it **may** panic if the destructor has
275     /// previously been run for this thread.
276     #[stable(feature = "rust1", since = "1.0.0")]
277     pub fn with<F, R>(&'static self, f: F) -> R
278                       where F: FnOnce(&T) -> R {
279         self.try_with(f).expect("cannot access a TLS value during or \
280                                  after it is destroyed")
281     }
282
283     unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
284         // Execute the initialization up front, *then* move it into our slot,
285         // just in case initialization fails.
286         let value = (self.init)();
287         let ptr = slot.get();
288
289         // note that this can in theory just be `*ptr = Some(value)`, but due to
290         // the compiler will currently codegen that pattern with something like:
291         //
292         //      ptr::drop_in_place(ptr)
293         //      ptr::write(ptr, Some(value))
294         //
295         // Due to this pattern it's possible for the destructor of the value in
296         // `ptr` (e.g. if this is being recursively initialized) to re-access
297         // TLS, in which case there will be a `&` and `&mut` pointer to the same
298         // value (an aliasing violation). To avoid setting the "I'm running a
299         // destructor" flag we just use `mem::replace` which should sequence the
300         // operations a little differently and make this safe to call.
301         mem::replace(&mut *ptr, Some(value));
302
303         (*ptr).as_ref().unwrap()
304     }
305
306     /// Query the current state of this key.
307     ///
308     /// A key is initially in the `Uninitialized` state whenever a thread
309     /// starts. It will remain in this state up until the first call to [`with`]
310     /// within a thread has run the initialization expression successfully.
311     ///
312     /// Once the initialization expression succeeds, the key transitions to the
313     /// `Valid` state which will guarantee that future calls to [`with`] will
314     /// succeed within the thread.
315     ///
316     /// When a thread exits, each key will be destroyed in turn, and as keys are
317     /// destroyed they will enter the `Destroyed` state just before the
318     /// destructor starts to run. Keys may remain in the `Destroyed` state after
319     /// destruction has completed. Keys without destructors (e.g. with types
320     /// that are [`Copy`]), may never enter the `Destroyed` state.
321     ///
322     /// Keys in the `Uninitialized` state can be accessed so long as the
323     /// initialization does not panic. Keys in the `Valid` state are guaranteed
324     /// to be able to be accessed. Keys in the `Destroyed` state will panic on
325     /// any call to [`with`].
326     ///
327     /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
328     /// [`Copy`]: ../../std/marker/trait.Copy.html
329     #[unstable(feature = "thread_local_state",
330                reason = "state querying was recently added",
331                issue = "27716")]
332     pub fn state(&'static self) -> LocalKeyState {
333         unsafe {
334             match (self.inner)() {
335                 Some(cell) => {
336                     match *cell.get() {
337                         Some(..) => LocalKeyState::Valid,
338                         None => LocalKeyState::Uninitialized,
339                     }
340                 }
341                 None => LocalKeyState::Destroyed,
342             }
343         }
344     }
345
346     /// Acquires a reference to the value in this TLS key.
347     ///
348     /// This will lazily initialize the value if this thread has not referenced
349     /// this key yet. If the key has been destroyed (which may happen if this is called
350     /// in a destructor), this function will return a ThreadLocalError.
351     ///
352     /// # Panics
353     ///
354     /// This function will still `panic!()` if the key is uninitialized and the
355     /// key's initializer panics.
356     #[unstable(feature = "thread_local_state",
357                reason = "state querying was recently added",
358                issue = "27716")]
359     pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
360                       where F: FnOnce(&T) -> R {
361         unsafe {
362             let slot = (self.inner)().ok_or(AccessError {
363                 _private: (),
364             })?;
365             Ok(f(match *slot.get() {
366                 Some(ref inner) => inner,
367                 None => self.init(slot),
368             }))
369         }
370     }
371 }
372
373 #[doc(hidden)]
374 #[cfg(target_thread_local)]
375 pub mod fast {
376     use cell::{Cell, UnsafeCell};
377     use fmt;
378     use mem;
379     use ptr;
380     use sys::fast_thread_local::{register_dtor, requires_move_before_drop};
381
382     pub struct Key<T> {
383         inner: UnsafeCell<Option<T>>,
384
385         // Metadata to keep track of the state of the destructor. Remember that
386         // these variables are thread-local, not global.
387         dtor_registered: Cell<bool>,
388         dtor_running: Cell<bool>,
389     }
390
391     impl<T> fmt::Debug for Key<T> {
392         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
393             f.pad("Key { .. }")
394         }
395     }
396
397     #[cfg(stage0)]
398     unsafe impl<T> ::marker::Sync for Key<T> { }
399
400     impl<T> Key<T> {
401         pub const fn new() -> Key<T> {
402             Key {
403                 inner: UnsafeCell::new(None),
404                 dtor_registered: Cell::new(false),
405                 dtor_running: Cell::new(false)
406             }
407         }
408
409         pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> {
410             if mem::needs_drop::<T>() && self.dtor_running.get() {
411                 return None
412             }
413             self.register_dtor();
414             Some(&*(&self.inner as *const _))
415         }
416
417         unsafe fn register_dtor(&self) {
418             if !mem::needs_drop::<T>() || self.dtor_registered.get() {
419                 return
420             }
421
422             register_dtor(self as *const _ as *mut u8,
423                           destroy_value::<T>);
424             self.dtor_registered.set(true);
425         }
426     }
427
428     unsafe extern fn destroy_value<T>(ptr: *mut u8) {
429         let ptr = ptr as *mut Key<T>;
430         // Right before we run the user destructor be sure to flag the
431         // destructor as running for this thread so calls to `get` will return
432         // `None`.
433         (*ptr).dtor_running.set(true);
434
435         // Some implementations may require us to move the value before we drop
436         // it as it could get re-initialized in-place during destruction.
437         //
438         // Hence, we use `ptr::read` on those platforms (to move to a "safe"
439         // location) instead of drop_in_place.
440         if requires_move_before_drop() {
441             ptr::read((*ptr).inner.get());
442         } else {
443             ptr::drop_in_place((*ptr).inner.get());
444         }
445     }
446 }
447
448 #[doc(hidden)]
449 pub mod os {
450     use cell::{Cell, UnsafeCell};
451     use fmt;
452     use marker;
453     use ptr;
454     use sys_common::thread_local::StaticKey as OsStaticKey;
455
456     pub struct Key<T> {
457         // OS-TLS key that we'll use to key off.
458         os: OsStaticKey,
459         marker: marker::PhantomData<Cell<T>>,
460     }
461
462     impl<T> fmt::Debug for Key<T> {
463         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
464             f.pad("Key { .. }")
465         }
466     }
467
468     unsafe impl<T> ::marker::Sync for Key<T> { }
469
470     struct Value<T: 'static> {
471         key: &'static Key<T>,
472         value: UnsafeCell<Option<T>>,
473     }
474
475     impl<T: 'static> Key<T> {
476         pub const fn new() -> Key<T> {
477             Key {
478                 os: OsStaticKey::new(Some(destroy_value::<T>)),
479                 marker: marker::PhantomData
480             }
481         }
482
483         pub unsafe fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
484             let ptr = self.os.get() as *mut Value<T>;
485             if !ptr.is_null() {
486                 if ptr as usize == 1 {
487                     return None
488                 }
489                 return Some(&(*ptr).value);
490             }
491
492             // If the lookup returned null, we haven't initialized our own
493             // local copy, so do that now.
494             let ptr: Box<Value<T>> = box Value {
495                 key: self,
496                 value: UnsafeCell::new(None),
497             };
498             let ptr = Box::into_raw(ptr);
499             self.os.set(ptr as *mut u8);
500             Some(&(*ptr).value)
501         }
502     }
503
504     unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
505         // The OS TLS ensures that this key contains a NULL value when this
506         // destructor starts to run. We set it back to a sentinel value of 1 to
507         // ensure that any future calls to `get` for this thread will return
508         // `None`.
509         //
510         // Note that to prevent an infinite loop we reset it back to null right
511         // before we return from the destructor ourselves.
512         let ptr = Box::from_raw(ptr as *mut Value<T>);
513         let key = ptr.key;
514         key.os.set(1 as *mut u8);
515         drop(ptr);
516         key.os.set(ptr::null_mut());
517     }
518 }
519
520 #[cfg(all(test, not(target_os = "emscripten")))]
521 mod tests {
522     use sync::mpsc::{channel, Sender};
523     use cell::{Cell, UnsafeCell};
524     use super::LocalKeyState;
525     use thread;
526
527     struct Foo(Sender<()>);
528
529     impl Drop for Foo {
530         fn drop(&mut self) {
531             let Foo(ref s) = *self;
532             s.send(()).unwrap();
533         }
534     }
535
536     #[test]
537     fn smoke_no_dtor() {
538         thread_local!(static FOO: Cell<i32> = Cell::new(1));
539
540         FOO.with(|f| {
541             assert_eq!(f.get(), 1);
542             f.set(2);
543         });
544         let (tx, rx) = channel();
545         let _t = thread::spawn(move|| {
546             FOO.with(|f| {
547                 assert_eq!(f.get(), 1);
548             });
549             tx.send(()).unwrap();
550         });
551         rx.recv().unwrap();
552
553         FOO.with(|f| {
554             assert_eq!(f.get(), 2);
555         });
556     }
557
558     #[test]
559     fn states() {
560         struct Foo;
561         impl Drop for Foo {
562             fn drop(&mut self) {
563                 assert!(FOO.state() == LocalKeyState::Destroyed);
564             }
565         }
566         fn foo() -> Foo {
567             assert!(FOO.state() == LocalKeyState::Uninitialized);
568             Foo
569         }
570         thread_local!(static FOO: Foo = foo());
571
572         thread::spawn(|| {
573             assert!(FOO.state() == LocalKeyState::Uninitialized);
574             FOO.with(|_| {
575                 assert!(FOO.state() == LocalKeyState::Valid);
576             });
577             assert!(FOO.state() == LocalKeyState::Valid);
578         }).join().ok().unwrap();
579     }
580
581     #[test]
582     fn smoke_dtor() {
583         thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
584
585         let (tx, rx) = channel();
586         let _t = thread::spawn(move|| unsafe {
587             let mut tx = Some(tx);
588             FOO.with(|f| {
589                 *f.get() = Some(Foo(tx.take().unwrap()));
590             });
591         });
592         rx.recv().unwrap();
593     }
594
595     #[test]
596     fn circular() {
597         struct S1;
598         struct S2;
599         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
600         thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell::new(None));
601         static mut HITS: u32 = 0;
602
603         impl Drop for S1 {
604             fn drop(&mut self) {
605                 unsafe {
606                     HITS += 1;
607                     if K2.state() == LocalKeyState::Destroyed {
608                         assert_eq!(HITS, 3);
609                     } else {
610                         if HITS == 1 {
611                             K2.with(|s| *s.get() = Some(S2));
612                         } else {
613                             assert_eq!(HITS, 3);
614                         }
615                     }
616                 }
617             }
618         }
619         impl Drop for S2 {
620             fn drop(&mut self) {
621                 unsafe {
622                     HITS += 1;
623                     assert!(K1.state() != LocalKeyState::Destroyed);
624                     assert_eq!(HITS, 2);
625                     K1.with(|s| *s.get() = Some(S1));
626                 }
627             }
628         }
629
630         thread::spawn(move|| {
631             drop(S1);
632         }).join().ok().unwrap();
633     }
634
635     #[test]
636     fn self_referential() {
637         struct S1;
638         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
639
640         impl Drop for S1 {
641             fn drop(&mut self) {
642                 assert!(K1.state() == LocalKeyState::Destroyed);
643             }
644         }
645
646         thread::spawn(move|| unsafe {
647             K1.with(|s| *s.get() = Some(S1));
648         }).join().ok().unwrap();
649     }
650
651     // Note that this test will deadlock if TLS destructors aren't run (this
652     // requires the destructor to be run to pass the test). macOS has a known bug
653     // where dtors-in-dtors may cancel other destructors, so we just ignore this
654     // test on macOS.
655     #[test]
656     #[cfg_attr(target_os = "macos", ignore)]
657     fn dtors_in_dtors_in_dtors() {
658         struct S1(Sender<()>);
659         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
660         thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
661
662         impl Drop for S1 {
663             fn drop(&mut self) {
664                 let S1(ref tx) = *self;
665                 unsafe {
666                     if K2.state() != LocalKeyState::Destroyed {
667                         K2.with(|s| *s.get() = Some(Foo(tx.clone())));
668                     }
669                 }
670             }
671         }
672
673         let (tx, rx) = channel();
674         let _t = thread::spawn(move|| unsafe {
675             let mut tx = Some(tx);
676             K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
677         });
678         rx.recv().unwrap();
679     }
680 }
681
682 #[cfg(test)]
683 mod dynamic_tests {
684     use cell::RefCell;
685     use collections::HashMap;
686
687     #[test]
688     fn smoke() {
689         fn square(i: i32) -> i32 { i * i }
690         thread_local!(static FOO: i32 = square(3));
691
692         FOO.with(|f| {
693             assert_eq!(*f, 9);
694         });
695     }
696
697     #[test]
698     fn hashmap() {
699         fn map() -> RefCell<HashMap<i32, i32>> {
700             let mut m = HashMap::new();
701             m.insert(1, 2);
702             RefCell::new(m)
703         }
704         thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
705
706         FOO.with(|map| {
707             assert_eq!(map.borrow()[&1], 2);
708         });
709     }
710
711     #[test]
712     fn refcell_vec() {
713         thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
714
715         FOO.with(|vec| {
716             assert_eq!(vec.borrow().len(), 3);
717             vec.borrow_mut().push(4);
718             assert_eq!(vec.borrow()[3], 4);
719         });
720     }
721 }