Table of content
What is this
The rules of the game are explained in my original post .
20th Challenge
Challenge
Calculate crc16-EN_13757 in Rust and create a webassembly package that can be run from javascript. The motivation here
is that crc is much simpler and faster in RUST.
Solution
mod utils ;
use wasm_bindgen :: prelude :: * ;
use crc16 ::{ EN_13757 , State };
use hex :: FromHexError ;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc" )]
#[global_allocator]
static ALLOC : wee_alloc :: WeeAlloc = wee_alloc :: WeeAlloc :: INIT ;
#[wasm_bindgen]
extern {
fn alert ( s : & str );
}
#[wasm_bindgen]
pub fn crc16_en_13757 ( s : & str ) -> String {
let a = hex :: decode ( & s );
match a {
Ok ( _ ) => { format! ( "{:#04x}" , State :: < EN_13757 > :: calculate ( & a .unwrap ()))},
Err ( _ ) => String :: from ( "Error calculating CRC16, invalid input." )
}
}
With a simple html
the web assembly is tested. A Hex string of 50 million charcters is calculated within 800ms
<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> hello-wasm example</title>
</head>
<body>
<script type= "module" >
import init , { crc16_en_13757 } from " ./assets/pkg/crc16_en_13757.js " ;
init ()
. then (() => {
const genRanHex = size => [... Array ( size )]. map (() => Math . floor ( Math . random () * 16 ). toString ( 16 )). join ( '' );
var input = genRanHex ( 50000000 );
let before = Date . now ();
var crc16 = crc16_en_13757 ( input );
let after = Date . now ();
alert ( after - before );
});
</script>
</body>
</html>
Result:
To see the full source see github .