collab-common 0.0.7

Code shared by collab's client and server
Documentation
//! Test utilities.

use std::sync::{Mutex, OnceLock};

/// A global value that can be read and set multiple times.
#[derive(Default)]
pub struct Global<T> {
    inner: OnceLock<Mutex<T>>,
}

impl<T> Global<T> {
    /// Creates a new global value.
    pub const fn new() -> Self {
        Self { inner: OnceLock::new() }
    }

    /// Sets the value of the global.
    pub fn set(&self, value: T) {
        match self.inner.get() {
            Some(inner) => {
                *inner.lock().unwrap() = value;
            },
            None => {
                let Ok(_) = self.inner.set(Mutex::new(value)) else {
                    unreachable!(
                        "get returned `None`, so the set will succeed"
                    );
                };
            },
        }
    }

    /// Executes a function with the value of the global, if it was set.
    pub fn with<F, R>(&self, fun: F) -> R
    where
        F: FnOnce(Option<&T>) -> R,
    {
        let Some(lock) = self.inner.get() else { return fun(None) };
        let value = &*lock.lock().unwrap();
        fun(Some(value))
    }
}