Adjust isHex length check (#1205)

This commit is contained in:
Jaco
2021-11-19 06:23:01 +02:00
committed by GitHub
parent 3b2ecb87e9
commit 88beb4d81c
3 changed files with 22 additions and 15 deletions
+3 -3
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { REGEX_HEX_NOPREFIX_IGNORE, REGEX_HEX_PREFIXED_IGNORE } from '../is/hex';
import { REGEX_HEX_NOPREFIX, REGEX_HEX_PREFIXED } from '../is/hex';
/**
* @name hexStripPrefix
@@ -20,9 +20,9 @@ import { REGEX_HEX_NOPREFIX_IGNORE, REGEX_HEX_PREFIXED_IGNORE } from '../is/hex'
export function hexStripPrefix (value?: string | null): string {
if (!value || value === '0x') {
return '';
} else if (REGEX_HEX_PREFIXED_IGNORE.test(value)) {
} else if (REGEX_HEX_PREFIXED.test(value)) {
return value.substr(2);
} else if (REGEX_HEX_NOPREFIX_IGNORE.test(value)) {
} else if (REGEX_HEX_NOPREFIX.test(value)) {
return value;
}
+12
View File
@@ -68,4 +68,16 @@ describe('isHex', (): void => {
isHex('0x123', -1, true)
).toEqual(true);
});
it.skip('performance', (): void => {
const test = '0x1234adbcdef5798351773526352876adbcdef2358735adbcdef2623587adbcdef11234adbcdef5798351773526352876adbcdef2358735adbcdef2623587adbcdef11234adbcdef5798351773526352876adbcdef2358735adbcdef2623587adbcdef11234adbcdef5798351773526352876adbcdef2358735adbcdef2623587adbcdef1';
console.time('performance:isHex');
for (let i = 0; i < 512000; i++) {
isHex(test);
}
console.timeEnd('performance:isHex');
});
});
+7 -12
View File
@@ -3,13 +3,9 @@
import type { HexString } from '../types';
export const REGEX_HEX_PREFIXED = /^0x([\da-fA-F]{2})+$/;
export const REGEX_HEX_PREFIXED = /^0x[\da-fA-F]+$/;
export const REGEX_HEX_NOPREFIX = /^([\da-fA-F]{2})+$/;
export const REGEX_HEX_PREFIXED_IGNORE = /^0x[\da-fA-F]+$/;
export const REGEX_HEX_NOPREFIX_IGNORE = /^[\da-fA-F]+$/;
export const REGEX_HEX_NOPREFIX = /^[\da-fA-F]+$/;
/**
* @name isHex
@@ -29,15 +25,14 @@ export const REGEX_HEX_NOPREFIX_IGNORE = /^[\da-fA-F]+$/;
export function isHex (value: unknown, bitLength = -1, ignoreLength = false): value is HexString {
return (
typeof value === 'string' && (
value === '0x' || (
ignoreLength
? REGEX_HEX_PREFIXED_IGNORE.test(value)
: REGEX_HEX_PREFIXED.test(value)
)
value === '0x' ||
REGEX_HEX_PREFIXED.test(value)
)
)
? bitLength === -1
? true
? ignoreLength
? true
: (value.length % 2 === 0)
: (value.length === (2 + Math.ceil(bitLength / 4)))
: false;
}