1 | import { BigInt } from '@polkadot/x-bigint';
|
2 | import { _0n, _1n } from './consts.js';
|
3 | import { nToBigInt } from './toBigInt.js';
|
4 | const DIV = BigInt(256);
|
5 | const NEG_MASK = BigInt(0xff);
|
6 | function toU8a(value, isLe, isNegative) {
|
7 | const arr = [];
|
8 | const withSigned = isNegative && (value < _0n);
|
9 | if (withSigned) {
|
10 | value = (value + _1n) * -_1n;
|
11 | }
|
12 | while (value !== _0n) {
|
13 | const mod = value % DIV;
|
14 | const val = Number(withSigned
|
15 | ? mod ^ NEG_MASK
|
16 | : mod);
|
17 | if (isLe) {
|
18 | arr.push(val);
|
19 | }
|
20 | else {
|
21 | arr.unshift(val);
|
22 | }
|
23 | value = (value - mod) / DIV;
|
24 | }
|
25 | return Uint8Array.from(arr);
|
26 | }
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | export function nToU8a(value, { bitLength = -1, isLe = true, isNegative = false } = {}) {
|
32 | const valueBi = nToBigInt(value);
|
33 | if (valueBi === _0n) {
|
34 | return bitLength === -1
|
35 | ? new Uint8Array(1)
|
36 | : new Uint8Array(Math.ceil((bitLength || 0) / 8));
|
37 | }
|
38 | const u8a = toU8a(valueBi, isLe, isNegative);
|
39 | if (bitLength === -1) {
|
40 | return u8a;
|
41 | }
|
42 | const byteLength = Math.ceil((bitLength || 0) / 8);
|
43 | const output = new Uint8Array(byteLength);
|
44 | if (isNegative) {
|
45 | output.fill(0xff);
|
46 | }
|
47 | output.set(u8a, isLe ? 0 : byteLength - u8a.length);
|
48 | return output;
|
49 | }
|