Skip to main content

async_wait/
async_wait.rs

1//! async wait through the public embedding API.
2use moonseed::*;
3mod support;
4use support::*;
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.read", NativePolicy::VmLocal, |cx| {
8        Ok(NativeReturn::Wait(WaitRequest {
9            operation: "read.asset".into(),
10            payload: MultiValue(vec![cx.arg(0).to_owned_value()?]),
11        }))
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    let read = rt.make_closure("example.read", ())?;
15    let mut journal = Journal::new();
16    let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut journal, 100)? else {
17        return Err("expected a host wait".into());
18    };
19    let request = rt.wait(key).ok_or("missing wait")?;
20    assert_eq!(request.operation, "read.asset");
21    let Value::String(name) = &request.payload[0] else {
22        return Err("expected a string".into());
23    };
24    assert_eq!(name.to_str(&rt)?, "answer");
25    // Submit work here; complete only after the host has its result.
26    rt.complete(key, Completion::Return(vec![Value::Integer(42)]))?;
27    assert_eq!(rt.run(100, &mut journal)?, StepOutcome::Completed);
28    assert_eq!(rt.finish_call::<i64>()?, 42);
29    Ok(())
30}
31
32#[cfg(test)]
33#[test]
34fn example_runs_and_asserts_its_result() {
35    main().unwrap();
36}