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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
use crate::Container;
use std::fmt::Debug;
use std::sync::atomic::{AtomicPtr, AtomicU8, Ordering};

#[cfg(feature = "unstable_provide")]
use {
    crate::{InjectionKey, Provider},
    once_cell::sync::Lazy,
    std::sync::Mutex,
};

static CONTAINER: GlobalContainer = GlobalContainer::new();

const UNINITIALIZED: u8 = 0;
const INITIALIZING: u8 = 1;
const INITIALIZED: u8 = 2;

struct GlobalContainer {
    container: AtomicPtr<Container<'static>>,
    state: AtomicU8,
}

impl GlobalContainer {
    const fn new() -> Self {
        Self {
            container: AtomicPtr::new(std::ptr::null_mut()),
            state: AtomicU8::new(UNINITIALIZED),
        }
    }

    fn initialize<F>(&self, init: F) -> Result<(), InitContainerError>
    where
        F: FnOnce(&mut Container<'static>),
    {
        let state = &self.state;

        match state.compare_exchange(
            UNINITIALIZED,
            INITIALIZING,
            Ordering::SeqCst,
            Ordering::SeqCst,
        ) {
            Ok(UNINITIALIZED) => {
                let mut container = Container::new();
                init(&mut container);
                let ptr = Box::into_raw(Box::new(container));

                self.container.store(ptr, Ordering::SeqCst);
                state.store(INITIALIZED, Ordering::SeqCst);
                Ok(())
            }
            Ok(INITIALIZING) => {
                while state.load(Ordering::SeqCst) == INITIALIZING {
                    std::hint::spin_loop();
                }

                Err(InitContainerError(InitContainerErrorKind::Initializing))
            }
            _ => Err(InitContainerError(
                InitContainerErrorKind::AlreadyInitialized,
            )),
        }
    }

    fn get(&self) -> Option<&'static Container<'static>> {
        match self.state.load(Ordering::SeqCst) {
            INITIALIZED => unsafe { Some(&*self.container.load(Ordering::SeqCst)) },
            _ => None,
        }
    }

    // This method should never be exposed, global container should be read-only after initialization
    #[allow(dead_code)]
    fn get_mut(&self) -> Option<&'static mut Container<'static>> {
        match self.state.load(Ordering::SeqCst) {
            INITIALIZED => unsafe { Some(&mut *self.container.load(Ordering::SeqCst)) },
            _ => None,
        }
    }
}

/// Container initialization errors.
pub enum InitContainerErrorKind {
    /// The container was initializing.
    Initializing,
    /// The container was already initialized.
    AlreadyInitialized,
}

/// Error returned when the container initialization failed.
pub struct InitContainerError(InitContainerErrorKind);

impl Debug for InitContainerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            InitContainerErrorKind::Initializing => {
                write!(f, "The container was initializing")
            }
            InitContainerErrorKind::AlreadyInitialized => {
                write!(f, "The container was already initialized")
            }
        }
    }
}

// A provider to be injected by #[provide]
#[doc(hidden)]
#[cfg(feature = "unstable_provide")]
pub struct InjectProvider {
    // The actual provider
    pub provider: Provider<'static>,
    // The key used to inject the provider
    pub key: InjectionKey<'static>,
}

// List of providers to be added to the global container
#[doc(hidden)]
#[cfg(feature = "unstable_provide")]
pub static PROVIDERS: Lazy<Mutex<Option<Vec<InjectProvider>>>> =
    Lazy::new(|| Mutex::new(Some(vec![])));

