rustduck-core 1.1.0

Safe typed TSDuck core bindings for rustduck
Documentation
//! Shared lifecycle state and transition validation for native plugin hosts.

use crate::{Error, Result};

/// The lifecycle state of a native host.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HostState {
    /// The host exists but has not been started.
    Created,
    /// The host has started native work.
    Running,
    /// Termination has been requested.
    Stopping,
    /// Native work has terminated.
    Stopped,
    /// Registration or native startup failed; the host cannot be reused.
    Failed,
}

impl HostState {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Created => "created",
            Self::Running => "running",
            Self::Stopping => "stopping",
            Self::Stopped => "stopped",
            Self::Failed => "failed",
        }
    }

    pub(crate) const fn is_active(self) -> bool {
        matches!(self, Self::Running | Self::Stopping)
    }
}

pub(crate) fn require_state(
    object: &'static str,
    operation: &'static str,
    actual: HostState,
    expected: HostState,
) -> Result<()> {
    if actual == expected {
        Ok(())
    } else {
        Err(invalid_state(object, operation, actual))
    }
}

pub(crate) fn invalid_state(
    object: &'static str,
    operation: &'static str,
    state: HostState,
) -> Error {
    Error::InvalidState {
        object,
        operation,
        state: state.as_str(),
    }
}

#[cfg(test)]
pub(crate) fn native_test_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
    LOCK.get_or_init(|| std::sync::Mutex::new(()))
        .lock()
        .expect("native lifecycle test lock")
}