/** * Encoding utilities for IAVL tree serialization. * Implements varint encoding compatible with Go's encoding/binary package. */ /** * Maximum value for various integer types */ const MAX_VARINT_LEN_64 = 10; // Maximum bytes needed for a 64-bit varint /** * Encodes an unsigned integer as a varint. * Compatible with Go's binary.PutUvarint. * Use this for lengths and other unsigned values. * * @param value - The unsigned integer to encode (must be non-negative) * @returns Uint8Array containing the unsigned varint * @throws Error if value is negative */ export function encodeUvarint(value: number | bigint): Uint8Array { if (typeof value === "number") { if (value < 0) throw new Error("encodeUvarint: value must be non-negative"); if (!Number.isSafeInteger(value)) throw new Error("encodeUvarint: value exceeds safe integer range"); // Fast path for small values if (value < 0x80) { return new Uint8Array([value]); } const bytes: number[] = []; let n = value; while (n >= 0x80) { bytes.push((n & 0x7F) | 0x80); n = Math.floor(n / 128); } bytes.push(n); return new Uint8Array(bytes); } else { // Handle bigint if (value < 0n) throw new Error("encodeUvarint: value must be non-negative"); if (value < 0x80n) { return new Uint8Array([Number(value)]); } const bytes: number[] = []; let n = value; while (n >= 0x80n) { bytes.push(Number(n & 0x7Fn) | 0x80); n >>= 7n; } bytes.push(Number(n)); return new Uint8Array(bytes); } } /** * Encodes a signed integer as a varint using ZigZag encoding. * Compatible with Go's binary.PutVarint. * Use this for tree metadata (height, size, version, nonces). * * ZigZag encoding maps signed integers to unsigned integers: * 0 → 0, -1 → 1, 1 → 2, -2 → 3, 2 → 4, ... * * Formula: (n << 1) ^ (n >> 63) for int64 * This is equivalent to: n >= 0 ? n * 2 : (-n * 2) - 1 * * @param value - The signed integer to encode * @returns Uint8Array containing the ZigZag-encoded varint */ export function encodeVarint(value: number | bigint): Uint8Array { if (typeof value === "number") { if (!Number.isSafeInteger(value)) throw new Error("encodeVarint: value exceeds safe integer range"); // ZigZag encode: map signed to unsigned // (n << 1) ^ (n >> 31) for 32-bit // For JS numbers, simulate with: n >= 0 ? n * 2 : (-n * 2) - 1 const zigzag = value >= 0 ? value * 2 : (-value * 2) - 1; // Now encode as unsigned varint if (zigzag < 0x80) { return new Uint8Array([zigzag]); } const bytes: number[] = []; let n = zigzag; while (n >= 0x80) { bytes.push((n & 0x7F) | 0x80); n = Math.floor(n / 128); } bytes.push(n); return new Uint8Array(bytes); } else { // Handle bigint with proper ZigZag encoding // Ensure value is actually a bigint if (typeof value !== 'bigint') { throw new Error(`encodeVarint: expected bigint but got ${typeof value}: ${value}`); } // ZigZag encode: map signed to unsigned // For positive: n << 1 // For negative: (abs(n) << 1) - 1 let zigzag: bigint; if (value >= 0n) { zigzag = value << 1n; } else { const absValue = value * BigInt(-1); zigzag = (absValue << 1n) - 1n; } if (zigzag < 0x80n) { return new Uint8Array([Number(zigzag)]); } const bytes: number[] = []; let n = zigzag; while (n >= 0x80n) { bytes.push(Number(n & 0x7Fn) | 0x80); n >>= 7n; } bytes.push(Number(n)); return new Uint8Array(bytes); } } /** * Decodes an unsigned varint from a Uint8Array. * Compatible with Go's binary.Uvarint. * Use this for lengths and other unsigned values. * * @param bytes - The byte array to decode from * @param offset - Starting offset in the array (default: 0) * @returns Object with decoded value and number of bytes read * @throws Error if the varint is malformed or too long */ export function decodeUvarint(bytes: Uint8Array, offset = 0): { value: number bytesRead: number } { let value = 0n; let shift = 0n; let bytesRead = 0; while (offset + bytesRead < bytes.length) { const byte = bytes[offset + bytesRead]; bytesRead++; if (bytesRead > MAX_VARINT_LEN_64) { throw new Error("decodeUvarint: varint too long"); } // Add the lower 7 bits to the value using BigInt for precision value |= BigInt(byte & 0x7F) << shift; // Check if this is the last byte (high bit not set) if ((byte & 0x80) === 0) { // Convert to number and check if it's within safe integer range const numValue = Number(value); if (!Number.isSafeInteger(numValue)) { throw new Error("decodeUvarint: value exceeds safe integer range"); } return { value: numValue, bytesRead, }; } shift += 7n; } throw new Error("decodeUvarint: unexpected end of data"); } /** * Decodes a ZigZag-encoded varint from a Uint8Array. * Compatible with Go's binary.Varint (signed with ZigZag encoding). * Use this for tree metadata (height, size, version, nonces). * * ZigZag decoding: (n >>> 1) ^ -(n & 1) * Or: n even ? n/2 : -(n+1)/2 * * @param bytes - The byte array to decode from * @param offset - Starting offset in the array (default: 0) * @returns Object with decoded value and number of bytes read * @throws Error if the varint is malformed or too long */ export function decodeVarint(bytes: Uint8Array, offset = 0): { value: number bytesRead: number } { // First decode as unsigned varint let unsignedValue = 0n; let shift = 0n; let bytesRead = 0; while (offset + bytesRead < bytes.length) { const byte = bytes[offset + bytesRead]; bytesRead++; if (bytesRead > MAX_VARINT_LEN_64) { throw new Error("decodeVarint: varint too long"); } // Add the lower 7 bits to the value using BigInt for precision unsignedValue |= BigInt(byte & 0x7F) << shift; // Check if this is the last byte (high bit not set) if ((byte & 0x80) === 0) { // ZigZag decode: (n >>> 1) ^ -(n & 1) const decoded = (unsignedValue >> 1n) ^ -(unsignedValue & 1n); // Convert to number and check if it's within safe integer range const numValue = Number(decoded); if (!Number.isSafeInteger(numValue)) { throw new Error("decodeVarint: value exceeds safe integer range, use decodeVarintBigInt"); } return { value: numValue, bytesRead, }; } shift += 7n; } throw new Error("decodeVarint: unexpected end of data"); } /** * Decodes a ZigZag-encoded varint from a Uint8Array as a BigInt. * Compatible with Go's binary.Varint (signed with ZigZag encoding). * Use this for values that may exceed Number.MAX_SAFE_INTEGER. * * @param bytes - The byte array to decode from * @param offset - Starting offset in the array (default: 0) * @returns Object with decoded value and number of bytes read * @throws Error if the varint is malformed or too long */ export function decodeVarintBigInt(bytes: Uint8Array, offset = 0): { value: bigint bytesRead: number } { // First decode as unsigned varint let unsignedValue = 0n; let shift = 0n; let bytesRead = 0; while (offset + bytesRead < bytes.length) { const byte = bytes[offset + bytesRead]; bytesRead++; if (bytesRead > MAX_VARINT_LEN_64) { throw new Error("decodeVarintBigInt: varint too long"); } // Add the lower 7 bits to the value unsignedValue |= BigInt(byte & 0x7F) << shift; // Check if this is the last byte (high bit not set) if ((byte & 0x80) === 0) { // ZigZag decode: (n >>> 1) ^ -(n & 1) const decoded = (unsignedValue >> 1n) ^ -(unsignedValue & 1n); return { value: decoded, bytesRead, }; } shift += 7n; } throw new Error("decodeVarintBigInt: unexpected end of data"); } /** * Decodes a length-prefixed byte array from a Uint8Array. * Compatible with Go's encoding.DecodeBytes. * * @param bytes - The byte array to decode from * @param offset - Starting offset in the array (default: 0) * @returns Object with decoded bytes and total bytes read * @throws Error if the data is malformed or incomplete */ export function decodeBytes(bytes: Uint8Array, offset = 0): { bytes: Uint8Array bytesRead: number } { // Decode the length prefix (UNSIGNED - uses EncodeUvarint in Go) const { value: length, bytesRead: lengthBytes, } = decodeUvarint(bytes, offset); const start = offset + lengthBytes; const end = start + length; // Verify we have enough bytes if (end > bytes.length) { throw new Error(`Insufficient bytes: need ${end}, have ${bytes.length}`); } // Extract the byte slice const result = bytes.slice(start, end); return { bytes: result, bytesRead: lengthBytes + length, }; } /** * Encodes a byte array with a length prefix. * Compatible with Go's encoding.EncodeBytes. * Uses UNSIGNED varint for length (encodeUvarint). * * @param bytes - The byte array to encode * @returns Uint8Array containing the length prefix followed by the bytes */ export function encodeBytes(bytes: Uint8Array): Uint8Array { const lengthVarint = encodeUvarint(bytes.length); const result = new Uint8Array(lengthVarint.length + bytes.length); result.set(lengthVarint, 0); result.set(bytes, lengthVarint.length); return result; } /** * Calculates the encoded size of a byte array (length prefix + data). * Compatible with Go's encoding.EncodeBytesSize. * Uses UNSIGNED varint length for the length prefix. * * @param bytes - The byte array to calculate size for * @returns Number of bytes needed to encode the array with length prefix */ export function encodedBytesSize(bytes: Uint8Array): number { return uvarintLength(bytes.length) + bytes.length; } /** * Calculates the length of an unsigned varint encoding for a given value. * Compatible with Go's binary.PutUvarint. * * @param value - The value to calculate encoding length for (must be non-negative) * @returns Number of bytes needed to encode the value */ export function uvarintLength(value: number | bigint): number { if (typeof value === "number") { if (value < 0) throw new Error("uvarintLength: value must be non-negative"); if (value < 0x80) return 1; if (value < 0x4000) return 2; if (value < 0x200000) return 3; if (value < 0x10000000) return 4; // For larger values, calculate precisely let len = 0; let n = value; while (n > 0) { len++; n >>>= 7; } return len; } else { if (value < 0n) throw new Error("uvarintLength: value must be non-negative"); if (value < 0x80n) return 1; let len = 0; let n = value; while (n > 0n) { len++; n >>= 7n; } return len; } } /** * Calculates the length of a ZigZag-encoded varint for a given signed value. * Compatible with Go's binary.PutVarint. * * @param value - The signed value to calculate encoding length for * @returns Number of bytes needed to encode the value with ZigZag encoding */ export function varintLength(value: number | bigint): number { if (typeof value === "number") { if (!Number.isSafeInteger(value)) throw new Error("varintLength: value exceeds safe integer range"); // ZigZag encode first, then calculate length const zigzag = value >= 0 ? value * 2 : (-value * 2) - 1; return uvarintLength(zigzag); } else { // ZigZag encode first, then calculate length const zigzag = value >= 0n ? value << 1n : ((~value) << 1n) | 1n; return uvarintLength(zigzag); } }