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
//! ### Problem
//!
//! lets consider following code:
//!
//! ```
//! use std::sync::Once;
//!
//! 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 mut VALUE: Option<String> = None;
//!     static INIT: Once = Once::new();
//!
//!     unsafe{
//!         INIT.call_once(||{
//!             VALUE = Some(T::string());
//!         });
//!         VALUE.as_ref().unwrap().as_str()
//!     }
//! }
//!
//! // 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 std::sync::Once;
//!
//! 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 mut VALUE: Option<StaticTypeMap<String>> = None;
//!     static INIT: Once = Once::new();
//!
//!     let map = unsafe{
//!         INIT.call_once(||{
//!             VALUE = Some(StaticTypeMap::new());
//!         });
//!         VALUE.as_ref().unwrap()
//!     };
//!
//!     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<'a>(&'a str);
//! impl<'a> X for B<'a>{
//!     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::sync::RwLock;
use std::any::TypeId;
use std::collections::HashMap;


pub struct StaticTypeMap<T: 'static>{
    map: RwLock<HashMap<TypeId, &'static T>>
}

pub struct Entry<Type: 'static>{
    _marker: std::marker::PhantomData<Type>
}

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 reader = self.map.read().unwrap();
            if let Some(ref reference) = reader.get(&TypeId::of::<Type>()){
                return &reference;
            }
        }
        // otherwise construct new value and put inside map
        // allocate value on heap
        let boxed = Box::new(f());
        // leak it's value until program is terminated
        let reference: &'static T = Box::leak(boxed);

        let mut writer = self.map.write().unwrap();
        let old = writer.insert(TypeId::of::<Type>(), reference);
        if old.is_some(){
            panic!("StaticTypeMap value was reinitialized. This is a bug.")
        }
        reference
    }
}