msgpack / msgpack-javascript

@msgpack/msgpack - MessagePack for JavaScript / msgpack.org[JavaScript/TypeScript/ECMA-262]
https://msgpack.org/
ISC License
1.3k stars 162 forks source link

can i override the int64 decoder? #222

Closed CHOYSEN closed 1 year ago

CHOYSEN commented 1 year ago

hi, i used msgpack-lite to operate data, but that library is no longer maintained, so we want to migrate to this library. The int64-buffer and msgpack-lite are maintained by the same author, so we also use the int64-buffer library in the project to create large numbers. We want to process int64-buffer during encoding and decoding, so I wrote the following code:

import * as msgpack from "@msgpack/msgpack";
import * as i from "int64-buffer";

const { Int64BE, Uint64BE } = i.default;

const codec = new msgpack.ExtensionCodec();
codec.register({
  type: 0xcf, // override the default behavior!
  encode: (input) => {
    if (Uint64BE.isUint64BE(input)) {
      return input.toArray();
    } else {
      return null;
    }
  },
  decode: (data) => {
    return new Uint64BE(data);
  },
});

codec.register({
  type: 0xd3, // override the default behavior!
  encode: (input) => {
    if (Int64BE.isInt64BE(input)) {
      return input.toArray();
    } else {
      return null;
    }
  },
  decode: (data) => {
    return new Int64BE(data);
  },
});

const data = { v: new Uint64BE("123456789abcdef0", 16) };

const encodedData = msgpack.encode(data, { extensionCodec: codec });

console.log(
  "encoded:",
  [...encodedData].map((i) => i.toString(16).padStart(2, '0'))
);

const decodedData = msgpack.decode(encodedData, {
  extensionCodec: codec,
});

console.log("decoded:", decodedData);

output:

encoded: [
  '81', 'a1', '76',
  'd7', 'cf', '12',
  '34', '56', '78',
  '9a', 'bc', 'de',
  'f0'
]
decoded: {
  v: ExtData {
    type: -49,
    data: Uint8Array(8) [
       18,  52,  86, 120,
      154, 188, 222, 240
    ]
  }
}

From the result, the default behavior can be overwritten normally when encoding, but not when decoding. Did I miss anything?