forked from tornado-packages/noble-curves
abstract/utils: reformat hexToBytes.
This commit is contained in:
parent
1d83bab27d
commit
c935b398fe
@ -44,7 +44,8 @@ export function hexToNumber(hex: string): bigint {
|
|||||||
return BigInt(hex === '' ? '0' : `0x${hex}`);
|
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
|
ZERO = 48, // 0
|
||||||
NINE = 57, // 9
|
NINE = 57, // 9
|
||||||
A_UP = 65, // A
|
A_UP = 65, // A
|
||||||
@ -54,15 +55,10 @@ const enum HexCharCode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function charCodeToBase16(char: number) {
|
function charCodeToBase16(char: number) {
|
||||||
if (char >= HexCharCode.ZERO && char <= HexCharCode.NINE) {
|
if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;
|
||||||
return char - HexCharCode.ZERO;
|
else if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);
|
||||||
} else if (char >= HexCharCode.A_UP && char <= HexCharCode.F_UP) {
|
else if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);
|
||||||
return char - (HexCharCode.A_UP - 10);
|
throw new Error('Invalid byte sequence');
|
||||||
} else if (char >= HexCharCode.A_LO && char <= HexCharCode.F_LO) {
|
|
||||||
return char - (HexCharCode.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);
|
if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
|
||||||
const len = hex.length;
|
const len = hex.length;
|
||||||
if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);
|
if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);
|
||||||
const array = new Uint8Array(len / 2);
|
const al = len / 2;
|
||||||
for (let i = 0, j = 0, l = array.length; i < l; i++) {
|
const array = new Uint8Array(al);
|
||||||
|
for (let i = 0, j = 0; i < al; i++) {
|
||||||
const n1 = charCodeToBase16(hex.charCodeAt(j++));
|
const n1 = charCodeToBase16(hex.charCodeAt(j++));
|
||||||
const n2 = charCodeToBase16(hex.charCodeAt(j++));
|
const n2 = charCodeToBase16(hex.charCodeAt(j++));
|
||||||
array[i] = n1 * 16 + n2;
|
array[i] = n1 * 16 + n2;
|
||||||
|
Loading…
Reference in New Issue
Block a user