datumesh_engine/
native_test.rs1use std::collections::{HashMap, HashSet};
5use std::fmt;
6use std::sync::Arc;
7
8use datumesh_core::{Cell, FunctionDescriptor, Scalar};
9
10use crate::error::EvalError;
11use crate::runtime::{Budget, Inputs, Runtime};
12
13pub const LANG: &str = "native_test";
15
16pub type NativeFn = dyn Fn(&Cell, &mut dyn Inputs, &mut Budget) -> Result<Scalar, EvalError> + Send + Sync;
18
19#[derive(Clone, Default)]
22pub struct NativeTest {
23 fns: HashMap<String, Arc<NativeFn>>,
24 asof_dependent: HashSet<String>,
25}
26
27impl NativeTest {
28 pub fn new() -> NativeTest {
30 NativeTest::default()
31 }
32
33 pub fn register(
35 &mut self,
36 fn_hash: impl Into<String>,
37 f: impl Fn(&Cell, &mut dyn Inputs, &mut Budget) -> Result<Scalar, EvalError> + Send + Sync + 'static,
38 ) -> &mut Self {
39 self.fns.insert(fn_hash.into(), Arc::new(f));
40 self
41 }
42
43 pub fn set_asof_dependent(&mut self, fn_hash: impl Into<String>) -> &mut Self {
46 self.asof_dependent.insert(fn_hash.into());
47 self
48 }
49}
50
51impl fmt::Debug for NativeTest {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 f.debug_struct("NativeTest").field("functions", &self.fns.len()).finish()
54 }
55}
56
57impl Runtime for NativeTest {
58 fn lang(&self) -> &str {
59 LANG
60 }
61
62 fn asof_dependent(&self, descriptor: &FunctionDescriptor) -> bool {
63 self.asof_dependent.contains(&descriptor.hash())
64 }
65
66 fn evaluate(
67 &self,
68 _descriptor: &FunctionDescriptor,
69 cell: &Cell,
70 inputs: &mut dyn Inputs,
71 budget: &mut Budget,
72 ) -> Result<Scalar, EvalError> {
73 match self.fns.get(&cell.fn_hash) {
74 Some(f) => {
75 budget.charge(1)?;
76 f(cell, inputs, budget)
77 }
78 None => Err(EvalError::Runtime(format!("no native function registered for {}", cell.fn_hash))),
79 }
80 }
81}