1 // Copyright 2018 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.
11 use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
15 use num::NonZeroUsize;
16 use self::sync_bitset::*;
18 #[cfg(target_pointer_width="64")]
19 const USIZE_BITS: usize = 64;
20 const TLS_KEYS: usize = 128; // Same as POSIX minimum
21 const TLS_KEYS_BITSET_SIZE: usize = (TLS_KEYS + (USIZE_BITS - 1)) / USIZE_BITS;
23 static TLS_KEY_IN_USE: SyncBitset = SYNC_BITSET_INIT;
25 ((* $($exp:tt)*) $($val:tt)*) => (dup!( ($($exp)*) $($val)* $($val)* ));
26 (() $($val:tt)*) => ([$($val),*])
28 static TLS_DESTRUCTOR: [AtomicUsize; TLS_KEYS] = dup!((* * * * * * *) ATOMIC_USIZE_INIT);
31 fn get_tls_ptr() -> *const u8;
32 fn set_tls_ptr(tls: *const u8);
35 #[derive(Copy, Clone)]
37 pub struct Key(NonZeroUsize);
40 fn to_index(self) -> usize {
44 fn from_index(index: usize) -> Self {
45 Key(NonZeroUsize::new(index + 1).unwrap())
48 pub fn as_usize(self) -> usize {
52 pub fn from_usize(index: usize) -> Self {
53 Key(NonZeroUsize::new(index).unwrap())
59 data: [Cell<*mut u8>; TLS_KEYS]
62 pub struct ActiveTls<'a> {
66 impl<'a> Drop for ActiveTls<'a> {
68 let value_with_destructor = |key: usize| {
69 let ptr = TLS_DESTRUCTOR[key].load(Ordering::Relaxed);
70 unsafe { mem::transmute::<_,Option<unsafe extern fn(*mut u8)>>(ptr) }
71 .map(|dtor| (&self.tls.data[key], dtor))
74 let mut any_non_null_dtor = true;
75 while any_non_null_dtor {
76 any_non_null_dtor = false;
77 for (value, dtor) in TLS_KEY_IN_USE.iter().filter_map(&value_with_destructor) {
78 let value = value.replace(ptr::null_mut());
79 if value != ptr::null_mut() {
80 any_non_null_dtor = true;
81 unsafe { dtor(value) }
90 Tls { data: dup!((* * * * * * *) (Cell::new(ptr::null_mut()))) }
93 pub unsafe fn activate(&self) -> ActiveTls {
94 set_tls_ptr(self as *const Tls as _);
95 ActiveTls { tls: self }
99 pub unsafe fn activate_persistent(self: Box<Self>) {
100 set_tls_ptr((&*self) as *const Tls as _);
104 unsafe fn current<'a>() -> &'a Tls {
105 &*(get_tls_ptr() as *const Tls)
108 pub fn create(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
109 let index = TLS_KEY_IN_USE.set().expect("TLS limit exceeded");
110 TLS_DESTRUCTOR[index].store(dtor.map_or(0, |f| f as usize), Ordering::Relaxed);
111 Key::from_index(index)
114 pub fn set(key: Key, value: *mut u8) {
115 let index = key.to_index();
116 assert!(TLS_KEY_IN_USE.get(index));
117 unsafe { Self::current() }.data[index].set(value);
120 pub fn get(key: Key) -> *mut u8 {
121 let index = key.to_index();
122 assert!(TLS_KEY_IN_USE.get(index));
123 unsafe { Self::current() }.data[index].get()
126 pub fn destroy(key: Key) {
127 TLS_KEY_IN_USE.clear(key.to_index());
132 use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
133 use iter::{Enumerate, Peekable};
135 use super::{TLS_KEYS_BITSET_SIZE, USIZE_BITS};
137 /// A bitset that can be used synchronously.
138 pub(super) struct SyncBitset([AtomicUsize; TLS_KEYS_BITSET_SIZE]);
140 pub(super) const SYNC_BITSET_INIT: SyncBitset =
141 SyncBitset([ATOMIC_USIZE_INIT, ATOMIC_USIZE_INIT]);
144 pub fn get(&self, index: usize) -> bool {
145 let (hi, lo) = Self::split(index);
146 (self.0[hi].load(Ordering::Relaxed) & lo) != 0
150 pub fn iter(&self) -> SyncBitsetIter {
152 iter: self.0.iter().enumerate().peekable(),
157 pub fn clear(&self, index: usize) {
158 let (hi, lo) = Self::split(index);
159 self.0[hi].fetch_and(!lo, Ordering::Relaxed);
162 /// Set any unset bit. Not atomic. Returns `None` if all bits were
163 /// observed to be set.
164 pub fn set(&self) -> Option<usize> {
165 'elems: for (idx, elem) in self.0.iter().enumerate() {
166 let mut current = elem.load(Ordering::Relaxed);
171 let trailing_ones = (!current).trailing_zeros() as usize;
172 match elem.compare_exchange(
174 current | (1 << trailing_ones),
178 Ok(_) => return Some(idx * USIZE_BITS + trailing_ones),
179 Err(previous) => current = previous,
186 fn split(index: usize) -> (usize, usize) {
187 (index / USIZE_BITS, 1 << (index % USIZE_BITS))
191 pub(super) struct SyncBitsetIter<'a> {
192 iter: Peekable<Enumerate<Iter<'a, AtomicUsize>>>,
196 impl<'a> Iterator for SyncBitsetIter<'a> {
199 fn next(&mut self) -> Option<usize> {
200 self.iter.peek().cloned().and_then(|(idx, elem)| {
201 let elem = elem.load(Ordering::Relaxed);
202 let low_mask = (1 << self.elem_idx) - 1;
203 let next = elem & !low_mask;
204 let next_idx = next.trailing_zeros() as usize;
205 self.elem_idx = next_idx + 1;
206 if self.elem_idx >= 64 {
212 _ => Some(idx * USIZE_BITS + next_idx),
222 fn test_data(bitset: [usize; 2], bit_indices: &[usize]) {
223 let set = SyncBitset([AtomicUsize::new(bitset[0]), AtomicUsize::new(bitset[1])]);
224 assert_eq!(set.iter().collect::<Vec<_>>(), bit_indices);
225 for &i in bit_indices {
232 test_data([0b0110_1001, 0], &[0, 3, 5, 6]);
233 test_data([0x8000_0000_0000_0000, 0x8000_0000_0000_0001], &[63, 64, 127]);
234 test_data([0, 0], &[]);
239 let set = SYNC_BITSET_INIT;
240 let key = set.set().unwrap();
241 assert!(set.get(key));
243 assert!(!set.get(key));