Circle

05 Dec 2017 0 Comments

Files creation

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="utf-8">
      <title>WebAssembly</title>
      <script src="script.js"></script>
  </head>
  <body>
    radius:<br>
    <input type="number" id="radius" min="0"><br>
    diameter:<br>
    <input type="number" id="diameter" min="0"><br>
    perimeter:<br>
    <input type="number" id="perimeter" min="0"><br>
    area:<br>
    <input type="number" id="area" min="0"><br>
  </body>
</html>

window.onload = function() {
    window.exports = {};

    let radius = document.querySelector('#radius'),
        diameter = document.querySelector('#diameter'),
        perimeter = document.querySelector('#perimeter'),
        area = document.querySelector('#area');

    let imports = {
        set_params: (r, d, p, a) => {
            if (radius != document.activeElement)
                radius.value = r;

            if (diameter != document.activeElement)
                diameter.value = d;
            
            if (perimeter != document.activeElement)
                perimeter.value = p;
                
            if (area != document.activeElement)
                area.value = a;
        }
    };

    fetch('build/main.wasm')
    .then(response => response.arrayBuffer())
    .then(bytes => WebAssembly.instantiate(bytes, { env: imports }))
    .then(results => {
        exports = results.instance.exports;
        
        radius.oninput = () => exports.set_radius(radius.value);
        diameter.oninput = () => exports.set_diameter(diameter.value);
        perimeter.oninput = () => exports.set_perimeter(perimeter.value);
        area.oninput = () => exports.set_area(area.value);
    });
};

use std::os::raw::c_double;
use std::f64::consts::PI;

// These functions are provided by the runtime in env.imports js object
extern "C" {
    fn set_params(_: c_double, _: c_double, _: c_double, _: c_double);
}

#[no_mangle]
pub unsafe fn set_radius(r: c_double) {
    let d = 2.0 * r;
    let p = 2.0 * PI * r;
    let a = PI * r * r;
    set_params(r, d, p, a);
}

#[no_mangle]
pub unsafe fn set_diameter(d: c_double) {
    let r = d / 2.0;
    set_radius(r);
}

#[no_mangle]
pub unsafe fn set_perimeter(p: c_double) {
    let r = p / 2.0 / PI;
    set_radius(r);
}

#[no_mangle]
pub unsafe fn set_area(a: c_double) {
    let r = (a / PI).sqrt();
    set_radius(r);
}

Save this file as main.wasm in build folder.
Or generate this file by
rustc +nightly --target wasm32-unknown-unknown -O --crate-type=cdylib src\main.rs -o build\main.big.wasm

Result