/** * BJData encoder (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, MARKER_OF_TYPE, HOST_LITTLE, HighPrec, Extension, BJDataError, write64, floatToHalf, utf8Encode, utf8Into, markerOfTypedArray, isTypedArray } from './types'; export interface EncodeOptions { /** write the count (#) of arrays and objects instead of an end marker (default false) */ count?: boolean; /** pack arrays of numbers into typed containers ([$type#n]), and rectangular nested arrays of * numbers into N-D ones ([$type#[dims]]) (default false; typed arrays are always packed) */ pack?: boolean; /** store a non-integer number as float32 ([d]) when that is exact (default false: [D]) */ float32?: boolean; /** write arrays of objects that share their keys and value types as a structure-of-arrays: * 'row' ([$), 'col' ({$), or false (default) */ soa?: false | 'row' | 'col'; /** the fewest records written as a structure-of-arrays (default 2) */ soaThreshold?: number; /** write the keys of each object sorted (default false) */ sortKeys?: boolean; /** Date values: 'string' (default, ISO 8601 as JSON.stringify), 'extension' (datetime_us) */ date?: 'string' | 'extension'; /** byte order: 'little' (BJData, default) or 'big' (UBJSON) */ endian?: 'little' | 'big'; /** called for a value that has no BJData form (a function, symbol, ...); its result is * written instead; default: such values are skipped in objects, null in arrays */ replacer?: (value: any) => any; /** maximum nesting (default 1000) */ maxDepth?: number; } const MAX_SAFE = 9007199254740991; /** The marker of an integer, as pybj chooses it: unsigned for non-negative values, signed else. */ function intMarker(x: number): string { if (x >= 0) { return x < 256 ? 'U' : x < 65536 ? 'u' : x < 4294967296 ? 'm' : 'M'; } return x >= -128 ? 'i' : x >= -32768 ? 'I' : x >= -2147483648 ? 'l' : 'L'; } /** The smallest integer type holding every value between lo and hi. */ function rangeMarker(lo: number, hi: number): string { if (lo >= 0) { return intMarker(hi); } const a = intMarker(lo), b = hi < 128 ? 'i' : hi < 32768 ? 'I' : hi < 2147483648 ? 'l' : 'L'; const rank = 'iIlL'; return rank.indexOf(a) >= rank.indexOf(b) ? a : b; } export class Encoder { private buf: Uint8Array; private v: DataView; pos = 0; private little: boolean; private o: EncodeOptions; private stack: any[] = []; private maxDepth: number; constructor(opts: EncodeOptions = {}) { this.o = opts; this.little = opts.endian !== 'big'; this.maxDepth = opts.maxDepth === undefined ? 1000 : opts.maxDepth; this.buf = new Uint8Array(1024); this.v = new DataView(this.buf.buffer); } /** The bytes written so far. */ result(): Uint8Array { return this.pos === this.buf.length ? this.buf : this.buf.slice(0, this.pos); } private ensure(k: number): void { const need = this.pos + k; if (need <= this.buf.length) { return; } // (doubling; a large write gets exactly its room, so a lone big array needs no final copy) const nb = new Uint8Array(Math.max(this.buf.length * 2, need)); nb.set(this.buf.subarray(0, this.pos)); this.buf = nb; this.v = new DataView(nb.buffer); } private byte(c: number): void { this.ensure(1); this.buf[this.pos++] = c; } private marker(m: string): void { this.ensure(1); this.buf[this.pos++] = m.charCodeAt(0); } /** A number of marker m without its marker. */ private raw(m: string, x: any): void { const size = FIXED_SIZE[m]; this.ensure(size); const v = this.v, at = this.pos, le = this.little; switch (m) { case 'i': v.setInt8(at, Number(x)); break; case 'U': case 'B': case 'C': v.setUint8(at, Number(x)); break; case 'I': v.setInt16(at, Number(x), le); break; case 'u': v.setUint16(at, Number(x), le); break; case 'l': v.setInt32(at, Number(x), le); break; case 'm': v.setUint32(at, Number(x), le); break; case 'L': case 'M': write64(v, at, x, m === 'L', le); break; case 'h': v.setUint16(at, floatToHalf(Number(x)), le); break; case 'd': v.setFloat32(at, Number(x), le); break; case 'D': v.setFloat64(at, Number(x), le); break; } this.pos += size; } /** An integer (|x| <= 2^53) with the marker pybj picks. */ private int(x: number): void { this.ensure(9); const b = this.buf, p = this.pos; if (x >= 0) { if (x < 256) { b[p] = 0x55; // U b[p + 1] = x; this.pos = p + 2; } else if (x < 65536) { b[p] = 0x75; // u this.v.setUint16(p + 1, x, this.little); this.pos = p + 3; } else if (x < 4294967296) { b[p] = 0x6d; // m this.v.setUint32(p + 1, x, this.little); this.pos = p + 5; } else { b[p] = 0x4d; // M write64(this.v, p + 1, x, false, this.little); this.pos = p + 9; } } else if (x >= -128) { b[p] = 0x69; // i b[p + 1] = x & 255; this.pos = p + 2; } else if (x >= -32768) { b[p] = 0x49; // I this.v.setInt16(p + 1, x, this.little); this.pos = p + 3; } else if (x >= -2147483648) { b[p] = 0x6c; // l this.v.setInt32(p + 1, x, this.little); this.pos = p + 5; } else { b[p] = 0x4c; // L write64(this.v, p + 1, x, true, this.little); this.pos = p + 9; } } private bigint(x: bigint): void { const zero = BigInt(0); if (x >= zero ? x < BigInt('18446744073709551616') : x >= BigInt('-9223372036854775808')) { if (x >= BigInt(-MAX_SAFE) && x <= BigInt(MAX_SAFE)) { this.int(Number(x)); return; } const m = x >= zero ? 'M' : 'L'; this.marker(m); this.raw(m, x); return; } this.highprec(utf8Encode(x.toString())); } private highprec(b: Uint8Array): void { this.marker('H'); this.int(b.length); this.bytes(b); } private bytes(b: Uint8Array): void { this.ensure(b.length); this.buf.set(b, this.pos); this.pos += b.length; } /** A string's length and bytes (a key, or the payload of [S]). */ private str(s: string): void { const n = s.length; this.ensure(3 * n + 9); const b = this.buf, p = this.pos; if (n <= 32) { // ASCII (most keys and short strings): written as we check let k = 0; for (; k < n; k++) { const c = s.charCodeAt(k); if (c > 127) { break; } b[p + 2 + k] = c; } if (k === n) { b[p] = 0x55; // U b[p + 1] = n; this.pos = p + 2 + n; return; } } // the bytes after room for the widest length its UTF-8 could need, then the length const most = 3 * n; const room = most < 256 ? 2 : most < 65536 ? 3 : most < 4294967296 ? 5 : 9; const len = utf8Into(s, b, p + room); const head = len < 256 ? 2 : len < 65536 ? 3 : len < 4294967296 ? 5 : 9; if (head !== room) { b.copyWithin(p + head, p + room, p + room + len); } this.int(len); this.pos = p + head + len; } private number(x: number): void { if (Number.isInteger(x) && x >= -MAX_SAFE && x <= MAX_SAFE && !(x === 0 && 1 / x < 0)) { this.int(x); return; } this.ensure(9); const p = this.pos; if (this.o.float32 && Math.fround(x) === x) { this.buf[p] = 0x64; // d this.v.setFloat32(p + 1, x, this.little); this.pos = p + 5; } else { this.buf[p] = 0x44; // D this.v.setFloat64(p + 1, x, this.little); this.pos = p + 9; } } /** Writes one value. */ value(x: any): void { switch (typeof x) { case 'number': this.number(x); return; case 'string': { if (x.length === 1 && x.charCodeAt(0) < 128) { this.ensure(2); this.buf[this.pos] = 0x43; // C this.buf[this.pos + 1] = x.charCodeAt(0); this.pos += 2; } else { this.byte(0x53); // S this.str(x); } return; } case 'boolean': this.byte(x ? 0x54 : 0x46); return; case 'bigint': this.bigint(x); return; case 'undefined': this.byte(0x5a); return; case 'object': break; default: { if (this.o.replacer) { const r = this.o.replacer(x); if (r !== x) { this.value(r); return; } } this.byte(0x5a); return; } } if (x === null) { this.byte(0x5a); return; } // the common containers first: arrays and plain objects if (Array.isArray(x)) { this.enter(x); this.array(x); this.depth--; return; } const proto = Object.getPrototypeOf(x); if ((proto === Object.prototype || proto === null) && typeof x.toJSON !== 'function') { this.enter(x); if (!this.ndobject(x)) { this.plain(x); } this.depth--; return; } if (x instanceof HighPrec) { this.highprec(x.bytes); return; } if (x instanceof Extension) { this.marker('E'); this.int(x.type); this.int(x.data.length); this.bytes(x.data); return; } if (x instanceof Date) { if (this.o.date === 'extension') { this.value(Extension.fromDate(x)); } else { this.value(isNaN(x.getTime()) ? null : x.toISOString()); } return; } if (isTypedArray(x)) { const m = markerOfTypedArray(x); if (m) { this.packed(m, x, null, 'C'); return; } } if (x instanceof ArrayBuffer || x instanceof DataView || Object.prototype.toString.call(x) === '[object ArrayBuffer]') { const b = x instanceof DataView ? new Uint8Array(x.buffer, x.byteOffset, x.byteLength) : new Uint8Array(x); this.packed('B', b, null, 'C'); return; } if (typeof x.toJSON === 'function' && !(x instanceof Map) && !(x instanceof Set)) { // (as JSON.stringify: the result of toJSON, whose own toJSON is not called) const y = x.toJSON(); if (y !== x) { this.value(y); return; } } this.enter(x); if (x instanceof Map) { this.object(Array.from(x.entries()).map((e) => [String(e[0]), e[1]])); } else if (x instanceof Set) { this.array(Array.from(x)); } else if (!this.ndobject(x)) { this.plain(x); } this.depth--; } // the containers being written (for circular references), stack[0 .. depth-1] private depth = 0; private enter(x: any): void { const st = this.stack, d = this.depth; for (let k = 0; k < d; k++) { if (st[k] === x) { this.depth = 0; throw new BJDataError('cannot serialize a circular structure'); } } if (d >= this.maxDepth) { this.depth = 0; throw new BJDataError('values nested deeper than ' + this.maxDepth); } st[d] = x; this.depth = d + 1; } /** The members of an object (as JSON: undefined, functions and symbols are left out, unless * the replacer gives them a value). */ private plain(x: any): void { const keys = Object.keys(x); if (this.o.sortKeys) { keys.sort(); } if (this.o.count || this.o.replacer) { this.object(keys.map((k) => [k, x[k]])); return; } this.byte(0x7b); // { for (let i = 0; i < keys.length; i++) { const k = keys[i], v = x[k]; const t = typeof v; if (t === 'undefined' || t === 'function' || t === 'symbol') { continue; } this.str(k); this.value(v); } this.byte(0x7d); // } } private object(entries: [string, any][]): void { const list: [string, any][] = []; for (const [k, v0] of entries) { let v = v0; if ((typeof v === 'function' || typeof v === 'symbol') && this.o.replacer) { v = this.o.replacer(v); } if (v !== undefined && typeof v !== 'function' && typeof v !== 'symbol') { list.push([k, v]); } } this.marker('{'); if (this.o.count) { this.marker('#'); this.int(list.length); } for (const [k, v] of list) { this.str(k); this.value(v); } if (!this.o.count) { this.marker('}'); } } private array(a: any[]): void { if (this.o.soa && a.length >= (this.o.soaThreshold || 2) && this.soa(a)) { return; } if (this.o.pack && a.length) { const nd = numericShape(a); if (nd) { this.packed(nd.marker, nd.flat, nd.dims.length > 1 ? nd.dims : null, 'C'); return; } } this.marker('['); if (this.o.count) { this.marker('#'); this.int(a.length); } for (const e of a) { this.value(e); } if (!this.o.count) { this.marker(']'); } } /** [$m#n payload] or [$m#[dims] payload]. */ private packed(m: string, data: ArrayLike, dims: number[] | null, order: 'C' | 'F'): void { this.marker('['); this.marker('$'); this.marker(m); this.marker('#'); if (dims) { if (order === 'F') { this.marker('['); } this.dims(dims); if (order === 'F') { this.marker(']'); } } else { this.int(data.length); } const size = FIXED_SIZE[m]; const n = data.length; if (isTypedArray(data) && markerOfTypedArray(data) === m && m !== 'h' && (size === 1 || this.little === HOST_LITTLE)) { const d = data as any; this.bytes(new Uint8Array(d.buffer, d.byteOffset, d.byteLength)); return; } this.ensure(n * size); this.column(m, data, this.pos, size); this.pos += n * size; } /** The numbers vals of marker m at p, p + st, p + 2 st, ... (room already ensured). */ private column(m: string, vals: ArrayLike, p: number, st: number): void { const b = this.buf, v = this.v, le = this.little, n = vals.length; switch (m) { case 'U': case 'B': case 'C': case 'i': for (let i = 0; i < n; i++, p += st) { b[p] = Number(vals[i]); } break; case 'I': for (let i = 0; i < n; i++, p += st) { v.setInt16(p, Number(vals[i]), le); } break; case 'u': for (let i = 0; i < n; i++, p += st) { v.setUint16(p, Number(vals[i]), le); } break; case 'l': for (let i = 0; i < n; i++, p += st) { v.setInt32(p, Number(vals[i]), le); } break; case 'm': for (let i = 0; i < n; i++, p += st) { v.setUint32(p, Number(vals[i]), le); } break; case 'L': case 'M': { const signed = m === 'L'; for (let i = 0; i < n; i++, p += st) { write64(v, p, vals[i], signed, le); } break; } case 'h': for (let i = 0; i < n; i++, p += st) { v.setUint16(p, floatToHalf(Number(vals[i])), le); } break; case 'd': for (let i = 0; i < n; i++, p += st) { v.setFloat32(p, Number(vals[i]), le); } break; case 'D': for (let i = 0; i < n; i++, p += st) { v.setFloat64(p, Number(vals[i]), le); } break; } } private dims(d: number[]): void { let hi = 0; for (const x of d) { if (!(Number.isInteger(x) && x >= 0)) { throw new BJDataError('an invalid array dimension ' + x); } hi = Math.max(hi, x); } const m = intMarker(hi); this.marker('['); this.marker('$'); this.marker(m); this.marker('#'); this.int(d.length); for (const x of d) { this.raw(m, x); } } /** A JData N-D array object {_ArrayType_, _ArraySize_, _ArrayData_: TypedArray} (nothing else * but _ArrayOrder_), or an ndarray-like value (numjs, scijs ndarray), as a packed N-D array. */ private ndobject(x: any): boolean { if (x._ArrayType_ !== undefined && x._ArraySize_ !== undefined && x._ArrayData_ !== undefined) { const keys = Object.keys(x); if (keys.some((k) => ['_ArrayType_', '_ArraySize_', '_ArrayData_', '_ArrayOrder_'].indexOf(k) < 0)) { return false; } const m = MARKER_OF_TYPE[String(x._ArrayType_).toLowerCase()]; const dims = Array.from(x._ArraySize_ as ArrayLike, Number); const data = x._ArrayData_; if (!m || !(isTypedArray(data) || Array.isArray(data))) { return false; } const total = dims.reduce((a: number, b: number) => a * b, 1); if (data.length !== total || Array.isArray(data) && data.some((e: any) => typeof e !== 'number' && typeof e !== 'bigint')) { return false; } const ord = String(x._ArrayOrder_ || 'r').toLowerCase(); this.packed(m, data, dims, ord[0] === 'c' ? 'F' : 'C'); return true; } // numjs NdArray: selection (scijs ndarray), shape, dtype if (x.selection && x.shape && typeof x.flatten === 'function' && x.selection.data) { const flat = x.flatten().selection.data; const m = markerOfTypedArray(flat) || 'D'; this.packed(m, flat, Array.from(x.shape as number[]), 'C'); return true; } // scijs ndarray: data, shape, stride, offset (contiguous row-major only) if (isTypedArray(x.data) && Array.isArray(x.shape) && Array.isArray(x.stride) && typeof x.offset === 'number') { const m = markerOfTypedArray(x.data); let s = 1, contiguous = x.offset === 0; for (let k = x.shape.length - 1; k >= 0 && contiguous; k--) { contiguous = x.stride[k] === s; s *= x.shape[k]; } if (m && contiguous && x.data.length === s) { this.packed(m, x.data, x.shape.slice(), 'C'); return true; } } return false; } // ---- structure-of-arrays ---------------------------------------------------------------- private soa(a: any[]): boolean { const s = soaSchema(a, this.o.float32 === true); if (!s) { return false; } const columnar = this.o.soa === 'col'; const count = a.length; this.marker(columnar ? '{' : '['); this.marker('$'); this.marker('{'); this.schemaOut(s); this.marker('}'); this.marker('#'); this.int(count); // the leaves in schema order, each with its values (one array per leaf) const leaves: { f: SField; vals: any[] }[] = []; const walk = (fs: SField[]) => { for (const f of fs) { const vals = f.vals as any[]; if (f.kind === 'obj') { walk(f.sub as SField[]); } else if (f.kind === 'arr') { for (let k = 0; k < (f.len as number); k++) { const e = new Array(count); for (let i = 0; i < count; i++) { e[i] = vals[i][k]; } leaves.push({ f: { key: '', kind: 'n', marker: f.marker }, vals: e }); } } else { leaves.push({ f, vals }); } } }; walk(s); const widthOf = (f: SField) => f.kind === 'n' || f.kind === 'off' ? FIXED_SIZE[f.marker as string] : f.kind === 'Z' ? 0 : 1; let rec = 0; for (const l of leaves) { rec += widthOf(l.f); } // the payload: each leaf written over all records (row-major: strided) this.ensure(rec * count); const base = this.pos, b = this.buf; let inrec = 0; for (const l of leaves) { const f = l.f, vals = l.vals, w = widthOf(f); let p = columnar ? base + inrec * count : base + inrec; const st = columnar ? w : rec; switch (f.kind) { case 'n': this.column(f.marker as string, vals, p, st); break; case 'T': for (let i = 0; i < count; i++, p += st) { b[p] = vals[i] ? 0x54 : 0x46; } break; case 'dict': { const index = f.index as Map; for (let i = 0; i < count; i++, p += st) { b[p] = index.get(vals[i]) as number; } break; } case 'off': { const idx = new Array(count); for (let i = 0; i < count; i++) { idx[i] = i; } this.column(f.marker as string, idx, p, st); break; } } inrec += w; } this.pos = base + rec * count; // the offset tables, each followed by its text for (const l of leaves) { if (l.f.kind !== 'off') { continue; } const m = l.f.marker as string, w = FIXED_SIZE[m], vals = l.vals; let total = 0; for (let i = 0; i < count; i++) { total += utf8Length(vals[i]); } this.ensure((count + 1) * w + total); const table = this.pos; const offs = new Array(count + 1); let at = table + (count + 1) * w, o = 0; offs[0] = 0; for (let i = 0; i < count; i++) { const len = utf8Into(vals[i], this.buf, at); at += len; o += len; offs[i + 1] = o; } this.column(m, offs, table, w); this.pos = at; } return true; } private schemaOut(fs: SField[]): void { for (const f of fs) { this.str(f.key); switch (f.kind) { case 'n': this.marker(f.marker as string); break; case 'T': this.marker('T'); break; case 'Z': this.marker('Z'); break; case 'dict': { this.marker('['); this.marker('$'); this.marker('S'); this.marker('#'); const d = f.dict as string[]; this.int(d.length); for (const e of d) { this.str(e); } break; } case 'off': this.marker('['); this.marker('$'); this.marker(f.marker as string); this.marker(']'); break; case 'obj': this.marker('{'); this.schemaOut(f.sub as SField[]); this.marker('}'); break; case 'arr': this.marker('['); for (let k = 0; k < (f.len as number); k++) { this.marker(f.marker as string); } this.marker(']'); break; } } } } interface SField { key: string; kind: 'n' | 'T' | 'Z' | 'dict' | 'off' | 'obj' | 'arr'; marker?: string; sub?: SField[]; len?: number; dict?: string[]; index?: Map; vals?: any[]; // the values of the field in the records } function isPlainObject(x: any): boolean { if (x === null || typeof x !== 'object' || Array.isArray(x)) { return false; } const p = Object.getPrototypeOf(x); return p === Object.prototype || p === null; } /** The marker holding a list of numbers (all integers: the smallest integer type; else D or d). */ function numbersMarker(vals: any[], float32: boolean): string | null { let lo = Infinity, hi = -Infinity, ints = true, f32 = float32; for (const x of vals) { if (typeof x !== 'number') { return null; } if (ints && !(Number.isInteger(x) && Math.abs(x) <= MAX_SAFE && !(x === 0 && 1 / x < 0))) { ints = false; } if (f32 && Math.fround(x) !== x) { f32 = false; } if (x < lo) { lo = x; } if (x > hi) { hi = x; } } if (ints) { return rangeMarker(lo, hi); } return f32 ? 'd' : 'D'; } /** The schema of an array of records with the same keys and value kinds, or null. */ function soaSchema(recs: any[], float32: boolean): SField[] | null { if (!recs.every(isPlainObject)) { return null; } const keys = Object.keys(recs[0]); if (!keys.length) { return null; } const nk = keys.length; for (let j = 1; j < recs.length; j++) { // (the same keys in the same order, without a key array per record) let i = 0; for (const k in recs[j]) { if (k !== keys[i++]) { return null; } } if (i !== nk) { return null; } } const fs: SField[] = []; const count = recs.length; for (const key of keys) { const vals = new Array(count); for (let i = 0; i < count; i++) { vals[i] = recs[i][key]; } const t0 = typeof vals[0]; let f: SField | null = null; if (t0 === 'number') { const m = numbersMarker(vals, float32); if (m) { f = { key, kind: 'n', marker: m }; } } else if (t0 === 'boolean') { if (vals.every((x) => typeof x === 'boolean')) { f = { key, kind: 'T' }; } } else if (vals[0] === null) { if (vals.every((x) => x === null)) { f = { key, kind: 'Z' }; } } else if (t0 === 'string') { if (vals.every((x) => typeof x === 'string')) { const uniq = Array.from(new Set(vals)); if (uniq.length <= 255 && uniq.length * 2 <= vals.length) { const index = new Map(); uniq.forEach((s, i) => index.set(s, i)); f = { key, kind: 'dict', dict: uniq, index, marker: 'U' }; } else { let total = 0; for (const s of vals) { total += utf8Length(s); } const m = Math.max(total, vals.length) < 256 ? 'U' : Math.max(total, vals.length) < 65536 ? 'u' : 'm'; f = { key, kind: 'off', marker: m }; } } } else if (Array.isArray(vals[0])) { const len = vals[0].length; if (len > 0 && vals.every((x) => Array.isArray(x) && x.length === len)) { const all: any[] = []; for (const x of vals) { for (const e of x) { all.push(e); } } const m = numbersMarker(all, float32); if (m) { f = { key, kind: 'arr', marker: m, len }; } } } else if (isPlainObject(vals[0])) { const sub = soaSchema(vals, float32); if (sub) { f = { key, kind: 'obj', sub }; } } if (!f) { return null; } f.vals = vals; fs.push(f); } // (a record of no bytes, only null fields, is not allowed) return recordWidth(fs) > 0 ? fs : null; } function recordWidth(fs: SField[]): number { let w = 0; for (const f of fs) { switch (f.kind) { case 'n': case 'off': w += FIXED_SIZE[f.marker as string]; break; case 'dict': w += 1; break; case 'T': w += 1; break; case 'obj': w += recordWidth(f.sub as SField[]); break; case 'arr': w += FIXED_SIZE[f.marker as string] * (f.len as number); break; } } return w; } /** The marker, dimensions and flat values of a (nested, rectangular) array of numbers or BigInts, * or null. */ function numericShape(a: any[]): { marker: string; dims: number[]; flat: any[] } | null { const dims: number[] = []; let x: any = a; while (Array.isArray(x)) { if (!x.length) { return null; } dims.push(x.length); x = x[0]; } let flat: any[] = a; if (dims.length > 1) { flat = []; const walk = (y: any, k: number): boolean => { if (!Array.isArray(y) || y.length !== dims[k]) { return false; } if (k === dims.length - 1) { for (let i = 0; i < y.length; i++) { flat.push(y[i]); } return true; } for (const e of y) { if (!walk(e, k + 1)) { return false; } } return true; }; if (!walk(a, 0)) { return null; } } const m = numbersMarker(flat, false); if (m) { return { marker: m, dims, flat }; } // (BigInts, with integers) let big = false, neg = false; for (const e of flat) { if (typeof e === 'bigint') { big = true; } else if (!(typeof e === 'number' && Number.isInteger(e))) { return null; } if (e < 0) { neg = true; } } return big ? { marker: neg ? 'L' : 'M', dims, flat } : null; } /** The number of UTF-8 bytes of s (lone surrogates: 3, as U+FFFD). */ function utf8Length(s: string): number { let n = s.length; for (let k = 0; k < s.length; k++) { const c = s.charCodeAt(k); if (c < 0x80) { continue; } if (c < 0x800) { n += 1; } else if (c >= 0xd800 && c < 0xdc00 && k + 1 < s.length && (s.charCodeAt(k + 1) & 0xfc00) === 0xdc00) { n += 2; // (a pair: 4 bytes for 2 units) k++; } else { n += 2; } } return n; } /** The BJData bytes of a value. */ export function dumpb(value: any, opts: EncodeOptions = {}): Uint8Array { const e = new Encoder(opts); e.value(value); return e.result(); }