]> Witch of Git - jade-rose/blob - toolchain/src/js.rs
Implement wrappers for web
[jade-rose] / toolchain / src / js.rs
1 use super::{
2 inst::{ Encode, Inst},
3 Error,
4 };
5 use js_sys;
6 use std::io::{Cursor, Write};
7 use wasm_bindgen::prelude::*;
8
9 #[wasm_bindgen]
10 pub fn assemble(code: &str) -> Result<Vec<u8>, JsValue> {
11 let mut result = Cursor::new(Vec::new());
12 for (i, line) in code.lines().enumerate() {
13 let line = line.trim();
14 if line.is_empty() {
15 continue;
16 }
17 let inst = Inst::parse(line)
18 .ok_or_else(|| js_sys::Error::new(&format!("Error parsing line {}", i + 1)))?;
19 inst.encode(&mut result)
20 .expect("can always write into a vector");
21 }
22 Ok(result.into_inner())
23 }
24
25 #[wasm_bindgen]
26 pub fn disassemble(data: Vec<u8>) -> Result<String, JsValue> {
27 let mut input = Cursor::new(data);
28 let mut output = Cursor::new(Vec::new());
29 for inst in super::disassemble(&mut input)? {
30 writeln!(output, "{}", inst).unwrap();
31 }
32 // Can use _unchecked if we want because we control the display impl
33 Ok(String::from_utf8(output.into_inner()).unwrap())
34 }
35
36 impl From<Error> for JsValue {
37 fn from(e: Error) -> JsValue {
38 match e {
39 Error::Io { position, error } => {
40 js_sys::Error::new(&format!("Error at byte {}: {}", position, error)).into()
41 }
42 }
43 }
44 }