Skip to content

Commit

Permalink
Add WASM bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
wezm committed Mar 22, 2023
1 parent 53568f5 commit 909ed18
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/target
/Cargo.lock
/wasm
10 changes: 10 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,15 @@ repository = "https://github.com/wezm/rsspls.git"
readme = "README.md"
license = "Apache-2.0"

[lib]
# cdylib is for WASM
crate-type = ["cdylib", "rlib"]

[dependencies]
crc = "3.0.1"

[target.'cfg(target_family = "wasm")'.dependencies]
serde = { version = "1.0", features = ["derive"] }
serde-wasm-bindgen = "0.5"
serde_bytes = "0.11.9"
wasm-bindgen = "0.2.84"
9 changes: 9 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
all: wasm/macbinary.js

wasm/macbinary.js: target/wasm32-unknown-unknown/release/macbinary.wasm
wasm-bindgen target/wasm32-unknown-unknown/release/macbinary.wasm --target web --out-dir wasm

target/wasm32-unknown-unknown/release/macbinary.wasm:
cargo build --lib --target wasm32-unknown-unknown --release

.PHONY: target/wasm32-unknown-unknown/release/macbinary.wasm
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ mod macroman;
mod resource;
#[cfg(test)]
mod test;
#[cfg(target_family = "wasm")]
mod wasm;

const MBIN_SIG: u32 = u32::from_be_bytes(*b"mBIN");

Expand Down
31 changes: 31 additions & 0 deletions src/wasm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;

use crate::ParseError;

#[derive(Serialize, Deserialize)]
struct MacBinaryFile {
name: String,
#[serde(with = "serde_bytes")]
data_fork: Vec<u8>,
#[serde(with = "serde_bytes")]
rsrc_fork: Vec<u8>,
}

#[wasm_bindgen]
pub fn parse_macbinary(data: &[u8]) -> Result<JsValue, JsValue> {
let file = crate::parse(data)?;
let res = MacBinaryFile {
name: file.filename(),
data_fork: file.data_fork().to_vec(),
rsrc_fork: file.resource_fork_raw().to_vec(),
};
let js = serde_wasm_bindgen::to_value(&res)?;
Ok(js)
}

impl From<ParseError> for JsValue {
fn from(err: ParseError) -> JsValue {
JsValue::from(err.to_string())
}
}

0 comments on commit 909ed18

Please sign in to comment.