/** * Markers, type tables and the value classes of BJData Draft 4/5 * (https://neurojson.org/bjdata/draft4, https://github.com/NeuroJSON/bjdata). * * Copyright (c) 2019-2026 Qianqian Fang . Apache License 2.0. */ /** Size in bytes of each fixed-length marker. */ export const FIXED_SIZE: { [marker: string]: number } = { i: 1, U: 1, I: 2, u: 2, l: 4, m: 4, L: 8, M: 8, h: 2, d: 4, D: 8, C: 1, B: 1 }; /** The integer markers (lengths, counts, dimensions, keys). */ export const INT_MARKERS = 'iUIulmLM'; /** The JData _ArrayType_ name of each fixed-length marker. */ export const JDATA_TYPE: { [marker: string]: string } = { i: 'int8', U: 'uint8', I: 'int16', u: 'uint16', l: 'int32', m: 'uint32', L: 'int64', M: 'uint64', h: 'half', d: 'single', D: 'double', C: 'char', B: 'byte' }; /** The marker of each JData _ArrayType_ name (with the spec's aliases). */ export const MARKER_OF_TYPE: { [name: string]: string } = { int8: 'i', uint8: 'U', int16: 'I', uint16: 'u', int32: 'l', uint32: 'm', int64: 'L', uint64: 'M', half: 'h', float16: 'h', single: 'd', float32: 'd', double: 'D', float64: 'D', char: 'C', byte: 'B', logical: 'U', bool: 'U', boolean: 'U' }; export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; /** The typed-array constructor that holds each marker's values (half precision: Float32Array). */ export function typedArrayOf(marker: string): any { switch (marker) { case 'i': return Int8Array; case 'U': case 'C': case 'B': return Uint8Array; case 'I': return Int16Array; case 'u': return Uint16Array; case 'l': return Int32Array; case 'm': return Uint32Array; case 'L': return typeof BigInt64Array !== 'undefined' ? BigInt64Array : null; case 'M': return typeof BigUint64Array !== 'undefined' ? BigUint64Array : null; case 'h': case 'd': return Float32Array; case 'D': return Float64Array; } return null; } /** The marker of a typed array (by its constructor name, so that arrays of other realms count). */ export function markerOfTypedArray(a: any): string | null { const name = Object.prototype.toString.call(a).slice(8, -1); switch (name) { case 'Int8Array': return 'i'; case 'Uint8Array': case 'Uint8ClampedArray': return 'U'; case 'Int16Array': return 'I'; case 'Uint16Array': return 'u'; case 'Int32Array': return 'l'; case 'Uint32Array': return 'm'; case 'BigInt64Array': return 'L'; case 'BigUint64Array': return 'M'; case 'Float16Array': return 'h'; case 'Float32Array': return 'd'; case 'Float64Array': return 'D'; } return null; } export function isTypedArray(a: any): a is TypedArray { return ArrayBuffer.isView(a) && !(a instanceof DataView); } /** True on little-endian machines (all common ones): typed-array payloads are then copied as is. */ export const HOST_LITTLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; /** * A high-precision number ([H] marker): a JSON number in text, of any length and precision. The * bytes are kept as read, so that a JData _ByteStream_, also stored with [H], is not altered. */ export class HighPrec { readonly bytes: Uint8Array; constructor(value: string | Uint8Array) { this.bytes = typeof value === 'string' ? utf8Encode(value) : value; } toString(): string { return utf8Decode(this.bytes, 0, this.bytes.length); } valueOf(): number { return Number(this.toString()); } toJSON(): string { return this.toString(); } } /** * An extension value ([E][type-id][byte-length][payload]). Type ids 0-255 are reserved by the * specification (1 epoch_s ... 10 uuid); `value` gives the payload of a known type in a native * form (Date, {re, im}, a UUID string, ...), and the object is written back unchanged. */ export class Extension { readonly type: number; readonly data: Uint8Array; constructor(type: number, data: Uint8Array) { if (!(Number.isInteger(type) && type >= 0)) { throw new BJDataError('an extension type id must be a non-negative integer'); } this.type = type; this.data = data; } /** The payload of a reserved type as a JavaScript value; the raw bytes for any other type. */ get value(): any { const d = this.data; const v = new DataView(d.buffer, d.byteOffset, d.byteLength); const need = (n: number) => { if (d.length !== n) { throw new BJDataError('extension type ' + this.type + ' needs ' + n + ' bytes, not ' + d.length); } }; switch (this.type) { case 1: need(4); return new Date(v.getUint32(0, true) * 1000); case 2: case 6: need(8); return new Date(Number(read64(v, 0, true, true)) / 1000); case 3: need(12); return new Date(Number(read64(v, 0, true, true)) * 1000 + v.getUint32(8, true) / 1e6); case 4: need(4); return { year: v.getInt16(0, true), month: d[2], day: d[3] }; case 5: need(4); return { hour: d[0], minute: d[1], second: d[2] }; case 7: need(8); return Number(read64(v, 0, true, true)); case 8: need(8); return { re: v.getFloat32(0, true), im: v.getFloat32(4, true) }; case 9: need(16); return { re: v.getFloat64(0, true), im: v.getFloat64(8, true) }; case 10: { need(16); let h = ''; for (let k = 0; k < 16; k++) { h += (d[k] < 16 ? '0' : '') + d[k].toString(16); if (k === 3 || k === 5 || k === 7 || k === 9) { h += '-'; } } return h; } } return d; } toJSON(): any { return { _ExtType_: this.type, _ExtData_: Array.from(this.data) }; } /** An extension for a Date: datetime_us (type 6), or epoch_s (type 1). */ static fromDate(date: Date, type: number = 6): Extension { const ms = date.getTime(); if (type === 1) { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, Math.floor(ms / 1000), true); return new Extension(1, b); } const b = new Uint8Array(8); write64(new DataView(b.buffer), 0, ms * 1000, true, true); return new Extension(type, b); } /** A uuid extension (type 10) from its text form. */ static fromUUID(uuid: string): Extension { const h = uuid.replace(/[{}-]/g, ''); if (!/^[0-9a-fA-F]{32}$/.test(h)) { throw new BJDataError('not a UUID: ' + uuid); } const b = new Uint8Array(16); for (let k = 0; k < 16; k++) { b[k] = parseInt(h.substr(2 * k, 2), 16); } return new Extension(10, b); } } /** A parse or encode error; `position` is the byte offset where decoding failed. */ export class BJDataError extends Error { readonly position?: number; constructor(message: string, position?: number) { super(position === undefined ? 'bjdata: ' + message : 'bjdata: ' + message + ' (at byte ' + position + ')'); this.name = 'BJDataError'; this.position = position; Object.setPrototypeOf(this, BJDataError.prototype); } } // ---- 64-bit integers (exact as numbers up to 2^53; BigInt beyond, where available) ----------- const TWO32 = 4294967296; const HAS_BIGINT = typeof BigInt === 'function'; /** A 64-bit integer: a number when it is exactly representable, else a BigInt (or, without * BigInt, the nearest number). `big` forces a BigInt. */ export function read64(v: DataView, at: number, signed: boolean, little: boolean, big: boolean = false): number | bigint { const lo = v.getUint32(little ? at : at + 4, little); const hi = signed ? v.getInt32(little ? at + 4 : at, little) : v.getUint32(little ? at + 4 : at, little); if (!big && hi < 2097152 && hi >= -2097152) { return hi * TWO32 + lo; // |value| < 2^53 } if (!HAS_BIGINT) { return hi * TWO32 + lo; } return BigInt(hi) * BigInt(TWO32) + BigInt(lo); } export function write64(v: DataView, at: number, x: number | bigint, signed: boolean, little: boolean): void { let lo: number, hi: number; if (typeof x === 'bigint') { const m = BigInt.asUintN(64, x); lo = Number(m & BigInt(0xffffffff)); hi = Number(m >> BigInt(32)); } else { // exact for |x| <= 2^53: hi = floor(x / 2^32) (two's complement once wrapped), lo in [0, 2^32) hi = Math.floor(x / TWO32); lo = x - hi * TWO32; hi = hi >>> 0; } void signed; v.setUint32(little ? at : at + 4, lo, little); v.setUint32(little ? at + 4 : at, hi, little); } // ---- float16 ------------------------------------------------------------------------------------ const f32 = new Float32Array(1); const u32 = new Uint32Array(f32.buffer); export function halfToFloat(h: number): number { const s = h & 0x8000 ? -1 : 1; const e = (h >> 10) & 0x1f; const f = h & 0x3ff; if (e === 0) { return s * f * 5.960464477539063e-8; // 2^-24 } if (e === 31) { return f ? NaN : s * Infinity; } return s * (1 + f / 1024) * Math.pow(2, e - 15); } export function floatToHalf(x: number): number { f32[0] = x; const b = u32[0]; const s = (b >>> 16) & 0x8000; const e = (b >>> 23) & 0xff; let m = b & 0x7fffff; if (e === 255) { return s | 0x7c00 | (m ? 0x200 : 0); } let he = e - 127 + 15; if (he >= 31) { return s | 0x7c00; } if (he <= 0) { if (he < -10) { return s; } m |= 0x800000; const shift = 14 - he; let hm = m >> shift; const rest = m & ((1 << shift) - 1), half = 1 << (shift - 1); if (rest > half || (rest === half && (hm & 1))) { hm++; } return s | hm; } let hm = m >> 13; const rest = m & 0x1fff; if (rest > 0x1000 || (rest === 0x1000 && (hm & 1))) { hm++; if (hm === 0x400) { hm = 0; he++; if (he >= 31) { return s | 0x7c00; } } } return s | (he << 10) | hm; } // ---- UTF-8 -------------------------------------------------------------------------------------- const TD: any = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8') : null; // (in Node.js, Buffer's own UTF-8 slicing: 4-5 times faster than TextDecoder for short strings) declare const process: any, Buffer: any; const NODE_UTF8: any = typeof process !== 'undefined' && process.versions && process.versions.node && typeof Buffer !== 'undefined' && Buffer.prototype && typeof Buffer.prototype.utf8Slice === 'function' ? Buffer.prototype.utf8Slice : null; const TE: any = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null; const fcc = String.fromCharCode; /** The string of len (1 to 16) ASCII bytes at b[at] (the caller checks they are ASCII); the * fastest way in V8 for short strings: one flat string, no temporary array. */ export function shortAscii(b: Uint8Array, at: number, len: number): string { switch (len) { case 1: return fcc(b[at]); case 2: return fcc(b[at], b[at + 1]); case 3: return fcc(b[at], b[at + 1], b[at + 2]); case 4: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3]); case 5: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4]); case 6: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5]); case 7: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6]); case 8: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7]); case 9: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7], b[at + 8]); case 10: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7], b[at + 8], b[at + 9]); case 11: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7], b[at + 8], b[at + 9], b[at + 10]); case 12: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7], b[at + 8], b[at + 9], b[at + 10], b[at + 11]); case 13: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7], b[at + 8], b[at + 9], b[at + 10], b[at + 11], b[at + 12]); case 14: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7], b[at + 8], b[at + 9], b[at + 10], b[at + 11], b[at + 12], b[at + 13]); case 15: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7], b[at + 8], b[at + 9], b[at + 10], b[at + 11], b[at + 12], b[at + 13], b[at + 14]); case 16: return fcc(b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7], b[at + 8], b[at + 9], b[at + 10], b[at + 11], b[at + 12], b[at + 13], b[at + 14], b[at + 15]); } return ''; } /** Whether the len bytes at b[at] are all ASCII. */ export function isAscii(b: Uint8Array, at: number, len: number): boolean { for (let k = at, e = at + len; k < e; k++) { if (b[k] > 127) { return false; } } return true; } // ASCII strings up to this length are built in JS: faster than Node's Buffer slicing (about 60 ns a // call) or TextDecoder (about 100 ns a call in Chrome) for short strings const JS_ASCII_MAX = NODE_UTF8 ? 16 : 64; export function utf8Decode(b: Uint8Array, start: number, end: number): string { const len = end - start; if (len <= JS_ASCII_MAX && isAscii(b, start, len)) { if (len <= 16) { return len ? shortAscii(b, start, len) : ''; } // (pieces of 16: a few flat strings, not one per character) let s = '', k = start; for (; k + 16 <= end; k += 16) { s += shortAscii(b, k, 16); } return k < end ? s + shortAscii(b, k, end - k) : s; } if (NODE_UTF8) { return NODE_UTF8.call(b, start, end); } if (TD) { return TD.decode(b.subarray(start, end)); } // (no TextDecoder: a plain decoder; invalid sequences become U+FFFD) let s = ''; for (let k = start; k < end;) { const c = b[k++]; let cp = 0xfffd; if (c < 0x80) { cp = c; } else if (c >= 0xc2 && c < 0xe0 && k < end) { cp = ((c & 0x1f) << 6) | (b[k++] & 0x3f); } else if (c >= 0xe0 && c < 0xf0 && k + 1 < end) { cp = ((c & 0x0f) << 12) | ((b[k] & 0x3f) << 6) | (b[k + 1] & 0x3f); k += 2; } else if (c >= 0xf0 && c < 0xf5 && k + 2 < end) { cp = ((c & 0x07) << 18) | ((b[k] & 0x3f) << 12) | ((b[k + 1] & 0x3f) << 6) | (b[k + 2] & 0x3f); k += 3; } s += String.fromCodePoint(cp); } return s; } const NODE_UTF8_WRITE: any = NODE_UTF8 && typeof Buffer.prototype.utf8Write === 'function' ? Buffer.prototype.utf8Write : null; const TE_INTO: boolean = !!TE && typeof TE.encodeInto === 'function'; /** Writes the UTF-8 bytes of s into b at `at` (b has room for 3 * s.length bytes); returns the * number of bytes written. Lone surrogates become U+FFFD, as with TextEncoder. */ export function utf8Into(s: string, b: Uint8Array, at: number): number { if (NODE_UTF8_WRITE) { return NODE_UTF8_WRITE.call(b, s, at, b.length - at); } if (TE_INTO) { return TE.encodeInto(s, b.subarray(at)).written; } let p = at; for (let k = 0; k < s.length; k++) { let c = s.charCodeAt(k); if (c < 0x80) { b[p++] = c; continue; } if (c < 0x800) { b[p++] = 0xc0 | (c >> 6); b[p++] = 0x80 | (c & 63); continue; } if (c >= 0xd800 && c < 0xe000) { const d = k + 1 < s.length ? s.charCodeAt(k + 1) : 0; if (c < 0xdc00 && d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); k++; b[p++] = 0xf0 | (c >> 18); b[p++] = 0x80 | ((c >> 12) & 63); b[p++] = 0x80 | ((c >> 6) & 63); b[p++] = 0x80 | (c & 63); continue; } c = 0xfffd; } b[p++] = 0xe0 | (c >> 12); b[p++] = 0x80 | ((c >> 6) & 63); b[p++] = 0x80 | (c & 63); } return p - at; } export function utf8Encode(s: string): Uint8Array { if (TE) { return TE.encode(s); } const out: number[] = []; for (let k = 0; k < s.length; k++) { let c = s.codePointAt(k) as number; if (c > 0xffff) { k++; } if (c < 0x80) { out.push(c); } else if (c < 0x800) { out.push(0xc0 | (c >> 6), 0x80 | (c & 63)); } else if (c < 0x10000) { if (c >= 0xd800 && c < 0xe000) { c = 0xfffd; } out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63)); } else { out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63)); } } return new Uint8Array(out); } /** A Uint8Array over any byte input: Uint8Array (Node Buffer), ArrayBuffer, DataView, a typed * array (its bytes), or an array of byte values. */ export function asBytes(input: any): Uint8Array { if (input instanceof Uint8Array) { // (a Node Buffer, whose slice() is a view into a shared pool: a plain Uint8Array view) return input.constructor === Uint8Array ? input : new Uint8Array(input.buffer, input.byteOffset, input.byteLength); } if (input instanceof ArrayBuffer || Object.prototype.toString.call(input) === '[object ArrayBuffer]' || (typeof SharedArrayBuffer !== 'undefined' && input instanceof SharedArrayBuffer)) { return new Uint8Array(input); } if (ArrayBuffer.isView(input)) { return new Uint8Array(input.buffer, input.byteOffset, input.byteLength); } if (Array.isArray(input)) { return Uint8Array.from(input); } if (input && typeof input === 'object' && typeof input.length === 'number') { return Uint8Array.from(input); // (an old Buffer polyfill, array-likes) } throw new BJDataError('the input must be bytes (Uint8Array, Buffer, ArrayBuffer or DataView)'); }