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/// Cue a jammed Uint8Array into a Noun (see `jam`).
6#[wasm_bindgen]
7pub fn cue(jam: &[u8]) -> Result<Noun, JsValue> {
8    cue_internal(jam).ok_or_else(|| JsValue::from_str("unable to parse jam"))
9}
10
11/// Encode a Noun as a Uint8Array of bytes.
12#[wasm_bindgen]
13pub fn jam(noun: Noun) -> Result<Vec<u8>, JsValue> {
14    Ok(jam_internal(noun))
15}
16
17/// Convert string to an Atom.
18#[wasm_bindgen]
19pub fn tas(s: &str) -> Noun {
20    let bytes = s.as_bytes();
21    let a = ibig::UBig::from_le_bytes(bytes);
22    Noun::Atom(a)
23}
24
25/// Convert an Atom into a string.
26#[wasm_bindgen]
27pub fn untas(noun: Noun) -> Result<String, JsValue> {
28    match noun {
29        Noun::Atom(atom) => Ok(String::from_utf8(atom.to_le_bytes())
30            .map_err(|_| JsValue::from_str("not valid utf8"))?),
31        _ => Err(JsValue::from_str("not an atom")),
32    }
33}
34
35/// Convert a string to sequence of Belts.
36///
37/// This is equivalent to `atom_to_belts(tas(s))`.
38///
39/// Belts are Atoms that fit the goldilocks prime field.
40///
41/// If a transaction contains non-based (not-fitting) atoms, it will be rejected.
42#[wasm_bindgen]
43pub fn tas_belts(s: &str) -> Noun {
44    atom_to_belts(tas(s)).unwrap()
45}
46
47/// Convert an Atom to belts.
48#[wasm_bindgen]
49pub fn atom_to_belts(atom: Noun) -> Result<Noun, JsValue> {
50    match atom {
51        Noun::Atom(atom) => Ok((&iris_ztd::belts_from_ubig(atom)[..]).to_noun()),
52        _ => Err(JsValue::from_str("not an atom")),
53    }
54}
55
56/// Convert a sequence of belts back into one atom.
57#[wasm_bindgen]
58pub fn belts_to_atom(noun: Noun) -> Result<Noun, JsValue> {
59    // Append tail so that this is parsed as list
60    // TODO: don't do this
61    let noun = Noun::Cell(Arc::new(noun), Arc::new(0u64.to_noun()));
62    let belts: Vec<Belt> =
63        NounDecode::from_noun(&noun).ok_or_else(|| JsValue::from_str("unable to parse belts"))?;
64    Ok(Noun::Atom(iris_ztd::belts_to_ubig(&belts)))
65}