deno.land / x / msgpack_javascript@v3.0.0-beta2 / test / codec-bigint.test.ts

codec-bigint.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import assert from "assert";import { encode, decode, ExtensionCodec, DecodeError } from "../src";
// There's a built-in `useBigInt64: true` option, but a custom codec might be// better if you'd like to encode bigint to reduce the size of binaries.
const BIGINT_EXT_TYPE = 0; // Any in 0-127
const extensionCodec = new ExtensionCodec();extensionCodec.register({ type: BIGINT_EXT_TYPE, encode(input: unknown): Uint8Array | null { if (typeof input === "bigint") { if (input <= Number.MAX_SAFE_INTEGER && input >= Number.MIN_SAFE_INTEGER) { return encode(Number(input)); } else { return encode(String(input)); } } else { return null; } }, decode(data: Uint8Array): bigint { const val = decode(data); if (!(typeof val === "string" || typeof val === "number")) { throw new DecodeError(`unexpected BigInt source: ${val} (${typeof val})`); } return BigInt(val); },});
describe("codec BigInt", () => { it("encodes and decodes 0n", () => { const value = BigInt(0); const encoded = encode(value, { extensionCodec }); assert.deepStrictEqual(decode(encoded, { extensionCodec }), value); });
it("encodes and decodes 100n", () => { const value = BigInt(100); const encoded = encode(value, { extensionCodec }); assert.deepStrictEqual(decode(encoded, { extensionCodec }), value); });
it("encodes and decodes -100n", () => { const value = BigInt(-100); const encoded = encode(value, { extensionCodec }); assert.deepStrictEqual(decode(encoded, { extensionCodec }), value); });
it("encodes and decodes MAX_SAFE_INTEGER+1", () => { const value = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1); const encoded = encode(value, { extensionCodec }); assert.deepStrictEqual(decode(encoded, { extensionCodec }), value); });
it("encodes and decodes MIN_SAFE_INTEGER-1", () => { const value = BigInt(Number.MIN_SAFE_INTEGER) - BigInt(1); const encoded = encode(value, { extensionCodec }); assert.deepStrictEqual(decode(encoded, { extensionCodec }), value); });});
msgpack_javascript

Version Info

Tagged at
a year ago