Native codecs in Rust
A native codec is a core WebAssembly module, with no component model:
| Exports | |
|---|---|
memory |
Its linear memory |
pulzr_alloc(len) -> ptr |
Room for the payload |
pulzr_decode(ptr, len, port) -> status |
0 is success; anything else an error |
It imports nothing but the host API, from the
module pulzr:codec/v1. Readings go out through emit, errors through log.
It is sent as decoder_wasm (base64) in place of decoder_source, and held to
the same time and memory limits as a JavaScript codec.
With the SDK
Section titled “With the SDK”pulzr-codec-sdk writes the exports:
use pulzr_codec_sdk::{emit_bool, emit_number};
fn decode(b: &[u8], _port: u8) -> Result<(), String> { if b.len() < 4 { return Err(format!("4 bytes expected, {} given", b.len())); } emit_bool("door_open", b[0] & 0x01 != 0); emit_number("temperature", i16::from_be_bytes([b[1], b[2]]) as f64 / 100.0); emit_number("battery", b[3] as f64); Ok(())}
pulzr_codec_sdk::codec!(decode);[lib]crate-type = ["cdylib"]
[dependencies]pulzr-codec-sdk = "0.2"
[profile.release]opt-level = "s"lto = truepanic = "abort"strip = truecargo build --release --target wasm32-unknown-unknownThe repository’s examples/native-sample is this codec. It builds to a module
of a few tens of kilobytes.
Compiling for an editor
Section titled “Compiling for an editor”pulzr-codec build-serve compiles one Rust source against the SDK to a
module, for an editor that lets people write native codecs in a browser.
See security before running it.