icedwright-probe 0.1.3

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
Documentation
//! The clock components should read instead of `Instant::now()`, so a harness can move it.
//!
//! Without the `control` feature these are the real clock. With it, a harness installs its
//! virtual clock once per process, and each call answers for the thread that makes it.

use std::time::{Instant, SystemTime};

/// The current instant: the harness's virtual instant under a harness, the real one otherwise.
#[must_use]
#[inline]
#[expect(
    clippy::disallowed_methods,
    reason = "the probe clock is the real clock unless a harness installs its virtual one"
)]
pub fn now() -> Instant {
    #[cfg(feature = "control")]
    if let Some(hooks) = hooks::get() {
        return (hooks.now)();
    }
    Instant::now()
}

/// The current wall-clock time: the harness's virtual wall clock under a harness, the real
/// one otherwise.
#[must_use]
#[inline]
#[expect(
    clippy::disallowed_methods,
    reason = "the probe clock is the real clock unless a harness installs its virtual one"
)]
pub fn system_now() -> SystemTime {
    #[cfg(feature = "control")]
    if let Some(hooks) = hooks::get() {
        return (hooks.system_now)();
    }
    SystemTime::now()
}

/// Declares that `component` runs a timer on the real clock, such as a ticker thread. A
/// harness refuses the step that creates it, because its ticks would depend on real time.
/// Outside a harness it does nothing.
#[inline]
pub fn real_timer(component: &'static str) {
    #[cfg(feature = "control")]
    if let Some(controller) = crate::control::current() {
        controller.real_timer(component);
    }
    #[cfg(not(feature = "control"))]
    let _ = component;
}

#[cfg(feature = "control")]
pub use hooks::install;

#[cfg(feature = "control")]
mod hooks {
    use std::sync::{PoisonError, RwLock};
    use std::time::{Instant, SystemTime};

    #[derive(Clone, Copy)]
    pub(super) struct Hooks {
        pub(super) now: fn() -> Instant,
        pub(super) system_now: fn() -> SystemTime,
    }

    static HOOKS: RwLock<Option<Hooks>> = RwLock::new(None);

    /// Makes [`now`](super::now) and [`system_now`](super::system_now) call these for the
    /// rest of the process. A harness installs functions that read the calling thread's
    /// virtual clock, so one install serves every test thread. Installing again replaces them.
    #[doc(hidden)]
    pub fn install(now: fn() -> Instant, system_now: fn() -> SystemTime) {
        *HOOKS.write().unwrap_or_else(PoisonError::into_inner) = Some(Hooks { now, system_now });
    }

    pub(super) fn get() -> Option<Hooks> {
        *HOOKS.read().unwrap_or_else(PoisonError::into_inner)
    }
}