Skip to main content

thread_local/
lib.rs

1// Copyright 2017 Amanieu d'Antras
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! Per-object thread-local storage
9//!
10//! This library provides the `ThreadLocal` type which allows a separate copy of
11//! an object to be used for each thread. This allows for per-object
12//! thread-local storage, unlike the standard library's `thread_local!` macro
13//! which only allows static thread-local storage.
14//!
15//! Per-thread objects are not destroyed when a thread exits. Instead, objects
16//! are only destroyed when the `ThreadLocal` containing them is destroyed.
17//!
18//! You can also iterate over the thread-local values of all thread in a
19//! `ThreadLocal` object using the `iter_mut` and `into_iter` methods. This can
20//! only be done if you have mutable access to the `ThreadLocal` object, which
21//! guarantees that you are the only thread currently accessing it.
22//!
23//! Note that since thread IDs are recycled when a thread exits, it is possible
24//! for one thread to retrieve the object of another thread. Since this can only
25//! occur after a thread has exited this does not lead to any race conditions.
26//!
27//! # Examples
28//!
29//! Basic usage of `ThreadLocal`:
30//!
31//! ```rust
32//! use thread_local::ThreadLocal;
33//! let tls: ThreadLocal<u32> = ThreadLocal::new();
34//! assert_eq!(tls.get(), None);
35//! assert_eq!(tls.get_or(|| 5), &5);
36//! assert_eq!(tls.get(), Some(&5));
37//! ```
38//!
39//! Combining thread-local values into a single result:
40//!
41//! ```rust
42//! use thread_local::ThreadLocal;
43//! use std::cell::Cell;
44//! use std::thread;
45//!
46//! let tls = ThreadLocal::new();
47//!
48//! // Create a bunch of threads to do stuff
49//! thread::scope(|scope| {
50//!     for _ in 0..5 {
51//!         scope.spawn(|| {
52//!             // Increment a counter to count some event...
53//!             let cell = tls.get_or(|| Cell::new(0));
54//!             cell.set(cell.get() + 1);
55//!         });
56//!     }
57//! });
58//!
59//! // Once all threads are done, collect the counter values and return the
60//! // sum of all thread-local counter values.
61//! let total = tls.into_iter().fold(0, |x, y| x + y.get());
62//! assert_eq!(total, 5);
63//! ```
64
65#![warn(missing_docs)]
66#![warn(clippy::undocumented_unsafe_blocks)]
67#![warn(unsafe_op_in_unsafe_fn)]
68#![cfg_attr(feature = "nightly", feature(thread_local))]
69
70mod cached;
71mod thread_id;
72
73#[allow(deprecated)]
74pub use cached::{CachedIntoIter, CachedIterMut, CachedThreadLocal};
75
76use std::cell::UnsafeCell;
77use std::fmt;
78use std::iter::FusedIterator;
79use std::mem::MaybeUninit;
80use std::panic::UnwindSafe;
81use std::ptr;
82use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering};
83use thread_id::Thread;
84
85/// The total number of buckets stored in each thread local.
86/// All buckets combined can hold up to `usize::MAX - 1` entries.
87const BUCKETS: usize = (usize::BITS - 1) as usize;
88
89/// Thread-local variable wrapper
90///
91/// See the [module-level documentation](index.html) for more.
92pub struct ThreadLocal<T: Send> {
93    /// The buckets in the thread local. The nth bucket contains `2^n`
94    /// elements. Each bucket is lazily allocated.
95    buckets: [AtomicPtr<Entry<T>>; BUCKETS],
96
97    /// The number of values in the thread local. This can be less than the real number of values,
98    /// but is never more.
99    values: AtomicUsize,
100}
101
102struct Entry<T> {
103    present: AtomicBool,
104    value: UnsafeCell<MaybeUninit<T>>,
105}
106
107impl<T> Entry<T> {
108    fn get_value_cell(&self) -> Option<&UnsafeCell<MaybeUninit<T>>> {
109        self.present.load(Ordering::Acquire).then_some(&self.value)
110    }
111
112    /// # Safety
113    /// The caller must guarantee that there are no concurent mutable accesses into
114    /// this entry's value.
115    unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
116        self.get_value_cell()
117            // SAFETY: The caller guarantees that there are no concurrent mutable
118            // accesses into this value.
119            .map(|cell| unsafe { (&*cell.get()).assume_init_ref() })
120    }
121}
122
123impl<T> Drop for Entry<T> {
124    fn drop(&mut self) {
125        if *self.present.get_mut() {
126            // SAFETY:
127            //  * If `present` is true, then the value was properly initalized.
128            //    and never dropped before.
129            //  * The value is embedded within an `Entry<T>` so the produced
130            //    pointer must be properly aligned and non-null, even if T is
131            //    a ZST.
132            unsafe {
133                MaybeUninit::assume_init_drop(&mut *self.value.get());
134            }
135        }
136    }
137}
138
139// SAFETY: ThreadLocal is always Sync, even if T isn't
140unsafe impl<T: Send> Sync for ThreadLocal<T> {}
141
142impl<T: Send> Default for ThreadLocal<T> {
143    fn default() -> ThreadLocal<T> {
144        ThreadLocal::new()
145    }
146}
147
148impl<T: Send> Drop for ThreadLocal<T> {
149    fn drop(&mut self) {
150        // Free each non-null bucket
151        for (i, bucket) in self.buckets.iter_mut().enumerate() {
152            let bucket_ptr = *bucket.get_mut();
153
154            let this_bucket_size = 1 << i;
155
156            if bucket_ptr.is_null() {
157                continue;
158            }
159
160            // SAFETY: All buckets are allocated from `allocate_bucket`.
161            unsafe { deallocate_bucket(bucket_ptr, this_bucket_size) };
162        }
163    }
164}
165
166impl<T: Send> ThreadLocal<T> {
167    #[allow(clippy::declare_interior_mutable_const)]
168    const NULL_BUCKET: AtomicPtr<Entry<T>> = AtomicPtr::new(ptr::null_mut());
169
170    /// Creates a new empty `ThreadLocal`.
171    pub const fn new() -> ThreadLocal<T> {
172        Self {
173            buckets: [Self::NULL_BUCKET; BUCKETS],
174            values: AtomicUsize::new(0),
175        }
176    }
177
178    /// Creates a new `ThreadLocal` with an initial capacity. If less than the capacity threads
179    /// access the thread local it will never reallocate. The capacity may be rounded up to the
180    /// nearest power of two.
181    pub fn with_capacity(capacity: usize) -> ThreadLocal<T> {
182        let allocated_buckets = (usize::BITS - capacity.leading_zeros()) as usize;
183
184        let mut buckets = [Self::NULL_BUCKET; BUCKETS];
185        for (i, bucket) in buckets[..allocated_buckets].iter_mut().enumerate() {
186            *bucket.get_mut() = allocate_bucket::<T>(1 << i);
187        }
188
189        Self {
190            buckets,
191            values: AtomicUsize::new(0),
192        }
193    }
194
195    /// Returns the element for the current thread, if it exists.
196    pub fn get(&self) -> Option<&T> {
197        thread_id::try_get().and_then(|id| self.get_inner(id))
198    }
199
200    /// Returns the element for the current thread, or creates it if it doesn't
201    /// exist.
202    pub fn get_or<F>(&self, create: F) -> &T
203    where
204        F: FnOnce() -> T,
205    {
206        let result = self.get_or_try(|| Ok::<T, ()>(create()));
207        // SAFETY: The provided closure will never return an Err instance.
208        unsafe { result.unwrap_unchecked() }
209    }
210
211    /// Returns the element for the current thread, or creates it if it doesn't
212    /// exist. If `create` fails, that error is returned and no element is
213    /// added.
214    pub fn get_or_try<F, E>(&self, create: F) -> Result<&T, E>
215    where
216        F: FnOnce() -> Result<T, E>,
217    {
218        let thread = thread_id::get();
219        if let Some(val) = self.get_inner(thread) {
220            return Ok(val);
221        }
222
223        Ok(self.insert(thread, create()?))
224    }
225
226    fn get_inner(&self, thread: Thread) -> Option<&T> {
227        let bucket_ptr = self.get_bucket(thread).load(Ordering::Acquire);
228        if bucket_ptr.is_null() {
229            return None;
230        }
231        // SAFETY:
232        // - Any allocation larger than isize::MAX bytes would fail to
233        //   allocate and thus the `bucket` pointer will be null, it thus must
234        //   be safe to that offset and create a mutable borrow from it.
235        // - This function has immutable access to the `ThreadLocal` and its contents.
236        //   so there should not be concurrent mutable accesses into the same entry.
237        // - `thread.index` is guaranteed to be in bounds within the selected bucket.
238        let entry = unsafe { &*bucket_ptr.add(thread.index) };
239        // SAFETY: This function has immutable access to the `ThreadLocal` and its contents.
240        // so there should not be concurrent mutable accesses into the same entry.
241        unsafe { entry.as_ref() }
242    }
243
244    #[cold]
245    fn insert(&self, thread: Thread, data: T) -> &T {
246        let bucket_atomic_ptr = self.get_bucket(thread);
247        let bucket_ptr: *const _ = bucket_atomic_ptr.load(Ordering::Acquire);
248
249        // If the bucket doesn't already exist, we need to allocate it
250        let bucket_ptr = if bucket_ptr.is_null() {
251            let new_bucket = allocate_bucket(thread.bucket_size());
252
253            match bucket_atomic_ptr.compare_exchange(
254                ptr::null_mut(),
255                new_bucket,
256                Ordering::AcqRel,
257                Ordering::Acquire,
258            ) {
259                Ok(_) => new_bucket,
260                // If the bucket value changed (from null), that means
261                // another thread stored a new bucket before we could,
262                // and we can free our bucket and use that one instead
263                Err(bucket_ptr) => {
264                    // SAFETY: This bucket was just allocated from the call
265                    // allocate_bucket above, and using the same bucket size.
266                    unsafe { deallocate_bucket(new_bucket, thread.bucket_size()) }
267                    bucket_ptr
268                }
269            }
270        } else {
271            bucket_ptr
272        };
273
274        // Insert the new element into the bucket
275        // SAFETY:
276        // - Any allocation larger than isize::MAX bytes would fail to
277        //   allocate and thus the `bucket` pointer will be null, it thus must
278        //   be safe to that offset and create a mutable borrow from it.
279        // - This function has immutable access to the `ThreadLocal` and its contents.
280        //   so there should not be concurrent mutable accesses into the same entry.
281        // - `thread.index` is guaranteed to be in bounds within the selected bucket.
282        let entry = unsafe { &*bucket_ptr.add(thread.index) };
283        // If `create` reentrantly called `get_or`/`get_or_try` on this same
284        // `ThreadLocal` from this thread, the slot is already initialized. Return
285        // the existing value and drop the one we just created, instead of
286        // overwriting it. Overwriting would leak the old value, double-count
287        // `self.values` (causing out-of-bounds iteration in `RawIter::next_mut`),
288        // and invalidate references handed out by the reentrant call.
289        // SAFETY: This function has `&self`, so there are no concurrent mutable
290        // accesses into this entry (this thread's slot is only written by this thread).
291        if let Some(existing) = unsafe { entry.as_ref() } {
292            return existing;
293        }
294        let value_ptr = entry.value.get();
295        // SAFETY: No concurrent read accesses are possible as this value has not
296        // been initialized until now, and no data races are possible since only
297        // the local thread can access this value. The target location of the pointer
298        // is valid since it came from the UnsafeCell and a valid initialized value
299        // of type `T` is being written into the cell.
300        let data_ref = &*unsafe { &mut *value_ptr }.write(data);
301        entry.present.store(true, Ordering::Release);
302
303        self.values.fetch_add(1, Ordering::Release);
304
305        data_ref
306    }
307
308    #[inline]
309    fn get_bucket(&self, thread: Thread) -> &AtomicPtr<Entry<T>> {
310        // SAFETY: Thread::bucket can never be BUCKETS or larger, and thus must be a valid offset.
311        unsafe { self.buckets.get_unchecked(thread.bucket) }
312    }
313
314    /// Returns an iterator over the local values of all threads in unspecified
315    /// order.
316    ///
317    /// This call can be done safely, as `T` is required to implement [`Sync`].
318    pub fn iter(&self) -> Iter<'_, T>
319    where
320        T: Sync,
321    {
322        Iter {
323            thread_local: self,
324            raw: RawIter::new(),
325        }
326    }
327
328    /// Returns a mutable iterator over the local values of all threads in
329    /// unspecified order.
330    ///
331    /// Since this call borrows the `ThreadLocal` mutably, this operation can
332    /// be done safely---the mutable borrow statically guarantees no other
333    /// threads are currently accessing their associated values.
334    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
335        IterMut {
336            thread_local: self,
337            raw: RawIter::new(),
338        }
339    }
340
341    /// Removes all thread-specific values from the `ThreadLocal`, effectively
342    /// resetting it to its original state.
343    ///
344    /// Since this call borrows the `ThreadLocal` mutably, this operation can
345    /// be done safely---the mutable borrow statically guarantees no other
346    /// threads are currently accessing their associated values.
347    pub fn clear(&mut self) {
348        *self = ThreadLocal::new();
349    }
350}
351
352impl<T: Send> IntoIterator for ThreadLocal<T> {
353    type Item = T;
354    type IntoIter = IntoIter<T>;
355
356    fn into_iter(self) -> IntoIter<T> {
357        IntoIter {
358            thread_local: self,
359            raw: RawIter::new(),
360        }
361    }
362}
363
364impl<'a, T: Send + Sync> IntoIterator for &'a ThreadLocal<T> {
365    type Item = &'a T;
366    type IntoIter = Iter<'a, T>;
367
368    fn into_iter(self) -> Self::IntoIter {
369        self.iter()
370    }
371}
372
373impl<'a, T: Send> IntoIterator for &'a mut ThreadLocal<T> {
374    type Item = &'a mut T;
375    type IntoIter = IterMut<'a, T>;
376
377    fn into_iter(self) -> IterMut<'a, T> {
378        self.iter_mut()
379    }
380}
381
382impl<T: Send + Default> ThreadLocal<T> {
383    /// Returns the element for the current thread, or creates a default one if
384    /// it doesn't exist.
385    pub fn get_or_default(&self) -> &T {
386        self.get_or(Default::default)
387    }
388}
389
390impl<T: Send + fmt::Debug> fmt::Debug for ThreadLocal<T> {
391    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
392        write!(f, "ThreadLocal {{ local_data: {:?} }}", self.get())
393    }
394}
395
396impl<T: Send + UnwindSafe> UnwindSafe for ThreadLocal<T> {}
397
398#[derive(Debug)]
399struct RawIter {
400    yielded: usize,
401    bucket: usize,
402    bucket_size: usize,
403    index: usize,
404}
405
406impl RawIter {
407    #[inline]
408    fn new() -> Self {
409        Self {
410            yielded: 0,
411            bucket: 0,
412            bucket_size: 1,
413            index: 0,
414        }
415    }
416
417    fn next<'a, T: Send + Sync>(&mut self, thread_local: &'a ThreadLocal<T>) -> Option<&'a T> {
418        while let Some(bucket) = thread_local.buckets.get(self.bucket) {
419            let bucket = bucket.load(Ordering::Acquire);
420
421            if !bucket.is_null() {
422                while self.index < self.bucket_size {
423                    // SAFETY:
424                    // - Any allocation larger than isize::MAX bytes would fail to
425                    //   allocate and thus the `bucket` pointer will be null, it thus must
426                    //   be safe to that offset and create a mutable borrow from it.
427                    // - This function has immutable access to the `ThreadLocal` and its contents.
428                    //   so there should not be concurrent mutable accesses into the same entry.
429                    // - `thread.index` is guaranteed to be in bounds within the selected bucket.
430                    let entry = unsafe { &*bucket.add(self.index) };
431                    self.index += 1;
432                    // SAFETY: As Iter has a read-only borrow on the ThreadLocal,
433                    // no mutable borrows on the values stored inside can exist at
434                    // the same time.
435                    //
436                    // The above present check is properly synchronized and ensures
437                    // that the value has been properly initialized.
438                    if let Some(value) = unsafe { entry.as_ref() } {
439                        self.yielded += 1;
440                        return Some(value);
441                    }
442                }
443            }
444
445            self.next_bucket();
446        }
447        None
448    }
449
450    fn next_mut<'a, T: Send>(
451        &mut self,
452        thread_local: &'a mut ThreadLocal<T>,
453    ) -> Option<&'a mut Entry<T>> {
454        if *thread_local.values.get_mut() == self.yielded {
455            return None;
456        }
457
458        loop {
459            // SAFETY: The above if check will evaluate to true before self.bucket grows
460            // large enough to be bigger than BUCKETS, thus the result of get_unchecked_mut
461            // must be valid for all possible values of self.bucket.
462            let bucket = unsafe { thread_local.buckets.get_unchecked_mut(self.bucket) };
463            let bucket = *bucket.get_mut();
464
465            if !bucket.is_null() {
466                while self.index < self.bucket_size {
467                    // SAFETY: Any allocation larger than isize::MAX bytes would fail to
468                    // allocate and thus the `bucket` pointer will be null, it thus must
469                    // be safe to that offset and create a mutable borrow from it.
470                    //
471                    // IterMut and IntoIter both have exclusive access to the
472                    // `ThreadLocal` and its contents, so there should not be concurrent
473                    // immutable accesses into the same entry.
474                    let entry = unsafe { &mut *bucket.add(self.index) };
475                    self.index += 1;
476                    if *entry.present.get_mut() {
477                        self.yielded += 1;
478                        return Some(entry);
479                    }
480                }
481            }
482
483            self.next_bucket();
484        }
485    }
486
487    #[inline]
488    fn next_bucket(&mut self) {
489        self.bucket_size <<= 1;
490        self.bucket += 1;
491        self.index = 0;
492    }
493
494    fn size_hint<T: Send>(&self, thread_local: &ThreadLocal<T>) -> (usize, Option<usize>) {
495        let total = thread_local.values.load(Ordering::Relaxed);
496
497        // NOTE: `saturating_sub` is required here to avoid integer underflow during
498        // concurrent insertion and iteration. The shortest dangerous interleaving is:
499        //
500        // - Thread A inserts, pausing after `present = true` but *before* `values = 1`
501        // - Thread B iterates, sees `present = true`, and sets `yielded = 1`
502        // - Thread B calls `size_hint` and sees `values = 0` and `yielded = 1`
503        (total.saturating_sub(self.yielded), None)
504    }
505
506    fn size_hint_frozen<T: Send>(&self, thread_local: &ThreadLocal<T>) -> (usize, Option<usize>) {
507        let total = thread_local.values.load(Ordering::Relaxed);
508
509        // NOTE: this method assumes no concurrent insertion to `thread_local`,
510        // so this subtraction cannot underflow as in `size_hint` above.
511        let remaining = total - self.yielded;
512        (remaining, Some(remaining))
513    }
514}
515
516/// Iterator over the contents of a `ThreadLocal`.
517#[derive(Debug)]
518pub struct Iter<'a, T: Send + Sync> {
519    thread_local: &'a ThreadLocal<T>,
520    raw: RawIter,
521}
522
523impl<'a, T: Send + Sync> Iterator for Iter<'a, T> {
524    type Item = &'a T;
525
526    fn next(&mut self) -> Option<Self::Item> {
527        self.raw.next(self.thread_local)
528    }
529
530    fn size_hint(&self) -> (usize, Option<usize>) {
531        self.raw.size_hint(self.thread_local)
532    }
533}
534
535impl<T: Send + Sync> FusedIterator for Iter<'_, T> {}
536
537/// Mutable iterator over the contents of a `ThreadLocal`.
538pub struct IterMut<'a, T: Send> {
539    thread_local: &'a mut ThreadLocal<T>,
540    raw: RawIter,
541}
542
543impl<'a, T: Send> Iterator for IterMut<'a, T> {
544    type Item = &'a mut T;
545
546    fn next(&mut self) -> Option<&'a mut T> {
547        self.raw
548            .next_mut(self.thread_local)
549            // SAFETY: IterMut has exclusive access to the underlying ThreadLocal
550            // and if RawIter::next_mut returns an entry, it's guaranteed to have
551            // been initialized.
552            .map(|entry| unsafe { (&mut *entry.value.get()).assume_init_mut() })
553    }
554
555    fn size_hint(&self) -> (usize, Option<usize>) {
556        self.raw.size_hint_frozen(self.thread_local)
557    }
558}
559
560impl<T: Send> ExactSizeIterator for IterMut<'_, T> {}
561impl<T: Send> FusedIterator for IterMut<'_, T> {}
562
563// Manual impl so we don't call Debug on the ThreadLocal, as doing so would create a reference to
564// this thread's value that potentially aliases with a mutable reference we have given out.
565impl<'a, T: Send + fmt::Debug> fmt::Debug for IterMut<'a, T> {
566    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567        f.debug_struct("IterMut").field("raw", &self.raw).finish()
568    }
569}
570
571/// An iterator that moves out of a `ThreadLocal`.
572#[derive(Debug)]
573pub struct IntoIter<T: Send> {
574    thread_local: ThreadLocal<T>,
575    raw: RawIter,
576}
577
578impl<T: Send> Iterator for IntoIter<T> {
579    type Item = T;
580
581    fn next(&mut self) -> Option<T> {
582        self.raw.next_mut(&mut self.thread_local).map(|entry| {
583            *entry.present.get_mut() = false;
584            // SAFETY: IntoIter owns the ThreadLocal and has exclusive access to it
585            // and the values stored within.
586            let cell = unsafe { &mut *entry.value.get() };
587            let old_value = std::mem::replace(cell, MaybeUninit::uninit());
588            // SAFETY: If RawIter returned a non-None result, it means this cell was
589            // previously populated and thus has been initialized.
590            unsafe { old_value.assume_init() }
591        })
592    }
593
594    fn size_hint(&self) -> (usize, Option<usize>) {
595        self.raw.size_hint_frozen(&self.thread_local)
596    }
597}
598
599impl<T: Send> ExactSizeIterator for IntoIter<T> {}
600impl<T: Send> FusedIterator for IntoIter<T> {}
601
602fn allocate_bucket<T>(size: usize) -> *mut Entry<T> {
603    Box::into_raw(
604        (0..size)
605            .map(|_| Entry::<T> {
606                present: AtomicBool::new(false),
607                value: UnsafeCell::new(MaybeUninit::uninit()),
608            })
609            .collect(),
610    ) as *mut _
611}
612
613/// # Safety
614/// The caller must ensure that `bucket` was allocated from [allocate_bucket]
615/// with the same `size` parameter.
616unsafe fn deallocate_bucket<T>(bucket: *mut Entry<T>, size: usize) {
617    // SAFETY: The caller ensures that the bucket pointer and size come from a
618    // corresponding call to `allocate_bucket` with an identical size, and thus:
619    //  * `bucket` must not be null.
620    //  * `size` must match the same length as when the bucket was allocated.
621    //  * `bucket` points to a slice of properly initialized `Entry<T>`.
622    //  * The total size of the allocation cannot be larger than isize::MAX
623    //    bytes or the allocation would have failed and panicked.
624    let slice = unsafe { std::slice::from_raw_parts_mut(bucket, size) };
625    // SAFETY: It's the caller's responsibliity that the bucket was created
626    // from `allocate_bucket`, which ensures that it was allocated using the
627    // global allocator.
628    drop(unsafe { Box::from_raw(slice) });
629}
630
631#[cfg(test)]
632mod tests {
633    use super::*;
634
635    use std::cell::RefCell;
636    use std::sync::atomic::AtomicUsize;
637    use std::sync::atomic::Ordering::Relaxed;
638    use std::sync::Arc;
639    use std::thread;
640
641    fn make_create() -> Arc<dyn Fn() -> usize + Send + Sync> {
642        let count = AtomicUsize::new(0);
643        Arc::new(move || count.fetch_add(1, Relaxed))
644    }
645
646    #[test]
647    fn same_thread() {
648        let create = make_create();
649        let mut tls = ThreadLocal::new();
650        assert_eq!(None, tls.get());
651        assert_eq!("ThreadLocal { local_data: None }", format!("{:?}", &tls));
652        assert_eq!(0, *tls.get_or(|| create()));
653        assert_eq!(Some(&0), tls.get());
654        assert_eq!(0, *tls.get_or(|| create()));
655        assert_eq!(Some(&0), tls.get());
656        assert_eq!(0, *tls.get_or(|| create()));
657        assert_eq!(Some(&0), tls.get());
658        assert_eq!("ThreadLocal { local_data: Some(0) }", format!("{:?}", &tls));
659        tls.clear();
660        assert_eq!(None, tls.get());
661    }
662
663    #[test]
664    fn reentrant_get_or() {
665        let tls: ThreadLocal<Box<u32>> = ThreadLocal::new();
666        let outer = tls.get_or(|| {
667            let inner = tls.get_or(|| Box::new(1));
668            assert_eq!(**inner, 1);
669            Box::new(2)
670        });
671        // The reentrant call already populated the slot, so the outer
672        // value is discarded and the existing value is returned.
673        assert_eq!(**outer, 1);
674        // Pre-fix, `values` was double-counted and this iterated out of
675        // bounds (UB caught by Miri). Post-fix exactly one value is present.
676        let collected: Vec<u32> = tls.into_iter().map(|b| *b).collect();
677        assert_eq!(collected, vec![1]);
678    }
679
680    #[test]
681    fn different_thread() {
682        let create = make_create();
683        let tls = Arc::new(ThreadLocal::new());
684        assert_eq!(None, tls.get());
685        assert_eq!(0, *tls.get_or(|| create()));
686        assert_eq!(Some(&0), tls.get());
687
688        let tls2 = tls.clone();
689        let create2 = create.clone();
690        thread::spawn(move || {
691            assert_eq!(None, tls2.get());
692            assert_eq!(1, *tls2.get_or(|| create2()));
693            assert_eq!(Some(&1), tls2.get());
694        })
695        .join()
696        .unwrap();
697
698        assert_eq!(Some(&0), tls.get());
699        assert_eq!(0, *tls.get_or(|| create()));
700    }
701
702    #[test]
703    fn iter() {
704        let tls = Arc::new(ThreadLocal::new());
705        tls.get_or(|| Box::new(1));
706
707        let tls2 = tls.clone();
708        thread::spawn(move || {
709            tls2.get_or(|| Box::new(2));
710            let tls3 = tls2.clone();
711            thread::spawn(move || {
712                tls3.get_or(|| Box::new(3));
713            })
714            .join()
715            .unwrap();
716            drop(tls2);
717        })
718        .join()
719        .unwrap();
720
721        let mut tls = Arc::try_unwrap(tls).unwrap();
722
723        let mut v = tls.iter().map(|x| **x).collect::<Vec<i32>>();
724        v.sort_unstable();
725        assert_eq!(vec![1, 2, 3], v);
726
727        let mut v = tls.iter_mut().map(|x| **x).collect::<Vec<i32>>();
728        v.sort_unstable();
729        assert_eq!(vec![1, 2, 3], v);
730
731        let mut v = tls.into_iter().map(|x| *x).collect::<Vec<i32>>();
732        v.sort_unstable();
733        assert_eq!(vec![1, 2, 3], v);
734    }
735
736    #[test]
737    fn miri_iter_soundness_check() {
738        let tls = Arc::new(ThreadLocal::new());
739        let _local = tls.get_or(|| Box::new(1));
740
741        let tls2 = tls.clone();
742        let join_1 = thread::spawn(move || {
743            let _tls = tls2.get_or(|| Box::new(2));
744            let iter = tls2.iter();
745            for item in iter {
746                println!("{:?}", item);
747            }
748        });
749
750        let iter = tls.iter();
751        for item in iter {
752            println!("{:?}", item);
753        }
754
755        join_1.join().ok();
756    }
757
758    #[test]
759    fn test_drop() {
760        let local = ThreadLocal::new();
761        struct Dropped(Arc<AtomicUsize>);
762        impl Drop for Dropped {
763            fn drop(&mut self) {
764                self.0.fetch_add(1, Relaxed);
765            }
766        }
767
768        let dropped = Arc::new(AtomicUsize::new(0));
769        local.get_or(|| Dropped(dropped.clone()));
770        assert_eq!(dropped.load(Relaxed), 0);
771        drop(local);
772        assert_eq!(dropped.load(Relaxed), 1);
773    }
774
775    #[test]
776    fn test_earlyreturn_buckets() {
777        struct Dropped(Arc<AtomicUsize>);
778        impl Drop for Dropped {
779            fn drop(&mut self) {
780                self.0.fetch_add(1, Relaxed);
781            }
782        }
783        let dropped = Arc::new(AtomicUsize::new(0));
784
785        // We use a high `id` here to guarantee that a lazily allocated bucket somewhere in the middle is used.
786        // Neither iteration nor `Drop` must early-return on `null` buckets that are used for lower `buckets`.
787        let thread = Thread::new(1234);
788        assert!(thread.bucket > 1);
789
790        let mut local = ThreadLocal::new();
791        local.insert(thread, Dropped(dropped.clone()));
792
793        let item = local.iter().next().unwrap();
794        assert_eq!(item.0.load(Relaxed), 0);
795        let item = local.iter_mut().next().unwrap();
796        assert_eq!(item.0.load(Relaxed), 0);
797        drop(local);
798        assert_eq!(dropped.load(Relaxed), 1);
799    }
800
801    #[test]
802    fn is_sync() {
803        fn foo<T: Sync>() {}
804        foo::<ThreadLocal<String>>();
805        foo::<ThreadLocal<RefCell<String>>>();
806    }
807}