1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
//! ### Problem //! //! lets consider following code: //! //! ``` //! use once_cell::sync::OnceCell; //! //! trait X{ //! fn string() -> String; //! } //! //! // having to recompute string() over and over might be expensive (not in this example, but still) //! // so we use lazy initialization //! fn generic<T: X>() -> &'static str{ //! static VALUE: OnceCell<String> = OnceCell::new(); //! //! VALUE.get_or_init(||{ //! T::string() //! }) //! } //! //! // And now it can be used like this //! struct A; //! impl X for A{ //! fn string() -> String{ //! "A".to_string() //! } //! } //! //! struct B; //! impl X for B{ //! fn string() -> String{ //! "B".to_string() //! } //! } //! //! fn main(){ //! assert_eq!(generic::<A>(), "A"); //! assert_eq!(generic::<B>(), "A"); // Wait what? //! // Not completely behaviour I was expecting //! // This is due to fact that static variable placed inside of generic function //! // wont be cloned into each version of function, but will be shared //! // Thus second call does not initialize value for B, but takes value //! // initialized in previous call. //! } //! ``` //! //! ### Solution //! This crate was designed to solve this particular problem. //! //! Lets make some changes: //! //! ``` //! use generic_static::StaticTypeMap; //! use once_cell::sync::OnceCell; //! //! trait X{ //! fn string() -> String; //! } //! //! // having to recompute string() over and over might be expensive (not in this example, but still) //! // so we use lazy initialization //! fn generic<T: X + 'static>() -> &'static str{ // T is bound to 'static //! static VALUE: OnceCell<StaticTypeMap<String>> = OnceCell::new(); //! let map = VALUE.get_or_init(|| StaticTypeMap::new()); //! //! map.call_once::<T, _>(||{ //! T::string() //! }) //! } //! //! // And now it can be used like this //! struct A; //! impl X for A{ //! fn string() -> String{ //! "A".to_string() //! } //! } //! //! struct B; //! impl X for B{ //! fn string() -> String{ //! "B".to_string() //! } //! } //! //! fn main(){ //! assert_eq!(generic::<A>(), "A"); //! assert_eq!(generic::<B>(), "B"); //! } //! ``` //! //! ### Drawbacks //! //! Current implementation uses RwLock to make it safe in concurrent //! applications, which will be slightly slower then regular use std::any::TypeId; use std::collections::HashMap; use std::sync::RwLock; use once_cell::sync::OnceCell; pub struct StaticTypeMap<T: 'static> { map: RwLock<HashMap<TypeId, &'static OnceCell<T>>>, } impl<T: 'static> StaticTypeMap<T> { pub fn new() -> Self { Self { map: RwLock::new(HashMap::new()), } } /// Initialize static value corresponding to provided type. /// /// Initialized value will stay on heap until program terminated. /// No drop method will be called. pub fn call_once<Type, Init>(&'static self, f: Init) -> &'static T where Type: 'static, Init: FnOnce() -> T, { // If already initialized, just return stored value let cell = { let reader = self.map.read().unwrap(); reader.get(&TypeId::of::<Type>()).cloned() // Clone reference }; if let Some(cell) = cell { return cell.get_or_init(f); } let cell = { let mut writer = self.map.write().unwrap(); let cell = writer .entry(TypeId::of::<Type>()) .or_insert_with(|| { let boxed = Box::new(OnceCell::new()); Box::leak(boxed) }); *cell }; cell .get_or_init(f) } } impl<T: 'static> Default for StaticTypeMap<T> { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use super::*; #[test] fn deadlock_issue4() { fn map() -> &'static StaticTypeMap<String> { static VALUE: OnceCell<StaticTypeMap<String>> = OnceCell::new(); VALUE.get_or_init(|| StaticTypeMap::new()) } fn get_u32_value() -> &'static str { map().call_once::<u32, _>(|| "u32".to_string()) } let res = map().call_once::<u64, _>(|| format!("{} and", get_u32_value())); assert_eq!(res, "u32 and") } }