/** * BJData decoder (Draft 4, and the Draft 5 structure-of-arrays containers and extensions). * * Copyright (c) 2019-2026 Qianqian Fang . Apache License 2.0. */ import { FIXED_SIZE, INT_MARKERS, JDATA_TYPE, HOST_LITTLE, HighPrec, Extension, BJDataError, read64, halfToFloat, utf8Decode, asBytes, typedArrayOf, shortAscii } from './types'; export interface DecodeOptions { /** 64-bit integer scalars ([L], [M]): 'auto' (default) a number when exact, else a BigInt; * 'always' a BigInt; 'never' a number (rounded beyond 2^53) */ bigint?: 'auto' | 'always' | 'never'; /** N-D packed arrays ([$type#[dims]): 'jdata' (default) an {_ArrayType_, _ArraySize_, * _ArrayData_: TypedArray} object; 'nested' nested arrays; 'flat' the typed array alone; or * a function (data, shape, order 'C'|'F', type) => value */ ndarray?: 'jdata' | 'nested' | 'flat' | ((data: any, shape: number[], order: 'C' | 'F', type: string) => any); /** Structure-of-arrays containers: 'records' (default) an array of objects; 'columns' an * object of columns (typed arrays for numeric fields) */ soa?: 'records' | 'columns'; /** [H] values: 'object' (default) a HighPrec, 'string', or 'number' */ highprec?: 'object' | 'string' | 'number'; /** [E] values: a function (type, payload) => value; default an Extension object */ extension?: (type: number, data: Uint8Array) => any; /** copy typed payloads out of the input (default true); false returns views into the input * where the alignment allows */ copy?: boolean; /** byte order of the numbers: 'little' (BJData, default) or 'big' (UBJSON, BJData Draft 1) */ endian?: 'little' | 'big'; /** maximum container nesting (default 1000) */ maxDepth?: number; } interface Field { name: string; kind: 'n' | 'T' | 'Z' | 'S' | 'H' | 'dict' | 'off' | 'obj' | 'arr'; marker?: string; // 'n' numbers; 'off' the offset type width: number; // bytes per record sub?: Field[]; // 'obj' fields, 'arr' elements dict?: any[]; // 'dict' entries table?: number; // 'off' index into the offset tables } const DIM_CHECK = Math.pow(2, 53); export class Decoder { private b: Uint8Array; private v: DataView; private n: number; pos: number; private little: boolean; private o: DecodeOptions; private depth = 0; private maxDepth: number; private keys: string[] = new Array(4096); // recently read ASCII keys, by a hash of their bytes constructor(input: any, opts: DecodeOptions = {}) { this.b = asBytes(input); this.v = new DataView(this.b.buffer, this.b.byteOffset, this.b.byteLength); this.n = this.b.length; this.pos = 0; this.o = opts; this.little = opts.endian !== 'big'; this.maxDepth = opts.maxDepth === undefined ? 1000 : opts.maxDepth; } get length(): number { return this.n; } private bad(msg: string, at: number = this.pos): never { throw new BJDataError(msg, at); } private need(k: number): void { if (k > this.n - this.pos) { throw new BJDataError('unexpected end of data', this.n); } } private next(): string { if (this.pos >= this.n) { throw new BJDataError('unexpected end of data', this.n); } return String.fromCharCode(this.b[this.pos++]); } private peek(): string { if (this.pos >= this.n) { throw new BJDataError('unexpected end of data', this.n); } return String.fromCharCode(this.b[this.pos]); } /** Skips no-op markers; false at the end of the input (between top-level values). */ skipNoop(): boolean { while (this.pos < this.n && this.b[this.pos] === 0x4e) { this.pos++; } return this.pos < this.n; } // ---- numbers ---------------------------------------------------------------------------- private num(m: string, big: boolean = false): any { const size = FIXED_SIZE[m]; this.need(size); const v = this.v, at = this.pos, le = this.little; this.pos += size; switch (m) { case 'i': return v.getInt8(at); case 'U': case 'B': return v.getUint8(at); case 'I': return v.getInt16(at, le); case 'u': return v.getUint16(at, le); case 'l': return v.getInt32(at, le); case 'm': return v.getUint32(at, le); case 'L': case 'M': { const mode = this.o.bigint; const x = read64(v, at, m === 'L', le, big || mode === 'always'); return mode === 'never' && typeof x === 'bigint' ? Number(x) : x; } case 'h': return halfToFloat(v.getUint16(at, le)); case 'd': return v.getFloat32(at, le); case 'D': return v.getFloat64(at, le); case 'C': return String.fromCharCode(v.getUint8(at)); } return this.bad('not a number marker ' + m); } /** A non-negative integer (a length, count or dimension), as a number. */ private uint(m: string, what: string): number { if (INT_MARKERS.indexOf(m) < 0 || m.length !== 1) { this.bad(what + ' must be an integer, not \'' + m + '\'', this.pos - 1); } const at = this.pos; let x = this.num(m); if (typeof x === 'bigint') { x = Number(x); } if (x < 0) { this.bad('a negative ' + what, at); } if (x >= DIM_CHECK) { this.bad(what + ' too large', at); } return x; } private text(len: number): string { this.need(len); const at = this.pos; this.pos += len; return utf8Decode(this.b, at, at + len); } /** A length: the common [U] inline, any integer type else. */ private len(what: string): number { const b = this.b; if (this.pos + 1 < this.n && b[this.pos] === 0x55) { const x = b[this.pos + 1]; this.pos += 2; return x; } return this.uint(this.next(), what); } private bytes(len: number): Uint8Array { this.need(len); const r = this.b.slice(this.pos, this.pos + len); this.pos += len; return r; } // ---- values ----------------------------------------------------------------------------- /** The value starting at the current position (no-op markers are not values). */ value(): any { const at = this.pos; if (at >= this.n) { throw new BJDataError('unexpected end of data', this.n); } const c = this.b[at]; // the common markers by their byte, without making a string switch (c) { case 0x55: { // U if (at + 1 < this.n) { this.pos = at + 2; return this.b[at + 1]; } break; } case 0x69: // i if (at + 1 < this.n) { this.pos = at + 2; return this.v.getInt8(at + 1); } break; case 0x44: // D if (at + 8 < this.n) { this.pos = at + 9; return this.v.getFloat64(at + 1, this.little); } break; case 0x75: // u if (at + 2 < this.n) { this.pos = at + 3; return this.v.getUint16(at + 1, this.little); } break; case 0x49: // I if (at + 2 < this.n) { this.pos = at + 3; return this.v.getInt16(at + 1, this.little); } break; case 0x6d: // m if (at + 4 < this.n) { this.pos = at + 5; return this.v.getUint32(at + 1, this.little); } break; case 0x6c: // l if (at + 4 < this.n) { this.pos = at + 5; return this.v.getInt32(at + 1, this.little); } break; case 0x64: // d if (at + 4 < this.n) { this.pos = at + 5; return this.v.getFloat32(at + 1, this.little); } break; case 0x53: { // S this.pos = at + 1; const len = this.len('a string length'); // (short ASCII values repeat: from the key cache, no new string) return len <= 16 && len > 0 ? this.cachedText(len) : this.text(len); } case 0x5a: this.pos = at + 1; return null; case 0x54: this.pos = at + 1; return true; case 0x46: this.pos = at + 1; return false; case 0x5b: this.pos = at + 1; return this.container(true, at); case 0x7b: this.pos = at + 1; return this.container(false, at); } const m = this.next(); switch (m) { case 'Z': return null; case 'T': return true; case 'F': return false; case 'i': case 'U': case 'I': case 'u': case 'l': case 'm': case 'L': case 'M': case 'h': case 'd': case 'D': case 'B': return this.num(m); case 'C': return this.num('C'); case 'S': return this.text(this.uint(this.next(), 'a string length')); case 'H': { const raw = this.bytes(this.uint(this.next(), 'a high-precision length')); const hp = this.o.highprec; if (hp === 'string' || hp === 'number') { const s = utf8Decode(raw, 0, raw.length); return hp === 'number' ? Number(s) : s; } return new HighPrec(raw); } case 'E': { const type = this.uint(this.next(), 'an extension type'); const data = this.bytes(this.uint(this.next(), 'an extension length')); return this.o.extension ? this.o.extension(type, data) : new Extension(type, data); } case '[': return this.container(true, at); case '{': return this.container(false, at); case 'N': return this.bad('a no-op where a value is expected', at); case ']': case '}': return this.bad('unexpected \'' + m + '\'', at); } return this.bad('unknown marker \'' + m + '\' (0x' + this.b[at].toString(16) + ')', at); } private key(): string { const len = this.len('a key length'); return len <= 32 && len > 0 ? this.cachedText(len) : this.text(len); } /** A short string (1 to 32 bytes): when ASCII and seen before, the same string again. */ private cachedText(len: number): string { if (len > this.n - this.pos) { return this.text(len); } const b = this.b, at = this.pos; let h = len, k = 0; for (; k < len; k++) { const x = b[at + k]; if (x > 127) { return this.text(len); } h = (h * 31 + x) | 0; } const slot = h & 4095; const cached = this.keys[slot]; if (cached !== undefined && cached.length === len) { k = 0; while (k < len && cached.charCodeAt(k) === b[at + k]) { k++; } if (k === len) { this.pos += len; return cached; } } const s = len <= 16 ? shortAscii(b, at, len) : String.fromCharCode.apply(null, b.subarray(at, at + len) as any); this.pos += len; this.keys[slot] = s; return s; } /** The byte at the current position (end of data is an error). */ private at(): number { if (this.pos >= this.n) { throw new BJDataError('unexpected end of data', this.n); } return this.b[this.pos]; } private container(isArray: boolean, at: number): any { if (++this.depth > this.maxDepth) { this.bad('containers nested deeper than ' + this.maxDepth, at); } let type: string | null = null; let count = -1; let dims: number[] | null = null; let order: 'C' | 'F' = 'C'; let out: any; if (this.at() === 0x24) { this.pos++; type = this.next(); if (type === '{') { const schema = this.schema(); if (this.next() !== '#') { this.bad('a structure-of-arrays without a count', this.pos - 1); } const c = this.countOrDims(true); out = this.soa(schema, !isArray, c.count, c.dims, c.order); this.depth--; return out; } if (!FIXED_SIZE[type]) { this.bad('\'' + type + '\' is not allowed as a container type (only i U I u l m L M h d D C B)', this.pos - 1); } if (this.peek() !== '#') { this.bad('a typed container without a count', this.pos); } } if (this.at() === 0x23) { this.pos++; const c = this.countOrDims(isArray && type !== null); count = c.count; dims = c.dims; order = c.order; } if (type !== null) { out = isArray ? this.packed(type, count, dims, order) : this.typedObject(type, count); } else if (isArray) { out = []; if (count >= 0) { // every element takes at least one byte if (count > this.n - this.pos) { throw new BJDataError('unexpected end of data', this.n); } while (out.length < count) { if (this.at() === 0x4e) { this.pos++; continue; } out.push(this.value()); } } else { for (;;) { const c = this.at(); if (c === 0x5d) { this.pos++; break; } if (c === 0x4e) { this.pos++; continue; } out.push(this.value()); } } } else { out = {}; if (count >= 0) { if (count > this.n - this.pos) { throw new BJDataError('unexpected end of data', this.n); } for (let k = 0; k < count;) { if (this.at() === 0x4e) { this.pos++; continue; } setKey(out, this.key(), this.value()); k++; } } else { for (;;) { const c = this.at(); if (c === 0x7d) { this.pos++; break; } if (c === 0x4e) { this.pos++; continue; } setKey(out, this.key(), this.value()); } } } this.depth--; return out; } /** After '#': a count, or (allowDims) an N-D dimension array, row-major [d1 d2 ...] or * column-major [[d1 d2 ...]]. */ private countOrDims(allowDims: boolean): { count: number; dims: number[] | null; order: 'C' | 'F' } { const m = this.next(); if (m !== '[') { return { count: this.uint(m, 'a count'), dims: null, order: 'C' }; } if (!allowDims) { this.bad('N-D dimensions are only allowed in a typed array', this.pos - 1); } let order: 'C' | 'F' = 'C'; let dims: number[]; const c = this.peek(); if (c === '[') { // column-major: [ [dims] ] this.pos++; order = 'F'; dims = this.dimBody(); if (this.next() !== ']') { this.bad('the column-major dimension wrapper must hold one array', this.pos - 1); } } else if (c === '#') { // [# d1 d2 ...], or the counted column-major wrapper [#<1> [dims] (no ] of its own) this.pos++; const k = this.uint(this.next(), 'a dimension count'); if (this.peek() === '[') { if (k !== 1) { this.bad('the column-major dimension wrapper must hold one array'); } this.pos++; order = 'F'; dims = this.dimBody(); } else { if (k > this.n - this.pos) { throw new BJDataError('unexpected end of data', this.n); } dims = []; for (let i = 0; i < k; i++) { dims.push(this.uint(this.next(), 'a dimension')); } } } else { dims = this.dimBody(); } let total = 1; for (const d of dims) { total *= d; } if (total >= DIM_CHECK) { this.bad('N-D array too large'); } return { count: total, dims, order }; } /** A dimension array after its '[': [$t#n raw], [#n m v ...] or [m v ... ]. */ private dimBody(): number[] { const dims: number[] = []; let c = this.peek(); if (c === '$') { this.pos++; const t = this.next(); if (INT_MARKERS.indexOf(t) < 0) { this.bad('dimensions must be integers', this.pos - 1); } if (this.next() !== '#') { this.bad('a typed dimension array without a count', this.pos - 1); } const k = this.uint(this.next(), 'a dimension count'); this.need(k * FIXED_SIZE[t]); for (let i = 0; i < k; i++) { dims.push(this.uintRaw(t)); } return dims; } if (c === '#') { this.pos++; const k = this.uint(this.next(), 'a dimension count'); if (k > this.n - this.pos) { throw new BJDataError('unexpected end of data', this.n); } for (let i = 0; i < k; i++) { dims.push(this.uint(this.next(), 'a dimension')); } return dims; } for (;;) { c = this.next(); if (c === ']') { return dims; } dims.push(this.uint(c, 'a dimension')); } } private uintRaw(t: string): number { const at = this.pos; let x = this.num(t); if (typeof x === 'bigint') { x = Number(x); } if (x < 0 || x >= DIM_CHECK) { this.bad('an invalid dimension', at); } return x; } /** A typed array payload of count elements of type t. */ private typed(t: string, count: number): any { const size = FIXED_SIZE[t]; const nbytes = count * size; this.need(nbytes); const at = this.pos; this.pos += nbytes; const b = this.b; if (t === 'C') { return utf8Decode(b, at, at + nbytes); } if (t === 'h') { const out = new Float32Array(count); const v = this.v, le = this.little; for (let k = 0; k < count; k++) { out[k] = halfToFloat(v.getUint16(at + 2 * k, le)); } return out; } const Ctor = typedArrayOf(t); if (!Ctor) { // (no BigInt64Array: an array of numbers) const out: any[] = []; const save = this.pos; this.pos = at; for (let k = 0; k < count; k++) { out.push(this.num(t)); } this.pos = save; return out; } const swap = size > 1 && this.little !== HOST_LITTLE; const off = b.byteOffset + at; if (this.o.copy === false && !swap && off % size === 0) { return new Ctor(b.buffer, off, count); } const raw = b.slice(at, at + nbytes); if (swap) { for (let k = 0; k < nbytes; k += size) { for (let i = 0, j = size - 1; i < j; i++, j--) { const x = raw[k + i]; raw[k + i] = raw[k + j]; raw[k + j] = x; } } } return new Ctor(raw.buffer, 0, count); } private packed(t: string, count: number, dims: number[] | null, order: 'C' | 'F'): any { const data = this.typed(t, count); if (dims === null) { return data; } const mode = this.o.ndarray || 'jdata'; if (typeof mode === 'function') { return mode(data, dims, order, JDATA_TYPE[t]); } if (mode === 'flat') { return data; } if (mode === 'nested') { return nest(typeof data === 'string' ? Array.from(data) : data, dims, order); } const r: any = { _ArrayType_: JDATA_TYPE[t], _ArraySize_: dims.slice() }; if (order === 'F') { r._ArrayOrder_ = 'column'; } r._ArrayData_ = typeof data === 'string' ? Uint8Array.from(data, (ch: string) => ch.charCodeAt(0)) : data; return r; } private typedObject(t: string, count: number): any { const out: any = {}; if (count > this.n - this.pos) { throw new BJDataError('unexpected end of data', this.n); } for (let k = 0; k < count;) { if (this.peek() === 'N') { this.pos++; continue; } const key = this.key(); setKey(out, key, this.num(t)); k++; } return out; } // ---- structure-of-arrays ---------------------------------------------------------------- private offsets = 0; /** A schema whose '{' has been read. */ private schema(): Field[] { this.offsets = 0; return this.fields(); } private fields(): Field[] { const fs: Field[] = []; for (;;) { const c = this.peek(); if (c === '}') { this.pos++; break; } if (c === 'N') { this.pos++; continue; } const name = this.key(); const f = this.typeSpec(); f.name = name; fs.push(f); } if (!fs.length) { this.bad('an empty structure-of-arrays schema'); } return fs; } private typeSpec(): Field { const at = this.pos; const m = this.next(); if (FIXED_SIZE[m]) { return { name: '', kind: 'n', marker: m, width: FIXED_SIZE[m] }; } switch (m) { case 'T': return { name: '', kind: 'T', width: 1 }; case 'Z': return { name: '', kind: 'Z', width: 0 }; case 'S': case 'H': return { name: '', kind: m, width: this.uint(this.next(), 'a fixed string length') }; case '{': { const sub = this.fields(); return { name: '', kind: 'obj', sub, width: sub.reduce((s, f) => s + f.width, 0) }; } case '[': { if (this.peek() === '$') { this.pos++; const t = this.next(); if (t === 'S' || t === 'H') { if (this.next() !== '#') { this.bad('a dictionary without a count', this.pos - 1); } const k = this.uint(this.next(), 'a dictionary count'); if (k > this.n - this.pos) { throw new BJDataError('unexpected end of data', this.n); } const dict: any[] = []; for (let i = 0; i < k; i++) { const len = this.uint(this.next(), 'a dictionary entry length'); if (t === 'S') { dict.push(this.text(len)); } else { const raw = this.bytes(len); dict.push(this.highprec(raw)); } } const width = k <= 255 ? 1 : k <= 65535 ? 2 : k <= 4294967295 ? 4 : 8; return { name: '', kind: 'dict', dict, width }; } if (INT_MARKERS.indexOf(t) < 0 || this.next() !== ']') { this.bad('a malformed offset-table field', at); } return { name: '', kind: 'off', marker: t, width: FIXED_SIZE[t], table: this.offsets++ }; } const sub: Field[] = []; while (this.peek() !== ']') { sub.push(this.typeSpec()); } this.pos++; if (!sub.length) { this.bad('an empty array field in a schema', at); } return { name: '', kind: 'arr', sub, width: sub.reduce((s, f) => s + f.width, 0) }; } } return this.bad('\'' + m + '\' is not allowed in a schema', at); } private highprec(raw: Uint8Array): any { const hp = this.o.highprec; if (hp === 'string' || hp === 'number') { const s = utf8Decode(raw, 0, raw.length); return hp === 'number' ? Number(s) : s; } return new HighPrec(raw); } private soa(fs: Field[], columnar: boolean, count: number, dims: number[] | null, order: 'C' | 'F'): any { const at = this.pos; const rec = fs.reduce((s, f) => s + f.width, 0); if (rec === 0) { this.bad('a structure-of-arrays schema whose records take no bytes', at); } if (count > (this.n - this.pos) / rec) { throw new BJDataError('unexpected end of data', this.n); } const base = this.pos; this.pos += count * rec; // offset tables and text buffers follow the payload, in schema order const tables: { off: number[]; text: number }[] = []; const offFields: Field[] = []; collectOffsets(fs, offFields); offFields.sort((a, b) => (a.table as number) - (b.table as number)); for (const f of offFields) { const w = f.width; this.need((count + 1) * w); const off: number[] = new Array(count + 1); for (let k = 0; k <= count; k++) { const x = this.num(f.marker as string); off[k] = typeof x === 'bigint' ? Number(x) : x; } for (let k = 0; k < count; k++) { if (off[k] > off[k + 1] || off[k] < 0) { this.bad('a decreasing string offset'); } } this.need(off[count]); tables.push({ off, text: this.pos }); this.pos += off[count]; } // leaf addresses: value of record i of leaf j at start_j + i * stride_j const leaves: { f: Field; start: number; stride: number }[] = []; let inrec = 0, colstart = 0; const place = (list: Field[]) => { for (const f of list) { if (f.kind === 'obj' || f.kind === 'arr') { place(f.sub as Field[]); continue; } if (columnar) { leaves.push({ f, start: base + colstart, stride: f.width }); colstart += f.width * count; } else { leaves.push({ f, start: base + inrec, stride: rec }); inrec += f.width; } } }; place(fs); const leafOf = new Map(); for (const l of leaves) { leafOf.set(l.f, l); } const asColumns = this.o.soa === 'columns'; // the values of one leaf, all records at once (one loop per field: no per-value dispatch) const leafColumn = (f: Field): any => { const l = leafOf.get(f) as { start: number; stride: number }; const b = this.b, v = this.v, le = this.little, st = l.stride; let p = l.start; switch (f.kind) { case 'n': { const m = f.marker as string; if (m === 'C') { const out = new Array(count); for (let i = 0; i < count; i++, p += st) { out[i] = String.fromCharCode(b[p]); } return out; } if (m === 'L' || m === 'M') { const signed = m === 'L'; const Ctor = typedArrayOf(m); if (asColumns && Ctor) { const out = new Ctor(count); for (let i = 0; i < count; i++, p += st) { out[i] = read64(v, p, signed, le, true); } return out; } const mode = this.o.bigint; const out = new Array(count); for (let i = 0; i < count; i++, p += st) { const x = read64(v, p, signed, le, mode === 'always'); out[i] = mode === 'never' && typeof x === 'bigint' ? Number(x) : x; } return out; } if (asColumns && columnar && m !== 'h') { // (contiguous: the typed payload itself) const save = this.pos; this.pos = l.start; const col = this.typed(m, count); this.pos = save; return col; } const out = new (typedArrayOf(m) as any)(count); switch (m) { case 'i': for (let i = 0; i < count; i++, p += st) { out[i] = v.getInt8(p); } break; case 'U': case 'B': for (let i = 0; i < count; i++, p += st) { out[i] = b[p]; } break; case 'I': for (let i = 0; i < count; i++, p += st) { out[i] = v.getInt16(p, le); } break; case 'u': for (let i = 0; i < count; i++, p += st) { out[i] = v.getUint16(p, le); } break; case 'l': for (let i = 0; i < count; i++, p += st) { out[i] = v.getInt32(p, le); } break; case 'm': for (let i = 0; i < count; i++, p += st) { out[i] = v.getUint32(p, le); } break; case 'h': for (let i = 0; i < count; i++, p += st) { out[i] = halfToFloat(v.getUint16(p, le)); } break; case 'd': for (let i = 0; i < count; i++, p += st) { out[i] = v.getFloat32(p, le); } break; case 'D': for (let i = 0; i < count; i++, p += st) { out[i] = v.getFloat64(p, le); } break; } return out; } case 'T': { const out = new Array(count); for (let i = 0; i < count; i++, p += st) { const c = b[p]; if (c !== 0x54 && c !== 0x46) { this.bad('a boolean field holds neither T nor F', p); } out[i] = c === 0x54; } return out; } case 'Z': { const out = new Array(count); for (let i = 0; i < count; i++) { out[i] = null; } return out; } case 'S': case 'H': { const out = new Array(count); const w = f.width; for (let i = 0; i < count; i++, p += st) { let e = p + w; while (e > p && b[e - 1] === 0) { e--; } out[i] = f.kind === 'S' ? utf8Decode(b, p, e) : this.highprec(b.slice(p, e)); } return out; } case 'dict': { const out = new Array(count); const w = f.width, dict = f.dict as any[], nd = dict.length; for (let i = 0; i < count; i++, p += st) { const idx = w === 1 ? b[p] : w === 2 ? v.getUint16(p, le) : w === 4 ? v.getUint32(p, le) : Number(read64(v, p, false, le)); if (!(idx < nd)) { this.bad('a dictionary index out of range', p); } out[i] = dict[idx]; } return out; } case 'off': { const out = new Array(count); const t = tables[f.table as number], off = t.off, m = f.marker as string; const save = this.pos; for (let i = 0; i < count; i++, p += st) { this.pos = p; const x = this.num(m); const idx = typeof x === 'bigint' ? Number(x) : x; if (!(idx >= 0 && idx < count)) { this.pos = save; this.bad('a string index out of range', p); } out[i] = utf8Decode(b, t.text + off[idx], t.text + off[idx + 1]); } this.pos = save; return out; } } return null; }; // the tree of the schema with each leaf's column interface Node { name: string; col?: any; sub?: Node[]; obj?: boolean } const nodeOf = (f: Field): Node => f.kind === 'obj' || f.kind === 'arr' ? { name: f.name, sub: (f.sub as Field[]).map(nodeOf), obj: f.kind === 'obj' } : { name: f.name, col: leafColumn(f) }; const nodes = fs.map(nodeOf); if (asColumns) { const column = (nd: Node): any => { if (nd.sub) { if (!nd.obj) { return nd.sub.map(column); } const o: any = {}; for (const g of nd.sub) { setKey(o, g.name, column(g)); } return o; } return nd.col; }; const r: any = {}; for (const nd of nodes) { setKey(r, nd.name, column(nd)); } return r; } const records = new Array(count); for (let i = 0; i < count; i++) { records[i] = {}; } // field by field over all records: each loop adds one key to objects of one shape const fill = (list: Node[], objs: any[]) => { for (const nd of list) { const name = nd.name; let vals: any; if (nd.sub) { vals = new Array(count); for (let i = 0; i < count; i++) { vals[i] = nd.obj ? {} : []; } if (nd.obj) { fill(nd.sub, vals); } else { for (const g of nd.sub) { fillArr(g, vals); } } } else { vals = nd.col; } if (name === '__proto__') { for (let i = 0; i < count; i++) { setKey(objs[i], name, vals[i]); } } else { for (let i = 0; i < count; i++) { objs[i][name] = vals[i]; } } } }; const fillArr = (nd: Node, arrs: any[][]) => { let vals: any; if (nd.sub) { vals = new Array(count); for (let i = 0; i < count; i++) { vals[i] = nd.obj ? {} : []; } if (nd.obj) { fill(nd.sub, vals); } else { for (const g of nd.sub) { fillArr(g, vals); } } } else { vals = nd.col; } for (let i = 0; i < count; i++) { arrs[i].push(vals[i]); } }; fill(nodes, records); return dims && dims.length > 1 ? nest(records, dims, order) : records; } } function collectOffsets(fs: Field[], out: Field[]): void { for (const f of fs) { if (f.kind === 'off') { out.push(f); } else if (f.sub) { collectOffsets(f.sub, out); } } } /** Sets a member, also one named __proto__ (as JSON.parse does), without touching the prototype. */ export function setKey(o: any, k: string, v: any): void { if (k === '__proto__') { Object.defineProperty(o, k, { value: v, writable: true, enumerable: true, configurable: true }); } else { o[k] = v; } } /** Nested arrays of the shape dims from flat data in row-major ('C') or column-major ('F') order. */ export function nest(data: ArrayLike, dims: number[], order: 'C' | 'F' = 'C'): any { const nd = dims.length; if (nd === 0) { return data.length ? data[0] : []; } // strides of each dimension in the flat data const stride = new Array(nd); if (order === 'C') { let s = 1; for (let k = nd - 1; k >= 0; k--) { stride[k] = s; s *= dims[k]; } } else { let s = 1; for (let k = 0; k < nd; k++) { stride[k] = s; s *= dims[k]; } } const build = (k: number, at: number): any => { const out = new Array(dims[k]); if (k === nd - 1) { for (let i = 0; i < dims[k]; i++) { out[i] = data[at + i * stride[k]]; } } else { for (let i = 0; i < dims[k]; i++) { out[i] = build(k + 1, at + i * stride[k]); } } return out; }; return build(0, 0); } /** The first top-level value of the input (no-op markers before it are skipped). */ export function loadb(input: any, opts: DecodeOptions = {}): any { const d = new Decoder(input, opts); if (!d.skipNoop()) { throw new BJDataError('no value in the input', 0); } return d.value(); } /** Every top-level value of the input, in order (a JSON-Mmap file: [table, document]). */ export function loadbAll(input: any, opts: DecodeOptions = {}): any[] { const d = new Decoder(input, opts); const out: any[] = []; while (d.skipNoop()) { out.push(d.value()); } return out; } /** The value at a byte offset and the offset after it: [value, nextOffset]. */ export function decodeAt(input: any, offset: number = 0, opts: DecodeOptions = {}): [any, number] { const d = new Decoder(input, opts); d.pos = offset; if (!d.skipNoop()) { throw new BJDataError('no value in the input', offset); } const v = d.value(); return [v, d.pos]; }