This repository was archived by the owner on Aug 7, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathzstd.ts
More file actions
69 lines (58 loc) · 1.98 KB
/
Copy pathzstd.ts
File metadata and controls
69 lines (58 loc) · 1.98 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
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
import type { Codec, CodecConstructor } from "./types.js";
type WasmModule = typeof import("../pkg/rumcodecs-wasm-node/rumcodecs_wasm.js");
const DEFAULT_CLEVEL = 1;
const MAX_CLEVEL = 22;
let wasmModule: Promise<WasmModule> | null = null;
async function getModule(): Promise<WasmModule> {
if (!wasmModule) {
wasmModule = import("../pkg/rumcodecs-wasm-node/rumcodecs_wasm.js");
}
return wasmModule;
}
interface ZstdConfig {
level?: number;
}
const Zstd: CodecConstructor<ZstdConfig> = class Zstd implements Codec {
public static codecId = "zstd";
public static DEFAULT_CLEVEL = DEFAULT_CLEVEL;
public static MAX_CLEVEL = MAX_CLEVEL;
public level: number;
constructor(level = DEFAULT_CLEVEL) {
if (!Number.isInteger(level)) {
throw Error(`Invalid level "${level}". Must be an integer.`);
}
this.level = level;
}
static fromConfig({ level }: ZstdConfig): Zstd {
return new Zstd(level);
}
async encode(data: Uint8Array): Promise<Uint8Array> {
let level = this.level;
if (level <= 0) {
level = DEFAULT_CLEVEL;
}
if (level > MAX_CLEVEL) {
level = MAX_CLEVEL;
}
const m = await getModule();
return m.zstd_compress(data, level);
}
async decode(data: Uint8Array, out?: Uint8Array): Promise<Uint8Array> {
const m = await getModule();
const result = m.zstd_decompress(data);
// An empty result is how the WASM side reports failure, and a frame that
// really does hold nothing looks identical. The frame header settles it:
// only a frame declaring zero bytes may legitimately decode to nothing.
// A frame carrying no declared size at all (`undefined`) cannot be told
// apart, and erring toward an Error beats returning an untouched `out`.
if (result.length === 0 && m.zstd_declared_content_size(data) !== 0) {
throw new Error("Zstd decompression failed");
}
if (out !== undefined) {
out.set(result);
return out;
}
return result;
}
};
export default Zstd;