import { Annotated } from "./annotated"; import { DecodeError, ShortPacket } from "./codec"; import { Tag } from "./constants"; import { Set, Dictionary } from "./dictionary"; import { DoubleFloat, SingleFloat } from "./float"; import { Record } from "./record"; import { Bytes, BytesLike, underlying } from "./bytes"; import { Value } from "./values"; import { is } from "./is"; export interface DecoderOptions { includeAnnotations?: boolean; } export interface DecoderPointerOptions extends DecoderOptions { decodePointer?(d: TypedDecoder): T | undefined; } export interface TypedDecoder { atEnd(): boolean; mark(): any; restoreMark(m: any): void; skip(): void; next(): Value; withPointerDecoder(decodePointer: (d: TypedDecoder) => S | undefined, body: (d: TypedDecoder) => R): R; nextBoolean(): boolean | undefined; nextFloat(): SingleFloat | undefined; nextDouble(): DoubleFloat | undefined; nextPointer(): T | undefined; nextSignedInteger(): number | undefined; nextString(): string | undefined; nextByteString(): Bytes | undefined; nextSymbol(): symbol | undefined; openRecord(): boolean; openSequence(): boolean; openSet(): boolean; openDictionary(): boolean; closeCompound(): boolean; } export function asLiteral, Annotated>>( actual: Value, expected: E): E | undefined { return is(actual, expected) ? expected : void 0; } function _defaultDecodePointer(_d: TypedDecoder): T | undefined { throw new DecodeError("No decodePointer function supplied"); } export class Decoder implements TypedDecoder { packet: Uint8Array; index = 0; options: DecoderOptions; decodePointer: ((d: TypedDecoder) => T | undefined) = _defaultDecodePointer; constructor(packet: BytesLike = new Uint8Array(0), options: DecoderOptions = {}) { this.packet = underlying(packet); this.options = options; } get includeAnnotations(): boolean { return this.options.includeAnnotations ?? false; } write(data: BytesLike) { if (this.index === this.packet.length) { this.packet = underlying(data); } else { this.packet = Bytes.concat([this.packet.slice(this.index), data])._view; } this.index = 0; } nextbyte(): number { if (this.atEnd()) throw new ShortPacket("Short packet"); return this.packet[this.index++]; } nextbytes(n: number): DataView { const start = this.index; this.index += n; if (this.index > this.packet.length) throw new ShortPacket("Short packet"); // ^ NOTE: greater-than, not greater-than-or-equal-to - this makes atEnd() inappropriate return new DataView(this.packet.buffer, this.packet.byteOffset + start, n); } varint(): number { // TODO: Bignums :-/ const v = this.nextbyte(); if (v < 128) return v; return (this.varint() << 7) + (v - 128); } peekend(): boolean { return (this.nextbyte() === Tag.End) || (this.index--, false); } nextvalues(): Value[] { const result = []; while (!this.peekend()) result.push(this.next()); return result; } nextint(n: number): number { // TODO: Bignums :-/ if (n === 0) return 0; let acc = this.nextbyte(); if (acc & 0x80) acc -= 256; for (let i = 1; i < n; i++) acc = (acc * 256) + this.nextbyte(); return acc; } wrap(v: Value): Value { return this.includeAnnotations ? new Annotated(v) : v; } static dictionaryFromArray(vs: Value[]): Dictionary { const d = new Dictionary(); if (vs.length % 2) throw new DecodeError("Missing dictionary value"); for (let i = 0; i < vs.length; i += 2) { d.set(vs[i], vs[i+1]); } return d; } unshiftAnnotation(a: Value, v: Annotated) { if (this.includeAnnotations) { v.annotations.unshift(a); } return v; } next(): Value { const tag = this.nextbyte(); switch (tag) { case Tag.False: return this.wrap(false); case Tag.True: return this.wrap(true); case Tag.Float: return this.wrap(new SingleFloat(this.nextbytes(4).getFloat32(0, false))); case Tag.Double: return this.wrap(new DoubleFloat(this.nextbytes(8).getFloat64(0, false))); case Tag.End: throw new DecodeError("Unexpected Compound end marker"); case Tag.Annotation: { const a = this.next(); const v = this.next() as Annotated; return this.unshiftAnnotation(a, v); } case Tag.Pointer: { const v = this.decodePointer(this); if (v === void 0) { throw new DecodeError("decodePointer function failed"); } return this.wrap(v); } case Tag.SignedInteger: return this.wrap(this.nextint(this.varint())); case Tag.String: return this.wrap(Bytes.from(this.nextbytes(this.varint())).fromUtf8()); case Tag.ByteString: return this.wrap(Bytes.from(this.nextbytes(this.varint()))); case Tag.Symbol: return this.wrap(Symbol.for(Bytes.from(this.nextbytes(this.varint())).fromUtf8())); case Tag.Record: { const vs = this.nextvalues(); if (vs.length === 0) throw new DecodeError("Too few elements in encoded record"); return this.wrap(Record(vs[0], vs.slice(1))); } case Tag.Sequence: return this.wrap(this.nextvalues()); case Tag.Set: return this.wrap(new Set(this.nextvalues())); case Tag.Dictionary: return this.wrap(Decoder.dictionaryFromArray(this.nextvalues())); default: { const v = this.nextSmallOrMediumInteger(tag); if (v === void 0) { throw new DecodeError("Unsupported Preserves tag: " + tag); } return this.wrap(v); } } } nextSmallOrMediumInteger(tag: number): number | undefined { if (tag >= Tag.SmallInteger_lo && tag <= Tag.SmallInteger_lo + 15) { const v = tag - Tag.SmallInteger_lo; return v > 12 ? v - 16 : v; } if (tag >= Tag.MediumInteger_lo && tag <= Tag.MediumInteger_lo + 15) { const n = tag - Tag.MediumInteger_lo; return this.nextint(n + 1); } return void 0; } shortGuard(body: () => R, short: () => R): R { if (this.atEnd()) return short(); // ^ important somewhat-common case optimization - avoid the exception const start = this.mark(); try { return body(); } catch (e) { if (ShortPacket.isShortPacket(e)) { this.restoreMark(start); return short(); } throw e; } } try_next(): Value | undefined { return this.shortGuard(() => this.next(), () => void 0); } atEnd(): boolean { return this.index >= this.packet.length; } mark(): number { return this.index; } restoreMark(m: number): void { this.index = m; } skip(): void { // TODO: be more efficient this.next(); } replacePointerDecoder(decodePointer: (d: TypedDecoder) => S | undefined): Decoder { const replacement = new Decoder(this.packet, this.options); replacement.index = this.index; replacement.decodePointer = decodePointer; this.packet = new Uint8Array(); this.index = 0; this.decodePointer = _defaultDecodePointer; return replacement; } withPointerDecoder(decodePointer: (d: TypedDecoder) => S | undefined, body: (d: TypedDecoder) => R): R { const oldDecodePointer = this.decodePointer; const disguised = this as unknown as Decoder; disguised.decodePointer = decodePointer; try { return body(disguised); } finally { this.decodePointer = oldDecodePointer; } } skipAnnotations(): void { if (!this.atEnd() && this.packet[this.index] === Tag.Annotation) { this.index++; this.skip(); } } nextBoolean(): boolean | undefined { this.skipAnnotations(); switch (this.nextbyte()) { case Tag.False: return false; case Tag.True: return true; default: return void 0; } } nextFloat(): SingleFloat | undefined { this.skipAnnotations(); switch (this.nextbyte()) { case Tag.Float: return new SingleFloat(this.nextbytes(4).getFloat32(0, false)); default: return void 0; } } nextDouble(): DoubleFloat | undefined { this.skipAnnotations(); switch (this.nextbyte()) { case Tag.Double: return new DoubleFloat(this.nextbytes(8).getFloat64(0, false)); default: return void 0; } } nextPointer(): T | undefined { this.skipAnnotations(); switch (this.nextbyte()) { case Tag.Pointer: return this.decodePointer(this); default: return void 0; } } nextSignedInteger(): number | undefined { this.skipAnnotations(); const b = this.nextbyte(); switch (b) { case Tag.SignedInteger: return this.nextint(this.varint()); default: return this.nextSmallOrMediumInteger(b); } } nextString(): string | undefined { this.skipAnnotations(); switch (this.nextbyte()) { case Tag.String: return Bytes.from(this.nextbytes(this.varint())).fromUtf8(); default: return void 0; } } nextByteString(): Bytes | undefined { this.skipAnnotations(); switch (this.nextbyte()) { case Tag.ByteString: return Bytes.from(this.nextbytes(this.varint())); default: return void 0; } } nextSymbol(): symbol | undefined { this.skipAnnotations(); switch (this.nextbyte()) { case Tag.Symbol: return Symbol.for(Bytes.from(this.nextbytes(this.varint())).fromUtf8()); default: return void 0; } } openRecord(): boolean { this.skipAnnotations(); return (this.nextbyte() === Tag.Record) || (this.index--, false); } openSequence(): boolean { this.skipAnnotations(); return (this.nextbyte() === Tag.Sequence) || (this.index--, false); } openSet(): boolean { this.skipAnnotations(); return (this.nextbyte() === Tag.Set) || (this.index--, false); } openDictionary(): boolean { this.skipAnnotations(); return (this.nextbyte() === Tag.Dictionary) || (this.index--, false); } closeCompound(): boolean { return this.peekend(); } } export function decode(bs: BytesLike, options: DecoderPointerOptions = {}): Value { return new Decoder(bs, options).withPointerDecoder>( options.decodePointer ?? _defaultDecodePointer, d => d.next()); } export function decodeWithAnnotations(bs: BytesLike, options: DecoderPointerOptions = {}): Annotated { return decode(bs, { ... options, includeAnnotations: true }) as Annotated; }