UNPKG

@polkadot/util

Version:
44 lines 1.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.u8aToBigInt = void 0; const x_bigint_1 = require("@polkadot/x-bigint"); const consts_js_1 = require("../bi/consts.js"); const U8_MAX = (0, x_bigint_1.BigInt)(256); const U16_MAX = (0, x_bigint_1.BigInt)(256 * 256); /** * @name u8aToBigInt * @summary Creates a BigInt from a Uint8Array object. */ function u8aToBigInt(value, { isLe = true, isNegative = false } = {}) { if (!value || !value.length) { return (0, x_bigint_1.BigInt)(0); } const u8a = isLe ? value : value.reverse(); const dvI = new DataView(u8a.buffer, u8a.byteOffset); const mod = u8a.length % 2; let result = (0, x_bigint_1.BigInt)(0); // This is mostly written for readability (with the single isNegative shortcut), // as opposed to performance, e.g. `u8aToBn` does loop unrolling, etc. if (isNegative) { for (let i = u8a.length - 2; i >= mod; i -= 2) { result = (result * U16_MAX) + (0, x_bigint_1.BigInt)(dvI.getUint16(i, true) ^ 0xffff); } if (mod) { result = (result * U8_MAX) + (0, x_bigint_1.BigInt)(dvI.getUint8(0) ^ 0xff); } } else { for (let i = u8a.length - 2; i >= mod; i -= 2) { result = (result * U16_MAX) + (0, x_bigint_1.BigInt)(dvI.getUint16(i, true)); } if (mod) { result = (result * U8_MAX) + (0, x_bigint_1.BigInt)(dvI.getUint8(0)); } } return isNegative ? ((result * -consts_js_1._1n) - consts_js_1._1n) : result; } exports.u8aToBigInt = u8aToBigInt;