aboutsummaryrefslogtreecommitdiff
path: root/mingling_core/src/program/single_instance.rs
blob: 45d4d33e5cacb75e187e897472343527f54f1fd7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use std::sync::OnceLock;

use crate::{Program, ProgramCollect};

/// Global static reference to the current program instance
pub(crate) static THIS_PROGRAM: OnceLock<Option<Box<dyn std::any::Any + Send + Sync>>> =
    OnceLock::new();

/// Returns a reference to the current program instance, panics if not set.
pub fn this<C>() -> &'static Program<C>
where
    C: ProgramCollect<Enum = C> + 'static,
{
    try_get_this_program().expect("Program not initialized")
}

/// Returns a reference to the current program instance, if set.
fn try_get_this_program<C>() -> Option<&'static Program<C>>
where
    C: ProgramCollect<Enum = C> + 'static,
{
    THIS_PROGRAM.get()?.as_ref()?.downcast_ref::<Program<C>>()
}