reactive_graph_std_numeric/behaviour/entity/gate/
function.rs

1use std::sync::Arc;
2use std::sync::LazyLock;
3
4use reactive_graph_behaviour_model_impl::entity::EntityBehaviourFactoryCreator;
5use reactive_graph_behaviour_model_impl::entity::EntityBehaviourFunctions;
6use reactive_graph_behaviour_model_impl::entity::EntityBehaviourFunctionsStorage;
7
8use reactive_graph_std_numeric_model::NAMESPACE_NUMERIC_F64;
9
10use crate::behaviour::entity::gate::behaviour_f64::NumericGateF64Factory;
11
12use serde_json::Value;
13use serde_json::json;
14
15pub type NumericGateFunction<T> = fn(T, T) -> Value;
16pub type NumericGateF64Function = NumericGateFunction<f64>;
17
18pub const FN_ATAN2_F64: NumericGateF64Function = |lhs, rhs| json!(lhs.atan2(rhs));
19pub const FN_HYPOT_F64: NumericGateF64Function = |lhs, rhs| json!(lhs.hypot(rhs));
20pub const FN_LOG_F64: NumericGateF64Function = |lhs, rhs| json!(lhs.log(rhs));
21pub const FN_POW_F64: NumericGateF64Function = |lhs, rhs| json!(lhs.powf(rhs));
22
23const FACTORY_CREATOR_F64: EntityBehaviourFactoryCreator<NumericGateF64Function> = |ty, f| Arc::new(NumericGateF64Factory::new(ty.clone(), f));
24
25pub static NUMERIC_GATES_F64: EntityBehaviourFunctionsStorage<NumericGateF64Function> = LazyLock::new(|| {
26    EntityBehaviourFunctions::<NumericGateF64Function>::with_namespace(NAMESPACE_NUMERIC_F64, FACTORY_CREATOR_F64)
27        .behaviour("atan2", FN_ATAN2_F64)
28        .behaviour("hypot", FN_HYPOT_F64)
29        .behaviour("log", FN_POW_F64)
30        .behaviour("pow", FN_POW_F64)
31        .get()
32});
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn numeric_gate_function_test() {
40        let lhs: f64 = 0.5;
41        let rhs: f64 = 0.5;
42        assert_eq!(lhs.atan2(rhs), FN_ATAN2_F64(lhs, rhs));
43        assert_eq!(lhs.hypot(rhs), FN_HYPOT_F64(lhs, rhs));
44        assert_eq!(lhs.log(rhs), FN_LOG_F64(lhs, rhs));
45        assert_eq!(lhs.powf(rhs), FN_POW_F64(lhs, rhs));
46    }
47}