Skip to main content

trumly_wasm/
lib.rs

1//! trumly-core for the browser. No wasm-bindgen: three plain functions, so the only tool needed is
2//! `cargo build --target wasm32-unknown-unknown`.
3//!
4//! A WASM module can only exchange numbers with JavaScript, so text goes through the module's
5//! memory: JS asks us to `alloc` a buffer, copies bytes in, calls `check`, reads the answer bytes
6//! back out of memory, then calls `dealloc` on both buffers.
7//!
8//!   input  (JSON): [["path.md", "file text"], ...]
9//!   output (JSON): the `check --json` document, or {"error": "..."}
10
11use trumly_core::report::check;
12
13/// Reserve `len` bytes inside the module and return where they are.
14#[unsafe(no_mangle)]
15pub extern "C" fn alloc(len: usize) -> *mut u8 {
16    let mut buf = Vec::<u8>::with_capacity(len);
17    let ptr = buf.as_mut_ptr();
18    std::mem::forget(buf); // we hand ownership to the caller until they call dealloc
19    ptr
20}
21
22/// Give a buffer back. `len` must be the length passed to `alloc` (or returned by `check`).
23///
24/// # Safety
25/// `ptr` and `len` must come from `alloc` or `check` and be freed once.
26#[unsafe(no_mangle)]
27pub unsafe extern "C" fn dealloc(ptr: *mut u8, len: usize) {
28    drop(unsafe { Vec::from_raw_parts(ptr, 0, len) });
29}
30
31/// Run `check` over the JSON input at (ptr, len). Returns the output location packed into one
32/// u64: high 32 bits = pointer, low 32 bits = length. (wasm32 pointers are 32 bits.)
33///
34/// # Safety
35/// `ptr..ptr+len` must be readable memory, as filled in by the caller after `alloc`.
36#[unsafe(no_mangle)]
37pub unsafe extern "C" fn check_json(ptr: *const u8, len: usize) -> u64 {
38    let input = unsafe { std::slice::from_raw_parts(ptr, len) };
39    let out = run(input);
40    let mut bytes = out.into_bytes().into_boxed_slice();
41    let (p, l) = (bytes.as_mut_ptr() as usize as u64, bytes.len() as u64);
42    std::mem::forget(bytes);
43    (p << 32) | l
44}
45
46/// The safe part, separated so it can be tested without any pointers.
47pub fn run(input: &[u8]) -> String {
48    let files: Result<Vec<(String, String)>, String> = serde_json::from_slice::<Vec<(String, String)>>(input).map_err(|e| e.to_string());
49    match files {
50        Ok(files) => check(files).to_json().to_string(),
51        Err(e) => serde_json::json!({ "error": e }).to_string(),
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn checks_a_model_given_as_json() {
61        let out = run(br#"[["a.md", "---\nid: a\ntype: t\nparent: nope\n---\n"]]"#);
62        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
63        assert_eq!(v["structure"]["errors"][0]["kind"], "missing_parent");
64    }
65
66    #[test]
67    fn bad_input_is_an_error_object_not_a_crash() {
68        let v: serde_json::Value = serde_json::from_str(&run(b"nonsense")).unwrap();
69        assert!(v["error"].is_string());
70    }
71
72    // The pointer functions pack a 32-bit address into a u64, which only makes sense inside
73    // wasm32. So this test runs there (via a wasm test runner) and is skipped on a normal machine.
74    #[cfg(target_arch = "wasm32")]
75    #[test]
76    fn the_pointer_api_round_trips() {
77        let input = br#"[["a.md", "---\nid: a\ntype: t\n---\n"]]"#;
78        let buf = alloc(input.len());
79        unsafe {
80            std::ptr::copy_nonoverlapping(input.as_ptr(), buf, input.len());
81            let packed = check_json(buf, input.len());
82            let (p, l) = ((packed >> 32) as usize, (packed & 0xffff_ffff) as usize);
83            let out = std::slice::from_raw_parts(p as *const u8, l);
84            assert!(std::str::from_utf8(out).unwrap().contains("\"nodes\""));
85            dealloc(p as *mut u8, l);
86            dealloc(buf, input.len());
87        }
88    }
89}