wasm-ffi demo

Natural language detection using whatlang-rs

Detected Language:


Confidence: 100.0%

Portuguese Korean German Russian Italian English
Under the hood →

The main WebAssembly export here is detect, which takes a string pointer and gives back a pointer to a DetectResult struct. This function gets called each time the textarea is updated.

wasm-ffi wraps the call to detect. It writes the input string to memory before calling the WebAssembly function and it returns an object that can access the struct fields.

const $ = sel => document.querySelector(sel);
const textarea = $('textarea');
const DetectResult = new ffi.Struct({
lang: ffi.rust.string,
confidence: 'f64',
is_reliable: 'bool',
const whatlang = new ffi.Wrapper({
detect: [DetectResult, ['string']],
whatlang.fetch('whatlang.wasm').then(() => {
function update(str) {
const result = whatlang.detect(str);
$('#language').innerText = result.lang.value;
$('#reliable').className = (result.is_reliable) ? 'yes' : 'no';
$('#confidence').innerText = (result.confidence * 100).toFixed(1) + '%';
$('#bar').value = result.confidence * 100;
textarea.addEventListener('input', () => update(textarea.value));