Skip to main content

datumesh_engine/
native_test.rs

1//! [`NativeTest`] (feature `native-test`): a runtime of Rust closures keyed by function hash,
2//! for tests and benchmarks. Its language is `native_test`.
3
4use 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
13/// The language of [`NativeTest`]: descriptors with `code.lang` = `native_test`.
14pub const LANG: &str = "native_test";
15
16/// A function of the [`NativeTest`] runtime.
17pub type NativeFn = dyn Fn(&Cell, &mut dyn Inputs, &mut Budget) -> Result<Scalar, EvalError> + Send + Sync;
18
19/// A runtime whose functions are Rust closures, registered under the hash of the descriptor
20/// they implement. For tests only: nothing ties a closure to the descriptor's body.
21#[derive(Clone, Default)]
22pub struct NativeTest {
23    fns: HashMap<String, Arc<NativeFn>>,
24}
25
26impl NativeTest {
27    /// A runtime with no functions.
28    pub fn new() -> NativeTest {
29        NativeTest::default()
30    }
31
32    /// Registers `f` as the function whose descriptor hashes to `fn_hash`.
33    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}