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
use crate::rt::synchronize::Synchronize;
use std::{any::Any, collections::HashMap};

pub(crate) struct Set {
    /// Registered statics.
    statics: Option<HashMap<StaticKeyId, StaticValue>>,
}

#[derive(Eq, PartialEq, Hash, Copy, Clone)]
pub(crate) struct StaticKeyId(usize);

pub(crate) struct StaticValue {
    pub(crate) sync: Synchronize,
    v: Box<dyn Any>,
}

impl Set {
    /// Create an empty statics set.
    pub(crate) fn new() -> Set {
        Set {
            statics: Some(HashMap::new()),
        }
    }

    pub(crate) fn reset(&mut self) {
        assert!(
            self.statics.is_none(),
            "lazy_static was not dropped during execution"
        );
        self.statics = Some(HashMap::new());
    }

    pub(crate) fn drop(&mut self) -> HashMap<StaticKeyId, StaticValue> {
        self.statics
            .take()
            .expect("lazy_statics were dropped twice in one execution")
    }

    pub(crate) fn get_static<T: 'static>(
        &mut self,
        key: &'static crate::lazy_static::Lazy<T>,
    ) -> Option<&mut StaticValue> {
        self.statics
            .as_mut()
            .expect("attempted to access lazy_static during shutdown")
            .get_mut(&StaticKeyId::new(key))
    }

    pub(crate) fn init_static<T: 'static>(
        &mut self,
        key: &'static crate::lazy_static::Lazy<T>,
        value: StaticValue,
    ) -> &mut StaticValue {
        let v = self
            .statics
            .as_mut()
            .expect("attempted to access lazy_static during shutdown")
            .entry(StaticKeyId::new(key));

        if let std::collections::hash_map::Entry::Occupied(_) = v {
            unreachable!("told to init static, but it was already init'd");
        }

        v.or_insert(value)
    }
}

impl StaticKeyId {
    fn new<T>(key: &'static crate::lazy_static::Lazy<T>) -> Self {
        Self(key as *const _ as usize)
    }
}

impl StaticValue {
    pub(crate) fn new<T: 'static>(value: T) -> Self {
        Self {
            sync: Synchronize::new(),
            v: Box::new(value),
        }
    }

    pub(crate) fn get<T: 'static>(&self) -> &T {
        self.v
            .downcast_ref::<T>()
            .expect("lazy value must downcast to expected type")
    }
}