Skip to main content

iris_wasm/
noun.rs

1use iris_ztd::{cue as cue_internal, jam as jam_internal, Belt, Noun, NounDecode, NounEncode};
2use std::sync::Arc;
3use wasm_bindgen::prelude::*;
4
5#[wasm_bindgen]
6pub fn cue(jam: &[u8]) -> Result<Noun, JsValue> {
7    cue_internal(jam).ok_or_else(|| JsValue::from_str("unable to parse jam"))
8}
9
10#[wasm_bindgen]
11pub fn jam(noun: Noun) -> Result<Vec<u8>, JsValue> {
12    Ok(jam_internal(noun))
13}
14
15#[wasm_bindgen]
16pub fn tas(s: &str) -> Noun {
17    let bytes = s.as_bytes();
18    let a = ibig::UBig::from_le_bytes(bytes);
19    Noun::Atom(a)
20}
21
22#[wasm_bindgen]
23pub fn untas(noun: Noun) -> Result<String, JsValue> {
24    match noun {
25        Noun::Atom(atom) => Ok(String::from_utf8(atom.to_le_bytes())
26            .map_err(|_| JsValue::from_str("not valid utf8"))?),
27        _ => Err(JsValue::from_str("not an atom")),
28    }
29}
30
31#[wasm_bindgen]
32pub fn tas_belts(s: &str) -> Noun {
33    atom_to_belts(tas(s)).unwrap()
34}
35
36#[wasm_bindgen]
37pub fn atom_to_belts(atom: Noun) -> Result<Noun, JsValue> {
38    match atom {
39        Noun::Atom(atom) => Ok((&iris_ztd::belts_from_atom(atom)[..]).to_noun()),
40        _ => Err(JsValue::from_str("not an atom")),
41    }
42}
43
44#[wasm_bindgen]
45pub fn belts_to_atom(noun: Noun) -> Result<Noun, JsValue> {
46    // Append tail so that this is parsed as list
47    // TODO: don't do this
48    let noun = Noun::Cell(Arc::new(noun), Arc::new(0u64.to_noun()));
49    let belts: Vec<Belt> =
50        NounDecode::from_noun(&noun).ok_or_else(|| JsValue::from_str("unable to parse belts"))?;
51    Ok(Noun::Atom(iris_ztd::belts_to_atom(&belts)))
52}