-
Notifications
You must be signed in to change notification settings - Fork 170
/
Copy pathreuse-instances-with-extensions.test.ts
48 lines (38 loc) · 1.57 KB
/
reuse-instances-with-extensions.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// https://github.com/msgpack/msgpack-javascript/issues/195
import { deepStrictEqual } from "assert";
import { Encoder, Decoder, ExtensionCodec } from "../src/index";
const MSGPACK_EXT_TYPE_BIGINT = 0;
function registerCodecs(context: MsgPackContext) {
const { extensionCodec, encode, decode } = context;
extensionCodec.register({
type: MSGPACK_EXT_TYPE_BIGINT,
encode: (value) => (typeof value === "bigint" ? encode(value.toString()) : null),
decode: (data) => BigInt(decode(data) as string),
});
}
class MsgPackContext {
readonly encode: (value: unknown) => Uint8Array;
readonly decode: (buffer: BufferSource | ArrayLike<number>) => unknown;
readonly extensionCodec = new ExtensionCodec<MsgPackContext>();
constructor() {
const encoder = new Encoder({ extensionCodec: this.extensionCodec, context: this });
const decoder = new Decoder({ extensionCodec: this.extensionCodec, context: this });
this.encode = encoder.encode.bind(encoder);
this.decode = decoder.decode.bind(decoder);
registerCodecs(this);
}
}
describe("reuse instances with extensions", () => {
it("should encode and decode a bigint", () => {
const context = new MsgPackContext();
const buf = context.encode(BigInt(42));
const data = context.decode(buf);
deepStrictEqual(data, BigInt(42));
});
it("should encode and decode bigints", () => {
const context = new MsgPackContext();
const buf = context.encode([BigInt(1), BigInt(2), BigInt(3)]);
const data = context.decode(buf);
deepStrictEqual(data, [BigInt(1), BigInt(2), BigInt(3)]);
});
});