diff --git a/src/abstract/utils.ts b/src/abstract/utils.ts index 2682f2f..50ebfda 100644 --- a/src/abstract/utils.ts +++ b/src/abstract/utils.ts @@ -44,7 +44,8 @@ export function hexToNumber(hex: string): bigint { return BigInt(hex === '' ? '0' : `0x${hex}`); } -const enum HexCharCode { +// We use very optimized technique to convert hex string to byte array +const enum HexC { ZERO = 48, // 0 NINE = 57, // 9 A_UP = 65, // A @@ -54,15 +55,10 @@ const enum HexCharCode { } function charCodeToBase16(char: number) { - if (char >= HexCharCode.ZERO && char <= HexCharCode.NINE) { - return char - HexCharCode.ZERO; - } else if (char >= HexCharCode.A_UP && char <= HexCharCode.F_UP) { - return char - (HexCharCode.A_UP - 10); - } else if (char >= HexCharCode.A_LO && char <= HexCharCode.F_LO) { - return char - (HexCharCode.A_LO - 10); - } - - throw new Error('Invalid byte sequence.'); + if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO; + else if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10); + else if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10); + throw new Error('Invalid byte sequence'); } /** @@ -72,8 +68,9 @@ export function hexToBytes(hex: string): Uint8Array { if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); const len = hex.length; if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); - const array = new Uint8Array(len / 2); - for (let i = 0, j = 0, l = array.length; i < l; i++) { + const al = len / 2; + const array = new Uint8Array(al); + for (let i = 0, j = 0; i < al; i++) { const n1 = charCodeToBase16(hex.charCodeAt(j++)); const n2 = charCodeToBase16(hex.charCodeAt(j++)); array[i] = n1 * 16 + n2;