Skip to content

Commit feff64e

Browse files
committed
docs: preserve exact 64-bit map keys
1 parent 6d4b666 commit feff64e

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,30 @@ NodeJS `Buffer` is also acceptable because it is a subclass of `Uint8Array`.
160160

161161
`MapKeyConverterType` is defined as `(key: unknown) => string | number`.
162162

163+
When another language encodes a map key as an `int64` or `uint64`, the default decoder reads the key as a JavaScript `number`. Integers outside the safe integer range may lose precision before `mapKeyConverter` runs. To keep those keys exact, enable `useBigInt64` and convert `bigint` keys to decimal strings:
164+
165+
```typescript
166+
import { decode } from "@msgpack/msgpack";
167+
168+
// A one-entry MessagePack map: uint64 key 9007199254740993 -> nil.
169+
const encoded = Uint8Array.of(0x81, 0xcf, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xc0);
170+
const object = decode(encoded, {
171+
useBigInt64: true,
172+
mapKeyConverter(key) {
173+
if (typeof key === "bigint") {
174+
return key.toString();
175+
}
176+
if (typeof key === "string" || typeof key === "number") {
177+
return key;
178+
}
179+
throw new TypeError("Expected a string, number, or bigint map key");
180+
},
181+
});
182+
// { "9007199254740993": null }
183+
```
184+
185+
This option also decodes `int64` and `uint64` values as `bigint`. Decoded maps are plain objects, so numeric and string keys with the same string representation are not distinct.
186+
163187
To skip UTF-8 decoding of strings, `rawStrings` can be set to `true`. In this case, strings are decoded into `Uint8Array`.
164188

165189
You can use `max${Type}Length` to limit the length of each type decoded.

‎test/readme.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,26 @@ import { deepStrictEqual } from "assert";
22
import { encode, decode } from "../src/index.ts";
33

44
describe("README", () => {
5+
context("64-bit integer map keys", () => {
6+
it("retains every digit of a uint64 key beyond Number.MAX_SAFE_INTEGER", () => {
7+
const encoded = Uint8Array.of(0x81, 0xcf, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xc0);
8+
const object = decode(encoded, {
9+
useBigInt64: true,
10+
mapKeyConverter(key) {
11+
if (typeof key === "bigint") {
12+
return key.toString();
13+
}
14+
if (typeof key === "string" || typeof key === "number") {
15+
return key;
16+
}
17+
throw new TypeError("Expected a string, number, or bigint map key");
18+
},
19+
});
20+
const expectedKey = "9007199254740993";
21+
deepStrictEqual(object, { [expectedKey]: null });
22+
});
23+
});
24+
525
context("## Synopsis", () => {
626
it("runs", () => {
727
const object = {

0 commit comments

Comments
 (0)