UNPKG

1.46 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { BigInt } from '@polkadot/x-bigint';
4import { objectSpread } from "../object/spread.js";
5import { _0n, _1n } from "./consts.js";
6import { nToBigInt } from "./toBigInt.js";
7const DIV = BigInt(256);
8const NEG_MASK = BigInt(0xff);
9
10function toU8a(value, {
11 isLe,
12 isNegative
13}) {
14 const arr = [];
15
16 if (isNegative) {
17 value = (value + _1n) * -_1n;
18 }
19
20 while (value !== _0n) {
21 const mod = value % DIV;
22 const val = Number(isNegative ? mod ^ NEG_MASK : mod);
23
24 if (isLe) {
25 arr.push(val);
26 } else {
27 arr.unshift(val);
28 }
29
30 value = (value - mod) / DIV;
31 }
32
33 return Uint8Array.from(arr);
34}
35/**
36 * @name nToU8a
37 * @summary Creates a Uint8Array object from a bigint.
38 */
39
40
41export function nToU8a(value, options) {
42 const opts = objectSpread({
43 bitLength: -1,
44 isLe: true,
45 isNegative: false
46 }, options);
47 const valueBi = nToBigInt(value);
48
49 if (valueBi === _0n) {
50 return opts.bitLength === -1 ? new Uint8Array() : new Uint8Array(Math.ceil((opts.bitLength || 0) / 8));
51 }
52
53 const u8a = toU8a(valueBi, opts);
54
55 if (opts.bitLength === -1) {
56 return u8a;
57 }
58
59 const byteLength = Math.ceil((opts.bitLength || 0) / 8);
60 const output = new Uint8Array(byteLength);
61
62 if (opts.isNegative) {
63 output.fill(0xff);
64 }
65
66 output.set(u8a, opts.isLe ? 0 : byteLength - u8a.length);
67 return output;
68}
\No newline at end of file