UNPKG

@devgrid/messagepack

Version:
39 lines 1.31 kB
import { SmartBuffer } from '@devgrid/smartbuffer'; import Encoder from './encoder'; import Decoder from './decoder'; export default class Serializer { constructor(initialCapacity = 64) { this.initialCapacity = initialCapacity; this.encodingTypes = new Map(); this.decodingTypes = new Map(); this.encoder = new Encoder(this.encodingTypes); this.decoder = new Decoder(this.decodingTypes); } registerEncoder(type, check, encode) { this.encodingTypes.set(type, { check, encode }); return this; } registerDecoder(type, decode) { this.decodingTypes.set(type, decode); return this; } register(type, constructor, encode, decode) { if (type < 0 || type > 127) { throw new RangeError(`Bad type: 0 <= ${type} <= 127`); } this.registerEncoder(type, (obj) => obj instanceof constructor, (obj) => { const extBuf = new SmartBuffer(this.initialCapacity, true); encode(obj, extBuf); return extBuf; }); this.registerDecoder(type, decode); return this; } encode(x, buf) { return this.encoder.encode(x, buf); } decode(buf) { return this.decoder.decode(buf); } } //# sourceMappingURL=serializer.js.map