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, 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
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    asof_dependent: HashSet<String>,
25}
26
27impl NativeTest {
28    /// A runtime with no functions.
29    pub fn new() -> NativeTest {
30        NativeTest::default()
31    }
32
33    /// Registers `f` as the function whose descriptor hashes to `fn_hash`.
34    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    /// Declares the function whose descriptor hashes to `fn_hash` asof-dependent
44    /// ([`Runtime::asof_dependent`]). Since 0.3.0.
45    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}