1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::convert::TryFrom;
use anyhow::Result;
use wasmtime::{AsContextMut, Trap, TypedFunc};

use dataplane::smartmodule::{SmartModuleInput, SmartModuleOutput, SmartModuleInternalError};
use crate::{
    WasmSlice,
    smartmodule::{
        SmartModuleWithEngine, SmartModuleContext, SmartModuleInstance, SmartModuleExtraParams,
    },
};

const MAP_FN_NAME: &str = "map";
type OldMapFn = TypedFunc<(i32, i32), i32>;
type MapFn = TypedFunc<(i32, i32, u32), i32>;

pub struct SmartModuleMap {
    base: SmartModuleContext,
    map_fn: MapFnKind,
}
enum MapFnKind {
    Old(OldMapFn),
    New(MapFn),
}

impl MapFnKind {
    fn call(&self, store: impl AsContextMut, slice: WasmSlice) -> Result<i32, Trap> {
        match self {
            Self::Old(map_fn) => map_fn.call(store, (slice.0, slice.1)),
            Self::New(map_fn) => map_fn.call(store, slice),
        }
    }
}

impl SmartModuleMap {
    pub fn new(
        module: &SmartModuleWithEngine,
        params: SmartModuleExtraParams,
        version: i16,
    ) -> Result<Self> {
        let mut base = SmartModuleContext::new(module, params, version)?;
        let map_fn = if let Ok(map_fn) = base.instance.get_typed_func(&mut base.store, MAP_FN_NAME)
        {
            MapFnKind::New(map_fn)
        } else {
            let map_fn: OldMapFn = base.instance.get_typed_func(&mut base.store, MAP_FN_NAME)?;
            MapFnKind::Old(map_fn)
        };
        Ok(Self { base, map_fn })
    }
}

impl SmartModuleInstance for SmartModuleMap {
    fn process(&mut self, input: SmartModuleInput) -> Result<SmartModuleOutput> {
        let slice = self.base.write_input(&input)?;
        let map_output = self.map_fn.call(&mut self.base.store, slice)?;

        if map_output < 0 {
            let internal_error = SmartModuleInternalError::try_from(map_output)
                .unwrap_or(SmartModuleInternalError::UnknownError);
            return Err(internal_error.into());
        }

        let output: SmartModuleOutput = self.base.read_output()?;
        Ok(output)
    }

    fn params(&self) -> SmartModuleExtraParams {
        self.base.params.clone()
    }
}