1 |
|
2 |
|
3 | import { assert } from "../assert.js";
|
4 | import { BN, BN_ONE, BN_TWO, bnToBn, bnToU8a } from "../bn/index.js";
|
5 | import { u8aConcat } from "../u8a/index.js";
|
6 | const MAX_U8 = BN_TWO.pow(new BN(8 - 2)).isub(BN_ONE);
|
7 | const MAX_U16 = BN_TWO.pow(new BN(16 - 2)).isub(BN_ONE);
|
8 | const MAX_U32 = BN_TWO.pow(new BN(32 - 2)).isub(BN_ONE);
|
9 | const BL_16 = {
|
10 | bitLength: 16
|
11 | };
|
12 | const BL_32 = {
|
13 | bitLength: 32
|
14 | };
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | export function compactToU8a(value) {
|
29 | const bn = bnToBn(value);
|
30 |
|
31 | if (bn.lte(MAX_U8)) {
|
32 | return new Uint8Array([bn.toNumber() << 2]);
|
33 | } else if (bn.lte(MAX_U16)) {
|
34 | return bnToU8a(bn.shln(2).iadd(BN_ONE), BL_16);
|
35 | } else if (bn.lte(MAX_U32)) {
|
36 | return bnToU8a(bn.shln(2).iadd(BN_TWO), BL_32);
|
37 | }
|
38 |
|
39 | const u8a = bnToU8a(bn);
|
40 | let length = u8a.length;
|
41 |
|
42 | while (u8a[length - 1] === 0) {
|
43 | length--;
|
44 | }
|
45 |
|
46 | assert(length >= 4, 'Invalid length, previous checks match anything less than 2^30');
|
47 | return u8aConcat(
|
48 | [(length - 4 << 2) + 0b11], u8a.subarray(0, length));
|
49 | } |
\ | No newline at end of file |