/** * Compression codecs of JData arrays (_ArrayZipType_): zlib and gzip (Node's zlib, or pako), * lz4/lz4hc (raw LZ4 blocks, as zmat writes them; built in), base64, and any codec registered * with registerCodec (lzma, zstd, blosc2, ... from other libraries); byte shuffling. * * Copyright (c) 2019-2026 Qianqian Fang . BSD 3-clause license. */ import * as pako from 'pako'; import { nodeZlibModule } from './zlibmt'; export interface Codec { /** compress bytes; opts: {level, ...} */ encode?: (bytes: Uint8Array, opts: any) => Uint8Array; /** decompress bytes; size: the expected size in bytes, when known */ decode: (bytes: Uint8Array, size: number | undefined, opts: any) => Uint8Array; } declare const process: any; const NZ = nodeZlibModule(); /** A plain Uint8Array copy of bytes (Node's Buffer.slice gives views into shared memory). */ export function own(b: Uint8Array): Uint8Array { // (not b.slice(): on a Buffer it gives a Buffer, whose toJSON is {type: 'Buffer', data}) return new Uint8Array(b); } /** Bytes made here and given away, which nothing else refers to (the decoder keeps them as * they are, without a copy). */ const OWNED = new WeakSet(); export function giveAway(b: Uint8Array): Uint8Array { if (b.constructor !== Uint8Array) { b = new Uint8Array(b.buffer, b.byteOffset, b.byteLength); } OWNED.add(b); return b; } /** Whether b is bytes made here, all of its buffer (and forgets it: it is taken once). */ export function takeOwned(b: Uint8Array): boolean { return OWNED.delete(b) && b.byteOffset === 0 && b.byteLength === b.buffer.byteLength; } function zlibCodec(gz: boolean): Codec { return { encode: (b, o) => { const level = o && o.level !== undefined ? o.level : 6; if (NZ) { return own(gz ? NZ.gzipSync(b, { level }) : NZ.deflateSync(b, { level })); } return gz ? pako.gzip(b, { level }) : pako.deflate(b, { level }); }, decode: (b) => { if (NZ) { return giveAway(gz ? NZ.gunzipSync(b) : NZ.inflateSync(b)); } return giveAway(gz ? pako.ungzip(b) : pako.inflate(b)); } }; } // ---- base64 ------------------------------------------------------------------------------------- const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; const B64INV = new Int16Array(256).fill(-1); for (let k = 0; k < 64; k++) { B64INV[B64.charCodeAt(k)] = k; } B64INV['-'.charCodeAt(0)] = 62; // (base64url) B64INV['_'.charCodeAt(0)] = 63; const B64ENC = new Uint8Array(64); for (let k = 0; k < 64; k++) { B64ENC[k] = B64.charCodeAt(k); } declare const Buffer: any, TextDecoder: any; const NODE_BUFFER: any = typeof process !== 'undefined' && process.versions && process.versions.node && typeof Buffer === 'function' && typeof Buffer.from === 'function' ? Buffer : null; const TD: any = typeof TextDecoder !== 'undefined' ? new TextDecoder() : null; /** Bytes of base64 text (whitespace, padding and the URL alphabet accepted). */ export function base64ToBytes(s: string | Uint8Array): Uint8Array { const n = s.length; if (NODE_BUFFER && typeof s === 'string' && n >= 8192) { // Node's decoder, when it took every character (it skips the ones it does not know; and // from 8 kB its buffers are not slices of its shared pool) const pad = s.charCodeAt(n - 1) === 61 ? (s.charCodeAt(n - 2) === 61 ? 2 : 1) : 0; const b = NODE_BUFFER.from(s, 'base64'); if (b.length === Math.floor((n - pad) * 3 / 4)) { return giveAway(b); } } const out = new Uint8Array(Math.floor(n * 3 / 4) + 3); const str = typeof s === 'string'; let i = 0, k = 0, acc = 0, bits = 0; while (i < n) { // whole groups of four alphabet characters (all of the text but the end, usually) if (bits === 0) { if (str) { const t = s as string; for (; i + 4 <= n; i += 4) { const c0 = t.charCodeAt(i), c1 = t.charCodeAt(i + 1), c2 = t.charCodeAt(i + 2), c3 = t.charCodeAt(i + 3); if ((c0 | c1 | c2 | c3) > 255) { break; } const v0 = B64INV[c0], v1 = B64INV[c1], v2 = B64INV[c2], v3 = B64INV[c3]; if ((v0 | v1 | v2 | v3) < 0) { break; } out[k] = (v0 << 2) | (v1 >> 4); out[k + 1] = ((v1 & 15) << 4) | (v2 >> 2); out[k + 2] = ((v2 & 3) << 6) | v3; k += 3; } } else { const t = s as Uint8Array; for (; i + 4 <= n; i += 4) { const v0 = B64INV[t[i]], v1 = B64INV[t[i + 1]], v2 = B64INV[t[i + 2]], v3 = B64INV[t[i + 3]]; if ((v0 | v1 | v2 | v3) < 0) { break; } out[k] = (v0 << 2) | (v1 >> 4); out[k + 1] = ((v1 & 15) << 4) | (v2 >> 2); out[k + 2] = ((v2 & 3) << 6) | v3; k += 3; } } if (i >= n) { break; } } // a character at a time (padding, white space, line breaks), until a group boundary const c = str ? (s as string).charCodeAt(i) : (s as Uint8Array)[i]; i++; const v = c < 256 ? B64INV[c] : -1; if (v < 0) { if (c === 61 || c === 32 || c === 10 || c === 13 || c === 9) { // = and white space continue; } throw new Error('jdata: invalid base64 character code ' + c); } acc = ((acc << 6) | v) & 0xffffff; bits += 6; if (bits >= 8) { bits -= 8; out[k++] = (acc >> bits) & 0xff; } } return giveAway(k === out.length ? out : out.slice(0, k)); } /** Base64 text of bytes. */ export function bytesToBase64(b: Uint8Array): string { if (NODE_BUFFER) { return NODE_BUFFER.from(b.buffer, b.byteOffset, b.byteLength).toString('base64'); } const n = b.length; const out = new Uint8Array(4 * Math.ceil(n / 3)); let i = 0, k = 0; for (; i + 2 < n; i += 3, k += 4) { const x = (b[i] << 16) | (b[i + 1] << 8) | b[i + 2]; out[k] = B64ENC[x >> 18]; out[k + 1] = B64ENC[(x >> 12) & 63]; out[k + 2] = B64ENC[(x >> 6) & 63]; out[k + 3] = B64ENC[x & 63]; } if (i < n) { const x = (b[i] << 16) | (i + 1 < n ? b[i + 1] << 8 : 0); out[k] = B64ENC[x >> 18]; out[k + 1] = B64ENC[(x >> 12) & 63]; out[k + 2] = i + 1 < n ? B64ENC[(x >> 6) & 63] : 61; out[k + 3] = 61; } return asciiText(out); } /** The string of ASCII bytes. */ function asciiText(b: Uint8Array): string { if (TD) { return TD.decode(b); } const parts: string[] = []; for (let k = 0; k < b.length; k += 8192) { parts.push(String.fromCharCode.apply(null, b.subarray(k, k + 8192) as any)); } return parts.join(''); } // ---- LZ4 blocks --------------------------------------------------------------------------------- /** Decompresses a raw LZ4 block (no frame), as zmat's lz4 and lz4hc write. */ export function lz4Decode(src: Uint8Array, size?: number): Uint8Array { let cap = size !== undefined ? size : Math.max(64, src.length * 4); let out = new Uint8Array(cap); let ip = 0, op = 0; const n = src.length; const grow = (need: number) => { if (op + need <= cap) { return; } if (size !== undefined) { throw new Error('jdata: lz4 data larger than its size'); } while (cap < op + need) { cap *= 2; } const o = new Uint8Array(cap); o.set(out.subarray(0, op)); out = o; }; while (ip < n) { const token = src[ip++]; let lit = token >> 4; if (lit === 15) { let b; do { b = src[ip++]; lit += b; } while (b === 255 && ip < n); } if (ip + lit > n) { throw new Error('jdata: truncated lz4 data'); } grow(lit); if (lit < 32) { // (short runs: a loop beats making a subarray) for (let e = ip + lit; ip < e;) { out[op++] = src[ip++]; } } else { out.set(src.subarray(ip, ip + lit), op); ip += lit; op += lit; } if (ip >= n) { break; // the last sequence has no match } const off = src[ip] | (src[ip + 1] << 8); ip += 2; if (off === 0 || off > op) { throw new Error('jdata: invalid lz4 offset'); } let len = token & 15; if (len === 15) { let b; do { b = src[ip++]; len += b; } while (b === 255 && ip < n); } len += 4; grow(len); let from = op - off; if (len >= 32 && off >= len) { out.copyWithin(op, from, from + len); op += len; } else if (len >= 64) { // (a repeating pattern: copies of the period, each twice as long as the last) let done = 0; while (done < len) { const c = Math.min(len - done, off + done); out.copyWithin(op + done, from, from + c); done += c; } op += len; } else { for (let k = 0; k < len; k++) { out[op++] = out[from++]; } } } if (size !== undefined && op !== size) { throw new Error('jdata: lz4 data of ' + op + ' bytes, ' + size + ' expected'); } return giveAway(op === out.length ? out : out.slice(0, op)); } /** Compresses bytes into a raw LZ4 block (greedy, a 64k-entry hash table, LZ4's skipping). */ export function lz4Encode(src: Uint8Array): Uint8Array { const n = src.length; const out = new Uint8Array(n + Math.ceil(n / 255) + 16); const table = new Int32Array(65536).fill(-1); let ip = 0, anchor = 0, op = 0; const putLen = (x: number) => { while (x >= 255) { out[op++] = 255; x -= 255; } out[op++] = x; }; const emit = (litEnd: number, matchLen: number, offset: number) => { const lit = litEnd - anchor; const tok = op++; out[tok] = (Math.min(lit, 15) << 4) | (matchLen < 0 ? 0 : Math.min(matchLen - 4, 15)); if (lit >= 15) { putLen(lit - 15); } if (lit < 32) { for (let k = anchor; k < litEnd; k++) { out[op++] = src[k]; } } else { out.set(src.subarray(anchor, litEnd), op); op += lit; } if (matchLen >= 0) { out[op++] = offset & 255; out[op++] = offset >> 8; if (matchLen - 4 >= 15) { putLen(matchLen - 4 - 15); } } }; // (the last 5 bytes are literals, and a match starts at least 12 bytes before the end) const limit = n - 12, end = n - 5; const v = new DataView(src.buffer, src.byteOffset, src.byteLength); let misses = 0; while (ip < limit) { const seq = v.getUint32(ip, true); const h = Math.imul(seq, -1640531535) >>> 16; const ref = table[h]; table[h] = ip; if (ref >= 0 && ip - ref < 65536 && v.getUint32(ref, true) === seq) { // the match, back over the pending literals and on, four bytes at a time let s = ip, r = ref; while (s > anchor && r > 0 && src[s - 1] === src[r - 1]) { s--; r--; } let p = ip + 4, q = ref + 4; while (p + 4 <= end && v.getUint32(p, true) === v.getUint32(q, true)) { p += 4; q += 4; } while (p < end && src[p] === src[q]) { p++; q++; } emit(s, p - s, ip - ref); ip = p; anchor = ip; misses = 0; continue; } // (as LZ4 itself: longer steps through data that does not compress) ip += 1 + (misses++ >> 6); } emit(n, -1, 0); return out.slice(0, op); } // ---- byte shuffle ------------------------------------------------------------------------------- /** Groups the k-th bytes of every element of width w together (as Blosc and zmat). */ export function shuffle(b: Uint8Array, w: number): Uint8Array { const n = Math.floor(b.length / w); if (w <= 1 || n < 1) { return b; } const out = new Uint8Array(b.length); for (let k = 0; k < w; k++) { for (let i = 0; i < n; i++) { out[k * n + i] = b[i * w + k]; } } out.set(b.subarray(n * w), n * w); return out; } export function unshuffle(b: Uint8Array, w: number): Uint8Array { const n = Math.floor(b.length / w); if (w <= 1 || n < 1) { return b; } const out = new Uint8Array(b.length); for (let k = 0; k < w; k++) { for (let i = 0; i < n; i++) { out[i * w + k] = b[k * n + i]; } } out.set(b.subarray(n * w), n * w); return giveAway(out); } // ---- the registry ------------------------------------------------------------------------------- const BASE64: Codec = { encode: (b) => { const s = bytesToBase64(b); const o = new Uint8Array(s.length); for (let k = 0; k < s.length; k++) { o[k] = s.charCodeAt(k); } return o; }, decode: (b) => base64ToBytes(b) }; /** The built-in zlib and gzip codecs (the async functions run these on threads). */ export const ZLIB_CODEC: Codec = zlibCodec(false); export const GZIP_CODEC: Codec = zlibCodec(true); const CODECS: { [name: string]: Codec } = { zlib: ZLIB_CODEC, gzip: GZIP_CODEC, lz4: { encode: (b) => lz4Encode(b), decode: (b, size) => lz4Decode(b, size) }, lz4hc: { encode: (b) => lz4Encode(b), decode: (b, size) => lz4Decode(b, size) }, base64: BASE64 }; /** Adds or replaces a codec: registerCodec('zstd', {decode: (bytes, size) => ..., encode: ...}). */ export function registerCodec(name: string, codec: Codec): void { CODECS[name.toLowerCase()] = codec; } export function getCodec(name: string, extra?: { [name: string]: Codec }): Codec { const key = String(name).toLowerCase(); const c = (extra && extra[key]) || CODECS[key]; if (!c) { throw new Error('jdata: no codec for _ArrayZipType_ "' + name + '": register one with registerCodec("' + key + '", {decode, encode}) (lzma, zstd, blosc2 ... are not built in)'); } return c; } /** Whether name is the built-in base64 codec here (not one registered in its place). */ export function isBuiltinBase64(name: string, extra?: { [name: string]: Codec }): boolean { return getCodec(name, extra) === BASE64; } export function codecNames(): string[] { return Object.keys(CODECS); }