/** * Export compression functionality for IAVL trees. * * Implements compression techniques to reduce export size: * - Branch keys are skipped (can be derived during import) * - Leaf keys are delta-encoded compared to previous leaf * - Branch node versions are delta-encoded compared to max version in children * * Based on Go IAVL compress.go */ import type { ExportNode, } from "./types.js"; /** * Interface for node exporters. * Based on Go compress.go lines 8-10 */ export interface NodeExporter { next(): Promise } /** * Interface for node importers. * Based on Go compress.go lines 12-14 */ export interface NodeImporter { add(node: ExportNode): Promise } /** * CompressExporter wraps the normal exporter to apply compressions: * - Branch keys are skipped * - Leaf keys are encoded with delta compared with the previous leaf * - Branch node versions are encoded with delta compared with max version in children * * Based on Go compress.go lines 16-30 */ export class CompressExporter implements NodeExporter { private inner: NodeExporter; private lastKey: Uint8Array = new Uint8Array(0); private versionStack: bigint[] = []; constructor(exporter: NodeExporter) { this.inner = exporter; } async next(): Promise { const node = await this.inner.next(); if (!node) { return null; } // Create a copy to avoid modifying the original const compressedNode: ExportNode = { key: node.key, value: node.value, version: node.version, height: node.height, }; if (node.height === 0) { // Apply delta encoding to leaf keys const encoded = deltaEncode(node.key, this.lastKey); this.lastKey = node.key; compressedNode.key = encoded; this.versionStack.push(node.version); } else { // Branch keys can be derived on the fly when importing, safe to skip compressedNode.key = new Uint8Array(0); // Delta encode the version const len = this.versionStack.length; const maxVersion = maxBigInt( this.versionStack[len - 1], this.versionStack[len - 2], ); this.versionStack = this.versionStack.slice(0, len - 1); this.versionStack[len - 2] = node.version; compressedNode.version = node.version - maxVersion; } return compressedNode; } } /** * CompressImporter wraps the normal importer to decompress before import. * * Based on Go compress.go lines 57-69 */ export class CompressImporter implements NodeImporter { private inner: NodeImporter; private lastKey: Uint8Array = new Uint8Array(0); private minKeyStack: Uint8Array[] = []; private versionStack: bigint[] = []; constructor(importer: NodeImporter) { this.inner = importer; } async add(node: ExportNode): Promise { // Create a copy to avoid modifying the original const decompressedNode: ExportNode = { key: node.key, value: node.value, version: node.version, height: node.height, }; if (node.height === 0) { // Decode the delta-encoded key const key = deltaDecode(node.key, this.lastKey); decompressedNode.key = key; this.lastKey = key; this.minKeyStack.push(key); this.versionStack.push(decompressedNode.version); } else { // Use the min-key in right branch as the node key decompressedNode.key = this.minKeyStack[this.minKeyStack.length - 1]; // Leave the min-key in left branch in the stack this.minKeyStack = this.minKeyStack.slice(0, this.minKeyStack.length - 1); // Decode branch node version const len = this.versionStack.length; const maxVersion = maxBigInt( this.versionStack[len - 1], this.versionStack[len - 2], ); decompressedNode.version = node.version + maxVersion; this.versionStack = this.versionStack.slice(0, len - 1); this.versionStack[len - 2] = decompressedNode.version; } return this.inner.add(decompressedNode); } } /** * Delta encode a key based on shared prefix with previous key. * Returns: [shared_prefix_length][remaining_bytes] * * Based on Go compress.go lines 98-103 */ function deltaEncode(key: Uint8Array, lastKey: Uint8Array): Uint8Array { const shared = diffOffset(lastKey, key); // Encode shared length as varint const sharedBytes = encodeUvarint(shared); // Combine varint length with remaining key bytes const result = new Uint8Array(sharedBytes.length + key.length - shared); result.set(sharedBytes, 0); result.set(key.slice(shared), sharedBytes.length); return result; } /** * Decode a delta-encoded key. * * Based on Go compress.go lines 105-120 */ function deltaDecode(encoded: Uint8Array, lastKey: Uint8Array): Uint8Array { const [shared, bytesRead] = decodeUvarint(encoded); if (bytesRead <= 0) { throw new Error(`uvarint parse failed ${bytesRead}`); } const key = encoded.slice(bytesRead); if (shared === 0) { return key; } // Reconstruct the key using shared prefix from lastKey const newKey = new Uint8Array(shared + key.length); newKey.set(lastKey.slice(0, shared), 0); newKey.set(key, shared); return newKey; } /** * Returns the index of first byte that's different in two byte slices. * * Based on Go compress.go lines 122-136 */ function diffOffset(a: Uint8Array, b: Uint8Array): number { const minLen = Math.min(a.length, b.length); for (let i = 0; i < minLen; i++) { if (a[i] !== b[i]) { return i; } } return minLen; } /** * Returns the maximum of two BigInt values. * * Based on Go compress.go lines 139-144 */ function maxBigInt(a: bigint, b: bigint): bigint { return a > b ? a : b; } /** * Encode an unsigned integer as varint (variable-length encoding). * Compatible with Go's binary.PutUvarint. */ function encodeUvarint(value: number): Uint8Array { const bytes: number[] = []; while (value >= 0x80) { bytes.push((value & 0x7f) | 0x80); value >>>= 7; } bytes.push(value & 0x7f); return new Uint8Array(bytes); } /** * Decode an unsigned varint from bytes. * Returns [value, bytesRead]. If error, bytesRead will be <= 0. * Compatible with Go's binary.Uvarint. */ function decodeUvarint(bytes: Uint8Array): [number, number] { let value = 0; let shift = 0; for (let i = 0; i < bytes.length; i++) { const b = bytes[i]; if (shift >= 64) { // Overflow return [0, -1]; } if (b < 0x80) { // Last byte value |= (b << shift); return [value, i + 1]; } value |= ((b & 0x7f) << shift); shift += 7; } // Incomplete varint return [0, 0]; } /** * Create a compress exporter that wraps an async iterable exporter. */ export function createCompressExporter( exporter: AsyncIterable, ): AsyncIterable { const iterator = exporter[Symbol.asyncIterator](); const wrapper: NodeExporter = { async next(): Promise { const result = await iterator.next(); return result.done ? null : result.value; }, }; const compressor = new CompressExporter(wrapper); return { async* [Symbol.asyncIterator](): AsyncIterator { let node: ExportNode | null; while ((node = await compressor.next()) !== null) { yield node; } }, }; }