| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
use std::ops::Deref; |
| 15 |
|
| 16 |
#[cfg(not(feature = "integration_test"))] |
| 17 |
pub struct RuntimeLocal<T: 'static> { |
| 18 |
|
| 19 |
#[doc(hidden)] |
| 20 |
pub __data: T, |
| 21 |
} |
| 22 |
|
| 23 |
#[cfg(not(feature = "integration_test"))] |
| 24 |
impl<T> Deref for RuntimeLocal<T> { |
| 25 |
type Target = T; |
| 26 |
|
| 27 |
fn deref(&self) -> &Self::Target { |
| 28 |
&self.__data |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
#[cfg(not(feature = "integration_test"))] |
| 33 |
#[macro_export] |
| 34 |
macro_rules! runtime_local { |
| 35 |
($($(#[$attr:meta])* $vis: vis static $name:ident: $ty: ty = $init: expr;)*) => { |
| 36 |
$($(#[$attr])* $vis static $name: $crate::runtime::RuntimeLocal<$ty> = $crate::runtime::RuntimeLocal { |
| 37 |
__data: $init |
| 38 |
};)* |
| 39 |
}; |
| 40 |
} |
| 41 |
|
| 42 |
#[cfg(feature = "integration_test")] |
| 43 |
pub struct RuntimeLocal<T: 'static> { |
| 44 |
data: parking_lot::RwLock< |
| 45 |
hashbrown::HashMap<tokio::runtime::Id, &'static T, foldhash::fast::FixedState>, |
| 46 |
>, |
| 47 |
init: fn() -> T, |
| 48 |
} |
| 49 |
|
| 50 |
#[cfg(feature = "integration_test")] |
| 51 |
impl<T> RuntimeLocal<T> { |
| 52 |
|
| 53 |
#[doc(hidden)] |
| 54 |
pub const fn __new(init: fn() -> T) -> Self { |
| 55 |
Self { |
| 56 |
data: parking_lot::RwLock::new(hashbrown::HashMap::with_hasher( |
| 57 |
foldhash::fast::FixedState::with_seed(12345678910), |
| 58 |
)), |
| 59 |
init, |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
#[cfg(feature = "integration_test")] |
| 65 |
impl<T> Deref for RuntimeLocal<T> { |
| 66 |
type Target = T; |
| 67 |
fn deref(&self) -> &T { |
| 68 |
let id = tokio::runtime::Handle::current().id(); |
| 69 |
let guard = self.data.read(); |
| 70 |
match guard.get(&id) { |
| 71 |
Some(res) => res, |
| 72 |
None => { |
| 73 |
drop(guard); |
| 74 |
let data = Box::leak(Box::new((self.init)())); |
| 75 |
let mut guard = self.data.write(); |
| 76 |
guard.insert(id, data); |
| 77 |
data |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
#[cfg(feature = "integration_test")] |
| 84 |
#[macro_export] |
| 85 |
macro_rules! runtime_local { |
| 86 |
($($(#[$attr:meta])* $vis: vis static $name:ident: $ty: ty = $init: expr;)*) => { |
| 87 |
$($(#[$attr])* $vis static $name: $crate::runtime::RuntimeLocal<$ty> = $crate::runtime::RuntimeLocal::__new(|| $init);)* |
| 88 |
}; |
| 89 |
} |