UNPKG

1.75 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.compactToU8a = void 0;
4const index_js_1 = require("../bn/index.js");
5const index_js_2 = require("../u8a/index.js");
6const MAX_U8 = index_js_1.BN_TWO.pow(new index_js_1.BN(8 - 2)).isub(index_js_1.BN_ONE);
7const MAX_U16 = index_js_1.BN_TWO.pow(new index_js_1.BN(16 - 2)).isub(index_js_1.BN_ONE);
8const MAX_U32 = index_js_1.BN_TWO.pow(new index_js_1.BN(32 - 2)).isub(index_js_1.BN_ONE);
9const BL_16 = { bitLength: 16 };
10const BL_32 = { bitLength: 32 };
11/**
12 * @name compactToU8a
13 * @description Encodes a number into a compact representation
14 * @example
15 * <BR>
16 *
17 * ```javascript
18 * import { compactToU8a } from '@polkadot/util';
19 *
20 * console.log(compactToU8a(511, 32)); // Uint8Array([0b11111101, 0b00000111])
21 * ```
22 */
23function 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 // adjust to the minimum number of bytes
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 // subtract 4 as minimum (also catered for in decoding)
45 new Uint8Array([((length - 4) << 2) + 0b11]),
46 u8a.subarray(0, length)
47 ]);
48}
49exports.compactToU8a = compactToU8a;