-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzstd_worker.mjs
More file actions
42 lines (41 loc) · 1.54 KB
/
zstd_worker.mjs
File metadata and controls
42 lines (41 loc) · 1.54 KB
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
const url=new URL('zstd.wasm',import.meta.url);
await (await fetch(url)).arrayBuffer();
const worker=await new Promise(r=>{
// For browsers that don't support type: module on workers (firefox < 114, safari < 15)
// const worker=new Worker(new URL('./zstd_worker_script.js',import.meta.url));
const worker=new Worker(new URL('./zstd_worker_script.mjs',import.meta.url),{type:'module'});
worker.onmessage=msg=>{
if(msg.data==='ready'){
worker.onmessage=null;
r(worker);
}
};
});
/**
* Decompresses an array of bytes compressed with Zstd compression.
* The compressed version is transferred to the worker and transferred back on completion.
* @param {Uint8Array} bytes
* @return {Promise<{compressed:Uint8Array,uncompressed:Uint8Array}>}
*/
const unzstd=(bytes)=>new Promise(r=>{
worker.onmessage=({data:{compressed,uncompressed}})=>{
worker.onmessage=null;
r({compressed,uncompressed});
}
worker.postMessage(bytes,[bytes.buffer]);
});
/**
* Compresses an array of bytes with Zstd compression.
* The uncompressed version is transferred to the worker and transferred back on completion.
* @param {Uint8Array} bytes
* @param {1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22} [level=22]
* @return {Promise<{compressed:Uint8Array,uncompressed:Uint8Array}>}
*/
const zstd=(bytes,level=22)=>new Promise(r=>{
worker.onmessage=({data:{compressed,uncompressed}})=>{
worker.onmessage=null;
r({compressed,uncompressed});
}
worker.postMessage({uncompressed:bytes,level},[bytes.buffer]);
});
export {unzstd,zstd};