Function globals::get

source ·
pub fn get<T>() -> MutexGuard<'static, T>where
    T: 'static + Default + Send + Sync,
Expand description

Get a mutex gaurd handle to globle singleton

Examples found in repository?
src/lib.rs (line 29)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
pub fn get<T>() -> MutexGuard<'static, T>
where
    T: 'static + Default + Send + core::marker::Sync,
{
    {
        let mut globals = GLOBALS_LIST.lock();
        let id = TypeId::of::<T>();
        let p = globals.iter().find(|&r| r.0 == id);
        if let Some(v) = p {
            let m = unsafe { &*(v.1 as *const Mutex<dyn Any + Send + Sync> as *const Mutex<T>) };
            return m.lock();
        }
        let v = Box::new(Mutex::new(T::default()));
        let handle = Box::leak(v);
        globals.push_front((id, handle));
    }
    get()
}