use std::sync::{Mutex, OnceLock};
use crate::sync::lock;
pub struct Global<T>(OnceLock<T>);
impl<T> Global<T> {
pub const fn new() -> Self {
Self(OnceLock::new())
}
#[cfg_attr(not(feature = "json"), allow(dead_code))]
pub fn get(&self) -> Option<&T> {
self.0.get()
}
pub fn get_or_init(&self, init: impl FnOnce() -> T) -> &T {
self.0.get_or_init(init)
}
}
impl<T> Default for Global<T> {
fn default() -> Self {
Self::new()
}
}
pub struct Locked<T>(OnceLock<Mutex<T>>);
impl<T: Default> Locked<T> {
pub const fn new() -> Self {
Self(OnceLock::new())
}
pub fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
let mutex = self.0.get_or_init(|| Mutex::new(T::default()));
let mut guard = lock(mutex);
f(&mut guard)
}
}
impl<T: Default> Default for Locked<T> {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn global_is_initialized_once() {
static CELL: Global<String> = Global::new();
assert_eq!(CELL.get(), None);
let first = CELL.get_or_init(|| String::from("first"));
assert_eq!(first, "first");
let second = CELL.get_or_init(|| String::from("second"));
assert_eq!(second, "first");
}
#[test]
fn locked_creates_its_value_on_first_use() {
static LIST: Locked<Vec<u32>> = Locked::new();
LIST.with(|values| values.push(1));
LIST.with(|values| values.push(2));
assert_eq!(LIST.with(|values| values.clone()), vec![1, 2]);
}
#[test]
fn locked_recovers_from_a_poisoned_lock() {
static MAP: Locked<std::collections::HashMap<u32, u32>> = Locked::new();
let _ = std::panic::catch_unwind(|| {
MAP.with(|map| {
map.insert(2, 2);
panic!("poison the lock");
});
});
assert_eq!(MAP.with(|map| map.get(&2).copied()), Some(2));
MAP.with(|map| map.insert(3, 3));
assert_eq!(MAP.with(|map| map.len()), 2);
}
#[test]
fn the_default_constructors_build_an_empty_cell() {
let global: Global<u8> = Global::default();
assert_eq!(global.get(), None, "nothing is built before first use");
assert_eq!(*global.get_or_init(|| 7), 7);
let locked: Locked<Vec<u8>> = Locked::default();
assert!(
locked.with(|values| values.is_empty()),
"the guarded value starts as its `Default`"
);
locked.with(|values| values.push(1));
assert_eq!(locked.with(|values| values.clone()), vec![1]);
}
}