This repository has been archived by the owner on Oct 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uint.ts
77 lines (64 loc) · 2.34 KB
/
uint.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
// Code taken as it is from:
// https://raw.githubusercontent.com/ckb-js/lumos/develop/packages/codec/src/number/uint.ts
import { BI, BIish } from "@ckb-lumos/bi";
import { createFixedBytesCodec } from "@ckb-lumos/codec/lib/base";
import { CodecBaseParseError } from "@ckb-lumos/codec/lib/error";
function assertNumberRange(
value: BIish,
min: BIish,
max: BIish,
typeName: string
): void {
value = BI.from(value);
if (value.lt(min) || value.gt(max)) {
throw new CodecBaseParseError(
`Value must be between ${min.toString()} and ${max.toString()}, but got ${value.toString()}`,
typeName
);
}
}
export const createUintBICodec = (byteLength: number, littleEndian = false) => {
const max = BI.from(1)
.shl(byteLength * 8)
.sub(1);
return createFixedBytesCodec<BI, BIish>({
byteLength,
pack(biIsh) {
let endianType: "LE" | "BE" | "" = littleEndian ? "LE" : "BE";
if (byteLength <= 1) {
endianType = "";
}
const typeName = `Uint${byteLength * 8}${endianType}`;
if (typeof biIsh === "number" && !Number.isSafeInteger(biIsh)) {
throw new CodecBaseParseError(
`${biIsh} is not a safe integer`,
typeName
);
}
let num = BI.from(biIsh);
assertNumberRange(num, 0, max, typeName);
const result = new DataView(new ArrayBuffer(byteLength));
for (let i = 0; i < byteLength; i++) {
if (littleEndian) {
result.setUint8(i, num.and(0xff).toNumber());
} else {
result.setUint8(byteLength - i - 1, num.and(0xff).toNumber());
}
num = num.shr(8);
}
return new Uint8Array(result.buffer);
},
unpack: (buf) => {
const view = new DataView(Uint8Array.from(buf).buffer);
let result = BI.from(0);
for (let i = 0; i < byteLength; i++) {
if (littleEndian) {
result = result.or(BI.from(view.getUint8(i)).shl(i * 8));
} else {
result = result.shl(8).or(view.getUint8(i));
}
}
return result;
},
});
};