1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use crate::states::StateInstance;
use rustc_hash::FxHashMap;
use std::any::{Any, TypeId};
use std::fmt::Debug;

#[derive(Debug, Default)]
pub struct ArgsMap {
    cache: FxHashMap<TypeId, Box<dyn Any + Sync + Send>>,
}

impl ArgsMap {
    /// Get an immutable args reference for the provided type.
    /// If the args does not exist, a [`None`] is returned.
    pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
        if let Some(value) = self.cache.get(&TypeId::of::<T>()) {
            return value.downcast_ref::<T>();
        }

        None
    }

    /// Set the args into the registry with the provided type.
    /// If an exact type already exists, it'll be overwritten.
    pub fn set<T: Any + Send + Sync>(&mut self, args: T) -> &mut Self {
        self.cache.insert(TypeId::of::<T>(), Box::new(args));
        self
    }
}

#[derive(Debug)]
pub struct ExecuteArgs(pub ArgsMap);

impl StateInstance for ExecuteArgs {
    fn extract<T: Any + Send + Sync>(&self) -> Option<&T> {
        self.0.get::<T>()
    }
}