/// Initializes the global [`Container`].
#[cold]
pub fn init_container<F>(f: F) -> Result<(), InitContainerError>
where
    F: FnOnce(&mut Container<'static>),
{
    match CONTAINER.initialize(f) {
        Ok(_) => {
            #[cfg(feature = "unstable_provide")]
            {
                let mut lock = PROVIDERS.lock().unwrap();
                let providers = lock.take().unwrap();
                let container = CONTAINER.get_mut().unwrap();

                for InjectProvider { key, provider, .. } in providers {
                    container
                        .add_provider_internal(key.clone(), provider)
                        .unwrap_or_else(|_| panic!("Failed to add provider for key: {:?}", key));
                }
            }

            Ok(())
        }
        Err(e) => Err(e),
    }
}

/// Returns a reference to the global [`Container`] or `None` if is not initialized.
#[inline]
pub fn get_container() -> Option<&'static Container<'static>> {
    CONTAINER.get()
}

/// Returns a scoped value from the global [`Container`] or `None` if is not in the container.
#[macro_export]
macro_rules! get_scoped {
    ($scoped_type:ty) => {
        $crate::global::get_container()
            .expect("The container is not initialized")
            .get_scoped::<$scoped_type>()
    };

    ($scoped_type:ty, $name:expr) => {
        $crate::global::get_container()
            .expect("The container is not initialized")
            .get_scoped_with_name::<$scoped_type>($name)
    };

   (trait $trait_type:ident $(<$($generic:ident),+>)?) => {{
        let container = $crate::global::get_container().expect("The container is not initialized");
        $crate::get_scoped_trait!(container, $trait_type $(<$($generic),+>)?)
   }};

   (trait $trait_type:ident $(<$($generic:ident),+>)?, $name:expr) => {{
        let container = $crate::global::get_container().expect("The container is not initialized");
        $crate::get_scoped_trait!(container, $trait_type $(<$($generic),+>)?, $name)
   }};
}

/// Returns a singleton value from the global [`Container`] or `None` if is not in the container.
#[macro_export]
macro_rules! get_singleton {
    ($singleton_type:ty) => {
        $crate::global::get_container()
            .expect("The container is not initialized")
            .get_singleton::<$singleton_type>()
    };

    ($singleton_type:ty, $name:expr) => {
        $crate::global::get_container()
            .expect("The container is not initialized")
            .get_singleton_with_name::<$singleton_type>($name)
    };

    (trait $trait_type:ident $(<$($generic:ident),+>)?) => {{
        let container = $crate::global::get_container().expect("The container is not initialized");
        $crate::get_singleton_trait!(container, $trait_type $(<$($generic),+>)?)
    }};

    (trait $trait_type:ident $(<$($generic:ident),+>)?, $name:expr) => {{
        let container = $crate::global::get_container().expect("The container is not initialized");
        $crate::get_singleton_trait!(container, $trait_type $(<$($generic),+>)?, $name)
    }};
}

/// Returns a value from the [`Container`] or `None` if is not in the container.
#[macro_export]
macro_rules! resolve {
    ($type:ty) => {
        $crate::global::get_container()
            .expect("The container is not initialized")
            .get::<$type>()
    };

    ($type:ty, $name:expr) => {
        $crate::global::get_container()
            .expect("The container is not initialized")
            .get_with_name::<$type>($name)
    };

    (trait $trait_type:ident $(<$($generic:ident),+>)?) => {{
        let container = $crate::global::get_container().expect("The container is not initialized");
        $crate::get_resolved_trait!(container, $trait_type $(<$($generic),+>)?)
    }};

    (trait $trait_type:ident $(<$($generic:ident),+>)?, $name:expr) => {{
        let container = $crate::global::get_container().expect("The container is not initialized");
        $crate::get_resolved_trait!(container, $trait_type $(<$($generic),+>)?, $name)
    }};
}

#[cfg(test)]
mod tests {
    use crate::global::{get_container, init_container, GlobalContainer};
    use crate::{add_scoped_trait, add_singleton_trait};
    use std::sync::Mutex;

    pub trait Greeter {
        fn greet(&self) -> &str;
    }

    struct EnglishGreeter;
    impl Greeter for EnglishGreeter {
        fn greet(&self) -> &str {
            "Hello, world!"
        }
    }

    struct SpanishGreeter;
    impl Greeter for SpanishGreeter {
        fn greet(&self) -> &str {
            "Hola, mundo!"
        }
    }

    #[test]
    fn global_container_test() {
        init_container(|container| {
            container
                .add_scoped(|| String::from("Hello World"))
                .unwrap();
            container.add_singleton(Mutex::new(5_i32)).unwrap();
            add_singleton_trait!(container, Greeter => EnglishGreeter).unwrap();
            add_scoped_trait!(container, "es", Greeter => SpanishGreeter).unwrap();
        })
        .unwrap();

        let container = get_container().unwrap();

        assert_eq!(
            container.get_scoped::<String>().unwrap(),
            "Hello World".to_owned()
        );
        assert_eq!(
            *container
                .get_singleton::<Mutex<i32>>()
                .unwrap()
                .lock()
                .unwrap(),
            5_i32
        );

        let r1 = get_scoped!(String).unwrap();
        assert_eq!(r1, "Hello World".to_owned());

        let r2 = get_singleton!(Mutex<i32>).unwrap();
        assert_eq!(*r2.lock().unwrap(), 5_i32);

        let r3 = get_scoped!(trait Greeter, "es").unwrap();
        assert_eq!(r3.greet(), "Hola, mundo!");

        let r4 = get_singleton!(trait Greeter).unwrap();
        assert_eq!(r4.greet(), "Hello, world!");

        let r5 = resolve!(String).unwrap();
        let r6 = resolve!(Mutex<i32>).unwrap();

        assert_eq!(&*r5, "Hello World");
        assert_eq!(*r6.lock().unwrap(), 5_i32);
    }

    #[test]
    fn no_initialized_test() {
        static GLOBAL_CONTAINER: GlobalContainer = GlobalContainer::new();
        assert!(GLOBAL_CONTAINER.get().is_none());

        GLOBAL_CONTAINER.initialize(|_| {}).unwrap();
        assert!(GLOBAL_CONTAINER.get().is_some());
    }
}