UNPKG

1.19 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { BN } from "../bn/index.js";
4import { u8aToBn, u8aToU8a } from "../u8a/index.js";
5/**
6 * @name compactFromU8a
7 * @description Retrives the offset and encoded length from a compact-prefixed value
8 * @example
9 * <BR>
10 *
11 * ```javascript
12 * import { compactFromU8a } from '@polkadot/util';
13 *
14 * const [offset, length] = compactFromU8a(new Uint8Array([254, 255, 3, 0]));
15 *
16 * console.log('value offset=', offset, 'length=', length); // 4, 0xffff
17 * ```
18 */
19
20export function compactFromU8a(input) {
21 const u8a = u8aToU8a(input);
22 const flag = u8a[0] & 0b11; // The u8a is manually converted here, it is 2x faster that doing an
23 // additional call to u8aToBn
24
25 if (flag === 0b00) {
26 return [1, new BN(u8a[0] >>> 2)];
27 } else if (flag === 0b01) {
28 return [2, new BN(u8a[0] + u8a[1] * 0x100 >>> 2)];
29 } else if (flag === 0b10) {
30 return [4, new BN(u8a[0] + u8a[1] * 0x100 + u8a[2] * 0x10000 + u8a[3] * 0x1000000 >>> 2)];
31 } // add 5 to shifted (4 for base length, 1 for this byte)
32
33
34 const offset = (u8a[0] >>> 2) + 5;
35 return [offset, u8aToBn(u8a.subarray(1, offset))];
36}
\No newline at end of file