phasm/examples/crc32.html
2022-08-20 18:00:20 +02:00

93 lines
2.4 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>Examples - CRC32</title>
</head>
<body>
<h1>Buffer</h1>
<a href="index.html">List</a> - <a href="crc32.py.html">Source</a> - <a href="crc32.wat.html">WebAssembly</a>
<div style="white-space: pre;" id="results"></div>
<script type="text/javascript" src="./include.js"></script>
<script type="text/javascript">
let importObject = {};
// Build up a JS version
var makeCRCTable = function(){
var c;
var crcTable = [];
for(var n =0; n < 256; n++){
c = n;
for(var k =0; k < 8; k++){
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
crcTable[n] = c;
}
return crcTable;
}
window.crcTable = makeCRCTable();
var crc32_js = function(i8arr) {
var crcTable = window.crcTable;
var crc = 0 ^ (-1);
for (var i = 0; i < i8arr.length; i++ ) {
crc = (crc >>> 8) ^ crcTable[(crc ^ i8arr[i]) & 0xFF];
}
return (crc ^ (-1)) >>> 0;
};
// Run a single test
function run_test(app, str)
{
// Cast to Uint32 in Javascript
let crc32_wasm = (offset) => (app.instance.exports.crc32(offset) >>> 0);
let data = Uint8Array.from(str.split('').map(x => x.charCodeAt()));
offset = alloc_bytes(app, data);
// Run once to get the result
// For some reason, the JS version takes 2ms on the first run
let wasm_result = crc32_wasm(offset);
let js_result = crc32_js(data);
let wasm_time = run_times(100, () => crc32_wasm(offset));
let js_time = run_times(100, () => crc32_js(data));
test_result((js_result == wasm_result) && ((js_time == 0) || (wasm_time < js_time)), {
'summary': 'crc32(' + (str
? (str.length < 64 ? '"' + str + '"' : '"' + str.substring(0, 64) + '..." (' + str.length + ')')
: '""') + ')',
'attributes': {
'str': str,
'wasm_result': wasm_result,
'wasm_time': wasm_time,
'js_result': js_result,
'js_time': js_time,
'speedup': (js_time == wasm_time) ? '-' : (js_time / wasm_time),
},
});
}
// Load WebAssembly, and run all tests
WebAssembly.instantiateStreaming(fetch('crc32.wasm'), importObject)
.then(app => {
run_test(app, "");
run_test(app, "a");
run_test(app, "Z");
run_test(app, "ab");
run_test(app, "abcdefghijklmnopqrstuvwxyz");
run_test(app, "The quick brown fox jumps over the lazy dog");
run_test(app, "The quick brown fox jumps over the lazy dog".repeat(1024)); // FIXME: Too slow :(
});
</script>
</body>
</html>