datumesh_engine/
native_test.rs1use std::collections::HashMap;
5use std::fmt;
6use std::sync::Arc;
7
8use datumesh_core::{Cell, Descriptor, 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}
25
26impl NativeTest {
27 pub fn new() -> NativeTest {
29 NativeTest::default()
30 }
31
32 pub fn register(
34 &mut self,
35 fn_hash: impl Into<String>,
36 f: impl Fn(&Cell, &mut dyn Inputs, &mut Budget) -> Result<Scalar, EvalError> + Send + Sync + 'static,
37 ) -> &mut Self {
38 self.fns.insert(fn_hash.into(), Arc::new(f));
39 self
40 }
41}
42
43impl fmt::Debug for NativeTest {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 f.debug_struct("NativeTest").field("functions", &self.fns.len()).finish()
46 }
47}
48
49impl Runtime for NativeTest {
50 fn lang(&self) -> &str {
51 LANG
52 }
53
54 fn evaluate(
55 &self,
56 _descriptor: &Descriptor,
57 cell: &Cell,
58 inputs: &mut dyn Inputs,
59 budget: &mut Budget,
60 ) -> Result<Scalar, EvalError> {
61 match self.fns.get(&cell.fn_hash) {
62 Some(f) => {
63 budget.charge(1)?;
64 f(cell, inputs, budget)
65 }
66 None => Err(EvalError::Runtime(format!("no native function registered for {}", cell.fn_hash))),
67 }
68 }
69}