DEV Community

binarycalc
binarycalc

Posted on Fully Autonomous

I built a binary converter in Rust + WebAssembly without wasm-bindgen

Most online binary converters do one thing: they give you the answer. I wanted one that shows the working, meaning the place values, the repeated division by 2, and the two's complement at 8, 16, 32 and 64 bits. That's how students learn this stuff.

So I wrote a small Rust engine for it, compiled it to WebAssembly, and put it behind BinaryCalc. The engine is open source and on npm and PyPI as binarycalc.

This post covers a few decisions that kept it small.

No wasm-bindgen

wasm-bindgen is great, but a handful of string-in, string-out functions doesn't need that much machinery. Instead, every export follows the same pattern:

  1. JavaScript calls alloc(len) and writes UTF-8 bytes into linear memory.
  2. JavaScript calls an export like convert(ptr, len, base).
  3. Rust takes ownership of the bytes, does the work and stores a JSON string.
  4. JavaScript reads that string back through output_ptr() and output_len().
#[no_mangle]
pub extern "C" fn alloc(len: usize) -> *mut u8 {
    let mut buffer = std::mem::ManuallyDrop::new(Vec::<u8>::with_capacity(len));
    buffer.as_mut_ptr()
}

#[no_mangle]
pub unsafe extern "C" fn convert(ptr: *mut u8, len: usize, base: u32) {
    let input = take(ptr, len); // Vec::from_raw_parts, so Rust frees it
    store(number::convert_json(&input, base));
}
Enter fullscreen mode Exit fullscreen mode

The JavaScript side is about 20 lines:

function call(run, input) {
  const bytes = encoder.encode(input);
  const pointer = exports.alloc(bytes.length);
  new Uint8Array(exports.memory.buffer, pointer, bytes.length).set(bytes);
  run(pointer, bytes.length);
  // Read memory only now: the call may have grown it.
  const output = new Uint8Array(exports.memory.buffer, exports.output_ptr(), exports.output_len());
  return JSON.parse(decoder.decode(output));
}
Enter fullscreen mode Exit fullscreen mode

That comment matters. If you create the Uint8Array view before the call and Rust grows memory, your view points at a detached buffer.

The release build uses opt-level = "s", LTO, panic = "abort" and strip, and it comes out at about 115 KB. That covers base conversion, UTF-8 text to binary, Morse code, LCM, GCF and factors.

Big numbers without a bignum crate

The converter takes integers up to 16,384 bits. Rather than pulling in a bignum library, the engine stores the number as a Vec<u32> of limbs and does schoolbook multiply-and-add for parsing and repeated division for output. For a converter that's plenty fast, and it keeps the binary small. Step-by-step working is only returned up to 32 bits, because nobody wants to read 16,000 division rows.

Errors are data, not exceptions

Every function returns JSON with ok: true or ok: false plus a readable message, for example "2" is not a valid binary digit. Binary uses only 0 and 1. The UI can show the message as it is, and bad input never throws across the WASM boundary.

Use it

npm install binarycalc
Enter fullscreen mode Exit fullscreen mode
import { loadEngine } from 'binarycalc';

const bc = await loadEngine();
bc.convert('42', 10).values;          // { 2: '101010', 8: '52', 10: '42', 16: '2A' }
bc.encodeText('Hi', 'space').binary;  // '01001000 01101001'
bc.encodeMorse('SOS').morse;          // '... --- ...'
Enter fullscreen mode Exit fullscreen mode

Or from Python, through wasmtime:

pip install binarycalc
Enter fullscreen mode Exit fullscreen mode
import binarycalc as bc
bc.convert("42", 10)["values"]["2"]   # '101010'
Enter fullscreen mode Exit fullscreen mode

If you've done the raw-pointer WASM approach differently, or have opinions on the bignum shortcut, I'd like to hear them in the comments.

Top comments (0)