/
varint.ts
95 lines (88 loc) · 2.65 KB
/
varint.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
/**
* Functions for encoding typed integers in array buffers.
*
* @module
*/
import { instantiate } from "../_wasm_varint/lib/deno_std_wasm_varint.generated.mjs";
const U32MAX = 4_294_967_295;
const U64MAX = 18_446_744_073_709_551_615n;
/**
* Encodes the given `number` into `Uint8Array` with LEB128. The number needs to be in the range of `0` and `0xffffffff`.
* ```ts
* import { encodeU32 } from "./varint.ts";
*
* const encodedValue = encodeU32(42);
* // Do something with the encoded value
* ```
*/
export function encodeU32(val: number): Uint8Array {
if (!Number.isInteger(val)) throw new TypeError("Floats are not supported");
if (val < 0) throw new RangeError("Signed integers are not supported");
if (val > U32MAX) {
throw new RangeError(
`The given number exceeds the limit of unsigned integer: ${val}`,
);
}
const wasm = instantiate();
return wasm.encode_u32(val);
}
/**
* Encodes the given `BigInt` into `Uint8Array` with LEB128. The number needs to be in the range of `0` and `0xffffffffffffffff`.
* ```ts
* import { encodeU64 } from "./varint.ts";
*
* const encodedValue = encodeU64(42n);
* // Do something with the encoded value
* ```
*/
export function encodeU64(val: bigint): Uint8Array {
if (val < 0) throw new RangeError("Signed integers are not supported");
if (val > U64MAX) {
throw new RangeError(
`The given number exceeds the limit of unsigned long integer: ${val}`,
);
}
const wasm = instantiate();
return wasm.encode_u64(val);
}
/**
* Decodes the given `Uint8Array` into a `number` with LEB128.
* ```ts
* import { decodeU32 } from "./varint.ts";
* const bytes = Uint8Array.from([221, 199, 1]);
* const decodedValue = decodeU32(bytes);
*
* // Do something with the decoded value
* console.log(decodedValue === 25565);
* ```
*/
export function decodeU32(val: Uint8Array): number {
if (val.length > 5) throw RangeError("Too many bytes");
const wasm = instantiate();
try {
return wasm.decode_u32(val);
} catch {
throw new RangeError(`Bad varint: ${val}`);
}
}
/**
* Decodes the given `Uint8Array` into a `BigInt` with LEB128.
* ```ts
* import { decodeU64 } from "./varint.ts";
* const bytes = Uint8Array.from([221, 199, 1]);
* const decodedValue = decodeU64(bytes);
*
* // Do something with the decoded value
* console.log(decodedValue === 25565n);
* ```
*/
export function decodeU64(val: Uint8Array): BigInt {
if (val.length > 10) throw RangeError("Too many bytes");
const wasm = instantiate();
try {
return wasm.decode_u64(val);
} catch {
throw new RangeError(`Bad varint: ${val}`);
}
}