Skip to content

Instantly share code, notes, and snippets.

@otmb
Created July 12, 2018 17:52
Show Gist options
  • Save otmb/dc79d23d75c75302f43450bce6a2f640 to your computer and use it in GitHub Desktop.
Save otmb/dc79d23d75c75302f43450bce6a2f640 to your computer and use it in GitHub Desktop.
WebAssemblyをNodejs環境なしで試す
<html>
<head>
<title>Zstd wasm test</title>
<script type='text/javascript' src="./zstd.js"></script>
<script type="text/javascript" src="./run.js"></script>
</head>
<body>
<script type="text/javascript">
ZstdLib().then(function(Module) {
var zstd = new ZstdCodec(Module);
// === test ===
// fetch('test.txt.zst')
// .then(function(response) {
// return response.arrayBuffer();
// })
// .then(function(bytes) {
// var res = zstd.decompress(new Uint8Array(bytes));
// });
});
</script>
</body>
</html>
"use strict";
class ZstdCodec {
constructor(Module) {
this.zstd = Module;
this.ZSTD_isError = this.zstd.cwrap('ZSTD_isError', 'number', ['number']);
this.ZSTD_getFrameContentSize = this.zstd.cwrap('ZSTD_getFrameContentSize', 'number', ['array', 'number']);
this.ZSTD_decompress = this.zstd.cwrap('ZSTD_decompress', 'number', ['number', 'number', 'array', 'number']);
}
isError(zstd_rc) {
return this.ZSTD_isError(zstd_rc);
}
getFrameContentSize(zstd_bytes) {
const content_size = this.ZSTD_getFrameContentSize(zstd_bytes, zstd_bytes.length);
const content_size_limit = 1 * 1024 * 1024;
return content_size <= content_size_limit ? content_size : null;
}
decompress(zstd_bytes) {
console.log(zstd_bytes);
const content_size = this.getFrameContentSize(zstd_bytes);
if (!content_size) return null;
const heap = this.zstd._malloc(content_size);
try {
const decompress_rc = this.ZSTD_decompress(heap, content_size, zstd_bytes, zstd_bytes.length);
if (this.isError(decompress_rc) || decompress_rc != content_size) return null;
return new Uint8Array(this.zstd.HEAPU8.buffer, heap, content_size);
} finally {
this.zstd._free(heap);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment