@polkadot/util
Version:
A collection of useful utilities for @polkadot
45 lines (37 loc) • 1.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.compactFromU8a = compactFromU8a;
var _bn = require("../bn");
var _u8a = require("../u8a");
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
/**
* @name compactFromU8a
* @description Retrives the offset and encoded length from a compact-prefixed value
* @example
* <BR>
*
* ```javascript
* import { compactFromU8a } from '@polkadot/util';
*
* const [offset, length] = compactFromU8a(new Uint8Array([254, 255, 3, 0]));
*
* console.log('value offset=', offset, 'length=', length); // 4, 0xffff
* ```
*/
function compactFromU8a(input) {
const u8a = (0, _u8a.u8aToU8a)(input);
const flag = u8a[0] & 0b11; // The u8a is manually converted here, it is 2x faster that doing an
// additional call to u8aToBn
if (flag === 0b00) {
return [1, new _bn.BN(u8a[0] >>> 2)];
} else if (flag === 0b01) {
return [2, new _bn.BN(u8a[0] + u8a[1] * 0x100 >>> 2)];
} else if (flag === 0b10) {
return [4, new _bn.BN(u8a[0] + u8a[1] * 0x100 + u8a[2] * 0x10000 + u8a[3] * 0x1000000 >>> 2)];
} // add 5 to shifted (4 for base length, 1 for this byte)
const offset = (u8a[0] >>> 2) + 5;
return [offset, (0, _u8a.u8aToBn)(u8a.subarray(1, offset))];
}