emcc -o zstd.js -O0 \
-s WASM=1 \
-s "MODULARIZE=1" \
-s EXPORTED_FUNCTIONS="['_ZSTD_isError', '_ZSTD_getFrameContentSize', '_ZSTD_decompress']" \
-s EXTRA_EXPORTED_RUNTIME_METHODS="['cwrap','ccall']" \
-s 'EXPORT_NAME="ZstdLib"' \
lib/libzstd.bc
Created
July 12, 2018 17:52
-
-
Save otmb/dc79d23d75c75302f43450bce6a2f640 to your computer and use it in GitHub Desktop.
WebAssemblyをNodejs環境なしで試す
This file contains 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
<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> |
This file contains 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
"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