use wasm_bindgen::prelude::*;
use crate::memconv::{self, MemImage};
#[wasm_bindgen(start)]
pub fn start() {
console_error_panic_hook::set_once();
}
fn to_js(e: impl std::fmt::Display) -> JsValue {
JsValue::from_str(&e.to_string())
}
#[wasm_bindgen]
pub fn probe(bytes: &[u8]) -> Result<String, JsValue> {
let report = memconv::probe(bytes).map_err(to_js)?;
serde_json::to_string(&report).map_err(to_js)
}
#[wasm_bindgen]
pub fn supported_targets() -> Result<String, JsValue> {
serde_json::to_string(&memconv::supported_targets()).map_err(to_js)
}
#[wasm_bindgen]
pub struct Image {
inner: MemImage,
}
#[wasm_bindgen]
impl Image {
#[wasm_bindgen(constructor)]
pub fn new(bytes: Vec<u8>) -> Result<Image, JsValue> {
Ok(Image {
inner: MemImage::open(bytes).map_err(to_js)?,
})
}
#[wasm_bindgen(js_name = openPartition)]
pub fn open_partition(bytes: Vec<u8>, part: usize) -> Result<Image, JsValue> {
Ok(Image {
inner: MemImage::open_partition(bytes, Some(part)).map_err(to_js)?,
})
}
#[wasm_bindgen(getter)]
pub fn kind(&self) -> String {
self.inner.kind().to_string()
}
pub fn list(&mut self, path: &str) -> Result<String, JsValue> {
let entries = self.inner.list(path).map_err(to_js)?;
serde_json::to_string(&entries).map_err(to_js)
}
#[wasm_bindgen(js_name = readFile)]
pub fn read_file(&mut self, path: &str) -> Result<Vec<u8>, JsValue> {
self.inner.read_file(path).map_err(to_js)
}
#[wasm_bindgen(js_name = readSymlink)]
pub fn read_symlink(&mut self, path: &str) -> Result<String, JsValue> {
self.inner.read_symlink(path).map_err(to_js)
}
pub fn convert(&mut self, target: &str) -> Result<Vec<u8>, JsValue> {
self.inner.convert(target).map_err(to_js)
}
}