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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#![doc = include_str!("../README.md")]

#![cfg_attr(docsrs, feature(doc_cfg))]
use std::{ops::Deref, sync::OnceLock, fmt::{Debug, Display}};


#[cfg_attr(docsrs, doc(cfg(feature = "ctor")))]
#[cfg(feature = "ctor")]
pub use ctor;

#[cfg_attr(docsrs, doc(cfg(feature = "ctor")))]
#[cfg(feature = "ctor")]
#[macro_export]
/// Generate a static with a ctor procedure.
/// 
///```rust
///# use global_static::ctor_static;
///fn spit_a_number() -> i32 { 42 }
///
///ctor_static! {
///    pub MY_NUM: i32 = { 5 };
///    MY_OTHER_NUM: i32 = spit_a_number;
///    pub default DEFAULT_NUM: i32;
///};
///```
///This code will expand to the following:
///```rust
///# use global_static::*;
///# fn spit_a_number() -> i32 { 42 }
///pub static MY_NUM: Global<i32> = Global::new(|| { 5 });
///static MY_OTHER_NUM: Global<i32> = Global::new(spit_a_number);
///pub static DEFAULT_NUM: Global<i32> = Global::default();
///
///#[global_static::ctor::ctor]
///fn _global_init() {
///    MY_NUM.init();
///    MY_OTHER_NUM.init();
///    DEFAULT_NUM.init();
///}
///```
macro_rules! ctor_static {
    () => {};
    ($($body:tt)*) => {
        $crate::ctor_gen_defs!($($body)*);
        #[$crate::ctor::ctor]
        fn _global_init() {
            $crate::ctor_gen_inits!($($body)*);
        }
    };
}

///Internal macro. Do not use.
#[macro_export]
#[doc(hidden)]
macro_rules! ctor_gen_defs {
    () => {};

    ($name:ident: $type: ty = $init:block; $($tail:tt)*) => {
        static $name: $crate::Global<$type> = $crate::Global::new(|| $init);
        $crate::ctor_gen_defs!($($tail)*);
    };
    (pub $name:ident: $type: ty = $init:block; $($tail:tt)*) => {
        pub static $name: $crate::Global<$type> = $crate::Global::new(|| $init);
        $crate::ctor_gen_defs!($($tail)*);
    };

    ($name:ident: $type: ty = $init:expr; $($tail:tt)*) => {
        static $name: $crate::Global<$type> = $crate::Global::new($init);
        $crate::ctor_gen_defs!($($tail)*);
    };
    (pub $name:ident: $type: ty = $init:expr; $($tail:tt)*) => {
        pub static $name: $crate::Global<$type> = $crate::Global::new($init);
        $crate::ctor_gen_defs!($($tail)*);
    };

    (default $name:ident: $type: ty; $($tail:tt)*) => {
        static $name: $crate::Global<$type> = $crate::Global::default();
        $crate::ctor_gen_defs!($($tail)*);
    };
    (pub default $name:ident: $type: ty; $($tail:tt)*) => {
        pub static $name: $crate::Global<$type> = $crate::Global::default();
        $crate::ctor_gen_defs!($($tail)*);
    };

}

///Internal macro. Do not use.
#[macro_export]
#[doc(hidden)]
macro_rules! ctor_gen_inits {
    () => {};
    ($name:ident: $type: ty = $init:block; $($tail:tt)*) => {
        $name.init();
        $crate::ctor_gen_inits!($($tail)*);
    };
    (pub $name:ident: $type: ty = $init:block; $($tail:tt)*) => {
        $name.init();
        $crate::ctor_gen_inits!($($tail)*);
    };

    ($name:ident: $type: ty = $init:expr; $($tail:tt)*) => {
        $name.init();
        $crate::ctor_gen_inits!($($tail)*);
    };
    (pub $name:ident: $type: ty = $init:expr; $($tail:tt)*) => {
        $name.init();
        $crate::ctor_gen_inits!($($tail)*);
    };

    (default $name:ident: $type: ty; $($tail:tt)*) => {
        $name.init();
        $crate::ctor_gen_inits!($($tail)*);
    };
    (pub default $name:ident: $type: ty; $($tail:tt)*) => {
        $name.init();
        $crate::ctor_gen_inits!($($tail)*);
    };
}


///Lazily evaluated static allocation.
pub struct Global<T> {
    f: fn() -> T,
    data: OnceLock<SendPtr<T>>
}

struct SendPtr<T>(pub *const T);
unsafe impl<T> Send for SendPtr<T> {}
unsafe impl<T> Sync for SendPtr<T> {}

impl<T> Deref for SendPtr<T> {
    type Target = *const T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}


impl<T> Global<T> {
    ///Constructs a new global.
    ///Rather than a value, this function takes a closure that produces a value.
    ///```rust
    ///# use global_static::Global;
    ///
    ///static MY_TABLE: Global<Vec<&str>> = Global::new(|| vec!["a", "b", "c"]);
    pub const fn new(f: fn() -> T) -> Self {
        Self { f, data: OnceLock::new() }
    }

    ///Initializes the contents of a global. Does nothing if already initialized.
    pub fn init(&self) {
        if let None = self.data.get() { 
            let _ = unsafe { self.alloc() }; 
        }
    }

    ///Retrieves a reference to the value inside the global without allocating.
    ///This function will return `None` if the global has not been allocated.
    pub fn get(&self) -> Option<&T> {
        self.data.get().map(|ptr| {unsafe { &***ptr }})
    }

    ///Retrieves a reference to the value inside the global without allocating. Calling this function on
    ///an unallocated global is undefined behavior.
    pub unsafe fn get_unchecked(&self) -> &T {
        //lol
        &***self.data.get().unwrap_unchecked()
    } 
    
    ///Caller must ensure cell has not been already allocated
    unsafe fn alloc(&self) -> *const T {
        //box will panic if it cannot allocate
        let ptr = Box::leak(
            Box::new((self.f)())
            ) as *const T;
        self.data.set(SendPtr(ptr)).unwrap_unchecked();
        **self.data.get().unwrap_unchecked()
    }
}

impl<T: Default> Global<T> {
    ///Constructs a new global, using the [`Default`] implementation for `T` as the initializer.
    //cant use trait cus not const
    pub const fn default() -> Self {
        Self::new(T::default)
    } 
}

impl<T> Deref for Global<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match self.data.get() {
            Some(v) => unsafe { &***v },
            None => unsafe { &*self.alloc() },
        }
    }
}

impl<T: Debug> Debug for Global<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.deref())
    }
}
impl<T: Display> Display for Global<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.deref())
    }
}

static TEST: Global<u8> = Global::new(|| 5);

#[cfg(test)]
mod tests {
    use std::ops::Add;

    use super::*;

    #[test]
    fn it_works() {
        assert_eq!(TEST.add(1), 6);
        assert_eq!(*TEST, 5);
    }

    #[test]
    #[cfg(feature = "ctor")]
    fn ctor_test() {
        ctor_static! { 
            THING: u32 = { 5 };
            pub THING2: u32 = { 5 };
        };

        assert_eq!(THING.add(1), 6);
        assert_eq!(*THING, 5);
    } 
}