-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathdecode.ts
80 lines (74 loc) · 2.3 KB
/
decode.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { Decoder } from "./Decoder";
import type { ExtensionCodecType } from "./ExtensionCodec";
import type { ContextOf, SplitUndefined } from "./context";
export type DecodeOptions<ContextType = undefined> = Readonly<
Partial<{
extensionCodec: ExtensionCodecType<ContextType>;
/**
* Maximum string length.
*
* Defaults to 4_294_967_295 (UINT32_MAX).
*/
maxStrLength: number;
/**
* Maximum binary length.
*
* Defaults to 4_294_967_295 (UINT32_MAX).
*/
maxBinLength: number;
/**
* Maximum array length.
*
* Defaults to 4_294_967_295 (UINT32_MAX).
*/
maxArrayLength: number;
/**
* Maximum map length.
*
* Defaults to 4_294_967_295 (UINT32_MAX).
*/
maxMapLength: number;
/**
* Maximum extension length.
*
* Defaults to 4_294_967_295 (UINT32_MAX).
*/
maxExtLength: number;
}>
> &
ContextOf<ContextType>;
const getDecoder = (options: any) => new Decoder(
options.extensionCodec,
(options as typeof options & { context: any }).context,
options.maxStrLength,
options.maxBinLength,
options.maxArrayLength,
options.maxMapLength,
options.maxExtLength,
);
export const defaultDecodeOptions: DecodeOptions = {};
const defaultDecoder = getDecoder(defaultDecodeOptions);
/**
* It decodes a single MessagePack object in a buffer.
*
* This is a synchronous decoding function.
* See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.
*/
export function decode<ContextType = undefined>(
buffer: ArrayLike<number> | BufferSource,
options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,
): unknown {
const decoder = options === defaultDecodeOptions ? defaultDecoder : getDecoder(options);
return decoder.decode(buffer);
}
/**
* It decodes multiple MessagePack objects in a buffer.
* This is corresponding to {@link decodeMultiStream()}.
*/
export function decodeMulti<ContextType = undefined>(
buffer: ArrayLike<number> | BufferSource,
options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,
): Generator<unknown, void, unknown> {
const decoder = options === defaultDecodeOptions ? defaultDecoder : getDecoder(options);
return decoder.decodeMulti(buffer);
}