use std::sync::{Arc, RwLock};
use kevy_config::Config;
static GLOBAL: RwLock<Option<Arc<Config>>> = RwLock::new(None);
pub fn init(cfg: Arc<Config>) {
let mut g = GLOBAL.write().expect("config_global poisoned");
if g.is_none() {
*g = Some(cfg);
}
}
pub fn get() -> Arc<Config> {
GLOBAL
.read()
.expect("config_global poisoned")
.as_ref()
.cloned()
.unwrap_or_else(|| Arc::new(Config::default()))
}
pub fn replace(cfg: Arc<Config>) -> Result<(), &'static str> {
let mut g = GLOBAL.write().expect("config_global poisoned");
if g.is_none() {
return Err("config_global not initialised");
}
*g = Some(cfg);
Ok(())
}
pub fn is_initialised() -> bool {
GLOBAL
.read()
.expect("config_global poisoned")
.is_some()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn init_sets_once_then_ignores_subsequent_calls() {
let first = Arc::new(Config::default());
init(first.clone());
let second = Arc::new({
let mut c = Config::default();
c.memory.maxmemory = 12345;
c
});
init(second.clone());
let live = get();
assert_eq!(
live.memory.maxmemory, first.memory.maxmemory,
"init must be idempotent — second init call should not overwrite"
);
let third = Arc::new({
let mut c = Config::default();
c.memory.maxmemory = 67890;
c
});
replace(third.clone()).expect("replace after init must succeed");
assert_eq!(get().memory.maxmemory, 67890);
}
#[test]
fn get_after_init_returns_the_installed_config() {
let live = get();
assert!(Arc::strong_count(&live) >= 1);
}
}