Last active
February 16, 2018 01:19
-
-
Save abiodun0/2d4d7d4f3679b764f70c5f5ac4098f39 to your computer and use it in GitHub Desktop.
Greatest common divisor in '.wasm'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(lang_items)] | |
#![no_std] | |
#[no_mangle] | |
pub extern "C" fn gcd(mut n: i32, mut m: i32) -> i32 { | |
assert!(n != 0 && m != 0); | |
while m != 0 { | |
if m < n { | |
let t = m; | |
m = n; | |
n = t; | |
} | |
m = m % n; | |
} | |
n | |
} | |
// needed for no_std | |
#[lang = "panic_fmt"] | |
#[no_mangle] | |
pub extern fn rust_begin_panic(_msg: core::fmt::Arguments, | |
_file: &'static str, | |
_line: u32, | |
_column: u32) -> ! { | |
loop {} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset='utf-8'> | |
<title>wasm wasm wasm</title> | |
</head> | |
<body> | |
<form id='form'> | |
<div> | |
<label for='a'>Number A</label> | |
<input id='a' name='a' /> | |
</div> | |
<div> | |
<label for='b'>Number B</label> | |
<input id='b' name='b' /> | |
</div> | |
<div> | |
<button type='submit'>Compute</button> | |
</div> | |
<div id='result'></div> | |
</form> | |
<script> | |
const gcdWasm = fetch('gcd.wasm').then(response => | |
response.arrayBuffer() | |
).then(bytes => | |
WebAssembly.instantiate(bytes, {}) | |
).then(results => results.instance.exports.gcd); | |
const form = document.querySelector('#form') | |
const result = document.querySelector('#result') | |
form.addEventListener('submit', evt => { | |
evt.preventDefault() | |
const d = new FormData(form) | |
const a = parseInt(d.get('a'), 10) | |
const b = parseInt(d.get('b'), 10) | |
gcdWasm.then(fn => { | |
result.innerHTML = `The GCD of those two numbers is ${fn(a, b)}` | |
}) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment