-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
71 lines (58 loc) · 2.28 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright (c) 2018-present, Cruise LLC
//
// This source code is licensed under the Apache License, Version 2.0,
// found in the LICENSE file in the root directory of this source tree.
// You may not use this file except in compliance with the License.
const ModuleFactory = require("./wasm-lz4");
const ModulePromise = ModuleFactory();
let Module;
let context;
function ensureLoaded() {
if (!Module) {
throw new Error(
`wasm-lz4 has not finished loading. Please wait with "await decompress.isLoaded" before calling decompress`
);
}
}
module.exports = function decompress(src, destSize) {
ensureLoaded();
const srcSize = src.byteLength;
const srcPointer = Module._malloc(srcSize);
const destPointer = Module._malloc(destSize);
// create a view into the heap for our source buffer
const compressedHeap = new Uint8Array(Module.HEAPU8.buffer, srcPointer, srcSize);
// copy source buffer into the heap
compressedHeap.set(src);
// initialize the decompression context only once - its reusable
context = context || Module._createDecompressionContext();
// call the C function to decompress the frame
const resultSize = Module._decompressFrame(context, destPointer, destSize, srcPointer, srcSize);
try {
if (resultSize === -1) {
throw new Error("Error during decompression");
}
// copy destination buffer out of the heap back into js land
const output = Buffer.allocUnsafe(resultSize);
Buffer.from(Module.HEAPU8.buffer).copy(output, 0, destPointer, destPointer + resultSize);
return output;
} finally {
// free the source buffer memory
Module._free(srcPointer);
// free destination buffer on the heap
Module._free(destPointer);
}
};
// export a promise a consumer can listen to to wait
// for the module to finish loading
// module loading is async and can take
// several hundred milliseconds...accessing the module
// before it is loaded will throw an error
module.exports.isLoaded = ModulePromise.then((mod) => mod["ready"].then(() => {}));
// Wait for the promise returned from ModuleFactory to resolve
ModulePromise.then((mod) => {
Module = mod;
// export the Module object for testing purposes _only_
if (typeof process === "object" && process.env.NODE_ENV === "test") {
module.exports.__module = Module;
}
});