Skip to main content

hello_call/support/
mod.rs

1//! Helpers used by the embedding examples.
2#![allow(dead_code)] // Each executable uses a different subset of these helpers.
3use moonseed::*;
4#[derive(Debug)]
5pub struct ExampleError(String);
6impl From<&str> for ExampleError {
7    fn from(value: &str) -> Self {
8        Self(value.into())
9    }
10}
11impl From<String> for ExampleError {
12    fn from(value: String) -> Self {
13        Self(value)
14    }
15}
16macro_rules! diagnostic {
17    ($($ty:ty),*) => { $(impl From<$ty> for ExampleError {
18        fn from(value: $ty) -> Self { Self(format!("{value:?}")) }
19    })* };
20}
21diagnostic!(moonseed::Error, CompileError, VmError, SnapshotError);
22impl std::fmt::Display for ExampleError {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        f.write_str(&self.0)
25    }
26}
27impl std::error::Error for ExampleError {}
28pub type ExampleResult<T = ()> = std::result::Result<T, ExampleError>;
29pub fn eval<R: FromLuaMulti>(rt: &mut Runtime, source: &[u8]) -> ExampleResult<R> {
30    rt.load_main(&compile(source)?)?;
31    match rt.run(10_000, &mut Journal::new())? {
32        StepOutcome::Completed => Ok(R::from_lua_multi(rt.result_values()?, rt)?),
33        other => Err(format!("chunk did not complete: {other:?}").into()),
34    }
35}
36pub fn done<R>(outcome: CallOutcome<R>) -> ExampleResult<R> {
37    match outcome {
38        CallOutcome::Done(value) => Ok(value),
39        other => Err(match other {
40            CallOutcome::Waiting(_) => "call is waiting",
41            CallOutcome::OutOfFuel => "call ran out of fuel",
42            CallOutcome::ExitRequested { .. } => "call requested exit",
43            _ => "unsupported call outcome",
44        }
45        .into()),
46    }
47}
48pub struct Counter(pub i64);
49impl HostUserdata for Counter {
50    const SYMBOL: &'static str = "example.Counter";
51    fn logical_size(&self) -> u64 {
52        8
53    }
54}
55impl PortableUserdata for Counter {
56    fn encode(&self) -> Vec<u8> {
57        self.0.to_le_bytes().to_vec()
58    }
59    fn decode(bytes: &[u8]) -> Option<Self> {
60        Some(Self(i64::from_le_bytes(bytes.try_into().ok()?)))
61    }
62}
63pub fn counter_registry() -> HostRegistry {
64    let mut registry = HostRegistry::new();
65    registry.register_portable_userdata::<Counter>();
66    registry.function("example.next", NativePolicy::VmLocal, |cx| {
67        let Value::UserData(counter) = cx.captures()[0].to_owned_value()? else {
68            return Err(ApiError::WrongType.into());
69        };
70        let value = {
71            let mut state = cx.borrow_userdata_mut::<Counter>(&counter)?;
72            state.0 = state.0.wrapping_add(1);
73            state.0
74        };
75        cx.return_values(value)
76    });
77    registry
78}