1 | ;
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.u8aFixLength = void 0;
|
4 | /**
|
5 | * @name u8aFixLength
|
6 | * @summary Shifts a Uint8Array to a specific bitLength
|
7 | * @description
|
8 | * Returns a uint8Array with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length.
|
9 | * @example
|
10 | * <BR>
|
11 | *
|
12 | * ```javascript
|
13 | * import { u8aFixLength } from '@polkadot/util';
|
14 | *
|
15 | * u8aFixLength('0x12') // => 0x12
|
16 | * u8aFixLength('0x12', 16) // => 0x0012
|
17 | * u8aFixLength('0x1234', 8) // => 0x12
|
18 | * ```
|
19 | */
|
20 | function u8aFixLength(value, bitLength = -1, atStart = false) {
|
21 | const byteLength = Math.ceil(bitLength / 8);
|
22 | if (bitLength === -1 || value.length === byteLength) {
|
23 | return value;
|
24 | }
|
25 | else if (value.length > byteLength) {
|
26 | return value.subarray(0, byteLength);
|
27 | }
|
28 | const result = new Uint8Array(byteLength);
|
29 | result.set(value, atStart ? 0 : (byteLength - value.length));
|
30 | return result;
|
31 | }
|
32 | exports.u8aFixLength = u8aFixLength;
|