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