Ability to feed JS Decoder

This commit is contained in:
Tony Garnock-Jones 2018-11-19 16:55:14 +00:00
parent 28cf1d37a8
commit 594b379a77
1 changed files with 21 additions and 1 deletions

View File

@ -18,11 +18,18 @@ class ShortPacket extends DecodeError {}
class Decoder {
constructor(packet, options) {
options = options || {};
this.packet = packet._view || packet; // strip off Bytes wrapper, if any
this.packet = packet
? (packet._view || packet) // strip off Bytes wrapper, if any
: new Uint8Array(0);
this.index = 0;
this.shortForms = options.shortForms || {};
}
write(data) {
this.packet = Bytes.concat([this.packet.slice(this.index), data])._view;
this.index = 0;
}
nextbyte() {
if (this.index >= this.packet.length) throw new ShortPacket("Short packet");
// ^ NOTE: greater-than-or-equal-to, not greater-than.
@ -174,6 +181,19 @@ class Decoder {
return this.decodecollection(minor, this.nextvalues(this.wirelength(arg)));
}
}
try_next() {
const start = this.index;
try {
return this.next();
} catch (e) {
if (e instanceof ShortPacket) {
this.index = start;
return void 0;
}
throw e;
}
}
}
class Encoder {