Skip to main content

caretta_sync_core/global/
config.rs

1#[cfg(any(test, feature = "test"))]
2use tempfile::TempDir;
3use tokio::sync::OnceCell;
4
5use crate::config::Config;
6
7pub static CONFIG: GlobalConfig = GlobalConfig::const_new();
8pub struct GlobalConfig {
9    inner: OnceCell<Config>,
10}
11
12impl GlobalConfig {
13    pub const fn const_new() -> Self {
14        Self {
15            inner: OnceCell::const_new(),
16        }
17    }
18    pub async fn get_or_init<T>(&'static self, config: Config) -> &'static Config
19    where
20        T: Into<Config>,
21    {
22        self.inner.get_or_init(|| async { config }).await
23    }
24    pub async fn get_or_try_init<T, E>(
25        &'static self,
26        config: T,
27    ) -> Result<&'static Config, <T as TryInto<Config>>::Error>
28    where
29        T: TryInto<Config>,
30    {
31        self.inner
32            .get_or_try_init(|| async { config.try_into() })
33            .await
34    }
35    pub fn get(&'static self) -> Option<&'static Config> {
36        self.inner.get()
37    }
38    pub fn get_unchecked(&'static self) -> &'static Config {
39        self.get().expect("Config must be initialized before use!")
40    }
41}