|
1 | | -import { DecodeError, ExtensionCodec, decode, encode } from '@msgpack/msgpack'; |
| 1 | +import { Packr } from 'msgpackr'; |
2 | 2 | import { Codec } from './types'; |
3 | 3 |
|
4 | | -const BIGINT_EXT_TYPE = 0; |
5 | | -const extensionCodec = new ExtensionCodec(); |
6 | | -extensionCodec.register({ |
7 | | - type: BIGINT_EXT_TYPE, |
8 | | - encode(input: unknown): Uint8Array | null { |
9 | | - if (typeof input === 'bigint') { |
10 | | - if ( |
11 | | - input <= Number.MAX_SAFE_INTEGER && |
12 | | - input >= Number.MIN_SAFE_INTEGER |
13 | | - ) { |
14 | | - return encode(Number(input)); |
15 | | - } else { |
16 | | - return encode(String(input)); |
17 | | - } |
18 | | - } else { |
19 | | - return null; |
20 | | - } |
21 | | - }, |
22 | | - decode(data: Uint8Array): bigint { |
23 | | - const val = decode(data); |
24 | | - if (!(typeof val === 'string' || typeof val === 'number')) { |
25 | | - throw new DecodeError(`unexpected BigInt source: ${typeof val}`); |
26 | | - } |
27 | | - |
28 | | - return BigInt(val); |
29 | | - }, |
| 4 | +const packr = new Packr({ |
| 5 | + useRecords: false, |
| 6 | + moreTypes: true, |
| 7 | + bundleStrings: true, |
| 8 | + useTimestamp32: false, |
| 9 | + useBigIntExtension: true, |
| 10 | + skipValues: [undefined], |
30 | 11 | }); |
31 | 12 |
|
32 | 13 | /** |
33 | | - * Binary codec, uses [msgpack](https://www.npmjs.com/package/@msgpack/msgpack) under the hood |
| 14 | + * Binary codec, uses [msgpackr](https://www.npmjs.com/package/msgpackr) under the hood |
34 | 15 | * @type {Codec} |
35 | 16 | */ |
36 | 17 | export const BinaryCodec: Codec = { |
37 | 18 | toBuffer(obj) { |
38 | | - return encode(obj, { ignoreUndefined: true, extensionCodec }); |
| 19 | + return packr.pack(obj); |
39 | 20 | }, |
40 | 21 | fromBuffer: (buff: Uint8Array) => { |
41 | | - const res = decode(buff, { extensionCodec }); |
| 22 | + const res = packr.unpack(buff); |
42 | 23 | if (typeof res !== 'object' || res === null) { |
43 | 24 | throw new Error('unpacked msg is not an object'); |
44 | 25 | } |
|
0 commit comments