1 | import { hexAddPrefix } from './addPrefix.js';
|
2 | import { hexStripPrefix } from './stripPrefix.js';
|
3 | /**
|
4 | * @name hexFixLength
|
5 | * @summary Shifts a hex string to a specific bitLength
|
6 | * @description
|
7 | * Returns a `0x` prefixed string 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. Input values with less bits are returned as-is by default. When `withPadding` is set, shorter values are padded with `0`.
|
8 | * @example
|
9 | * <BR>
|
10 | *
|
11 | * ```javascript
|
12 | * import { hexFixLength } from '@polkadot/util';
|
13 | *
|
14 | * console.log('fixed', hexFixLength('0x12', 16)); // => 0x12
|
15 | * console.log('fixed', hexFixLength('0x12', 16, true)); // => 0x0012
|
16 | * console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12
|
17 | * ```
|
18 | */
|
19 | export function hexFixLength(value, bitLength = -1, withPadding = false) {
|
20 | const strLength = Math.ceil(bitLength / 4);
|
21 | const hexLength = strLength + 2;
|
22 | return hexAddPrefix((bitLength === -1 || value.length === hexLength || (!withPadding && value.length < hexLength))
|
23 | ? hexStripPrefix(value)
|
24 | : (value.length > hexLength)
|
25 | ? hexStripPrefix(value).slice(-1 * strLength)
|
26 | : `${'0'.repeat(strLength)}${hexStripPrefix(value)}`.slice(-1 * strLength));
|
27 | }
|