UNPKG

@eyhn/msgpack-stream

Version:

MessagePack for ECMA-262/JavaScript/TypeScript

68 lines 2.26 kB
// ExtensionCodec to handle MessagePack extensions import { ExtData } from "./ExtData.mjs"; import { timestampExtension } from "./timestamp.mjs"; export class ExtensionCodec { constructor() { // built-in extensions this.builtInEncoders = []; this.builtInDecoders = []; // custom extensions this.encoders = []; this.decoders = []; this.register(timestampExtension); } register({ type, encode, decode, }) { if (type >= 0) { // custom extensions this.encoders[type] = encode; this.decoders[type] = decode; } else { // built-in extensions const index = 1 + type; this.builtInEncoders[index] = encode; this.builtInDecoders[index] = decode; } } tryToEncode(object, context) { // built-in extensions for (let i = 0; i < this.builtInEncoders.length; i++) { const encodeExt = this.builtInEncoders[i]; if (encodeExt != null) { const data = encodeExt(object, context); if (data != null) { const type = -1 - i; return new ExtData(type, data); } } } // custom extensions for (let i = 0; i < this.encoders.length; i++) { const encodeExt = this.encoders[i]; if (encodeExt != null) { const data = encodeExt(object, context); if (data != null) { const type = i; return new ExtData(type, data); } } } if (object instanceof ExtData) { // to keep ExtData as is return object; } return null; } decode(data, type, context) { const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type]; if (decodeExt) { return decodeExt(data, type, context); } else { // decode() does not fail, returns ExtData instead. return new ExtData(type, data); } } } ExtensionCodec.defaultCodec = new ExtensionCodec(); //# sourceMappingURL=ExtensionCodec.mjs.map