|
| 1 | +// https://github.com/msgpack/msgpack-javascript/issues/195 |
| 2 | + |
| 3 | +import { deepStrictEqual } from "assert"; |
| 4 | +import { Encoder, Decoder, ExtensionCodec } from "../src/index"; |
| 5 | + |
| 6 | +const MSGPACK_EXT_TYPE_BIGINT = 0; |
| 7 | + |
| 8 | +function registerCodecs(context: MsgPackContext) { |
| 9 | + const { extensionCodec, encode, decode } = context; |
| 10 | + |
| 11 | + extensionCodec.register({ |
| 12 | + type: MSGPACK_EXT_TYPE_BIGINT, |
| 13 | + encode: (value) => (typeof value === "bigint" ? encode(value.toString()) : null), |
| 14 | + decode: (data) => BigInt(decode(data) as string), |
| 15 | + }); |
| 16 | +} |
| 17 | + |
| 18 | +class MsgPackContext { |
| 19 | + readonly encode: (value: unknown) => Uint8Array; |
| 20 | + readonly decode: (buffer: BufferSource | ArrayLike<number>) => unknown; |
| 21 | + readonly extensionCodec = new ExtensionCodec<MsgPackContext>(); |
| 22 | + |
| 23 | + constructor() { |
| 24 | + const encoder = new Encoder<MsgPackContext>({ extensionCodec: this.extensionCodec, context: this }); |
| 25 | + const decoder = new Decoder<MsgPackContext>({ extensionCodec: this.extensionCodec, context: this }); |
| 26 | + |
| 27 | + this.encode = encoder.encode.bind(encoder); |
| 28 | + this.decode = decoder.decode.bind(decoder); |
| 29 | + |
| 30 | + registerCodecs(this); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +describe("reuse instances with extensions", () => { |
| 35 | + it("should encode and decode a bigint", () => { |
| 36 | + const context = new MsgPackContext(); |
| 37 | + const buf = context.encode(BigInt(42)); |
| 38 | + const data = context.decode(buf); |
| 39 | + deepStrictEqual(data, BigInt(42)); |
| 40 | + }); |
| 41 | +}); |
0 commit comments