-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathencode.ts
More file actions
84 lines (75 loc) · 2.5 KB
/
encode.ts
File metadata and controls
84 lines (75 loc) · 2.5 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { Encoder } from "./Encoder";
import type { ExtensionCodecType } from "./ExtensionCodec";
import type { ContextOf, SplitUndefined } from "./context";
export type EncodeOptions<ContextType = undefined> = Partial<
Readonly<{
extensionCodec: ExtensionCodecType<ContextType>;
/**
* The maximum depth in nested objects and arrays.
*
* Defaults to 100.
*/
maxDepth: number;
/**
* The initial size of the internal buffer.
*
* Defaults to 2048.
*/
initialBufferSize: number;
/**
* If `true`, the keys of an object is sorted. In other words, the encoded
* binary is canonical and thus comparable to another encoded binary.
*
* Defaults to `false`. If enabled, it spends more time in encoding objects.
*/
sortKeys: boolean;
/**
* If `true`, non-integer numbers are encoded in float32, not in float64 (the default).
*
* Only use it if precisions don't matter.
*
* Defaults to `false`.
*/
forceFloat32: boolean;
/**
* If `true`, an object property with `undefined` value are ignored.
* e.g. `{ foo: undefined }` will be encoded as `{}`, as `JSON.stringify()` does.
*
* Defaults to `false`. If enabled, it spends more time in encoding objects.
*/
ignoreUndefined: boolean;
/**
* If `true`, integer numbers are encoded as floating point numbers,
* with the `forceFloat32` option taken into account.
*
* Defaults to `false`.
*/
forceIntegerToFloat: boolean;
}>
> &
ContextOf<ContextType>;
const getEncoder = (options: any) => new Encoder(
options.extensionCodec,
(options as typeof options & { context: any }).context,
options.maxDepth,
options.initialBufferSize,
options.sortKeys,
options.forceFloat32,
options.ignoreUndefined,
options.forceIntegerToFloat,
);
const defaultEncodeOptions: EncodeOptions = {};
const defaultEncoder = getEncoder(defaultEncodeOptions);
/**
* It encodes `value` in the MessagePack format and
* returns a byte buffer.
*
* The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.
*/
export function encode<ContextType = undefined>(
value: unknown,
options: EncodeOptions<SplitUndefined<ContextType>> = defaultEncodeOptions as any,
): Uint8Array {
const encoder = options === defaultEncodeOptions ? defaultEncoder : getEncoder(options);
return encoder.encode(value);
}