stepflow_wasm/
lib.rs

1use std::convert::TryFrom;
2use std::ffi::{CStr, CString};
3use std::mem;
4use std::os::raw::{c_char, c_void};
5use tinyjson::JsonValue;
6
7mod cstr;
8mod session_store;
9mod session_advance_blockedon;
10mod result;
11use result::StepFlowResult;
12
13
14/*
15** GLOBAL ALLOCATOR
16 */
17
18extern crate wee_alloc;
19
20#[global_allocator]
21static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
22
23
24/*
25** SESSION
26 */
27
28mod session;
29use session::{create_session, advance_session, get_statedata};
30
31// FUTURE: can we remove these unwrap() calls?
32
33#[no_mangle]
34pub extern fn createSession(data: *mut c_char) -> *mut c_char {
35  let json = str_from_cstr!(data);
36  let session_id = create_session(json, true);
37  let result = match session_id {
38      Ok(id) => StepFlowResult::Ok(JsonValue::Number(id.val().into())),
39      Err(e) => StepFlowResult::Err(e),
40  };
41  let cstring = CString::try_from(result).unwrap();
42  cstring.into_raw()
43}
44
45#[no_mangle]
46pub extern fn advanceSession(session_id_val: i32, step_output_json: *mut c_char) -> *mut c_char {
47  let result: StepFlowResult = advance_session(session_id_val, str_from_cstr_or_null!(step_output_json)).into();
48  let cstring = CString::try_from(result).unwrap();
49  cstring.into_raw()
50}
51
52#[no_mangle]
53pub extern fn getStateData(session_id_val: i32) -> *mut c_char {
54    let result: StepFlowResult = get_statedata(session_id_val).into();
55    let cstring = CString::try_from(result).unwrap();
56    cstring.into_raw()
57}
58
59
60/*
61** MEMORY
62 */
63
64#[no_mangle]
65pub extern fn alloc(num_bytes: usize) -> *mut c_void {
66    let mut buf = Vec::with_capacity(num_bytes);
67    let ptr = buf.as_mut_ptr();
68    mem::forget(buf);
69    ptr
70}
71
72#[no_mangle]
73pub unsafe extern fn dealloc(ptr: *mut c_void, num_bytes: usize) {
74    let _ = Vec::from_raw_parts(ptr, 0, num_bytes);
75}
76
77#[no_mangle]
78pub extern fn dealloc_str(ptr: *mut c_char) {
79    unsafe {
80        let _ = CString::from_raw(ptr);
81    }
82}