forked from tornado-packages/noble-curves
utils: refactor hexToBytes a bit
This commit is contained in:
parent
d0294bb2a6
commit
f58002e6d4
@ -44,21 +44,13 @@ export function hexToNumber(hex: string): bigint {
|
|||||||
return BigInt(hex === '' ? '0' : `0x${hex}`);
|
return BigInt(hex === '' ? '0' : `0x${hex}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// We use very optimized technique to convert hex string to byte array
|
// We use optimized technique to convert hex string to byte array
|
||||||
const enum HexC {
|
const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;
|
||||||
ZERO = 48, // 0
|
function asciiToBase16(char: number): number | undefined {
|
||||||
NINE = 57, // 9
|
if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;
|
||||||
A_UP = 65, // A
|
if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);
|
||||||
F_UP = 70, // F
|
if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);
|
||||||
A_LO = 97, // a
|
return;
|
||||||
F_LO = 102, // f
|
|
||||||
}
|
|
||||||
|
|
||||||
function charCodeToBase16(char: number) {
|
|
||||||
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');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -71,8 +63,13 @@ export function hexToBytes(hex: string): Uint8Array {
|
|||||||
const al = len / 2;
|
const al = len / 2;
|
||||||
const array = new Uint8Array(al);
|
const array = new Uint8Array(al);
|
||||||
for (let i = 0, j = 0; i < al; i++) {
|
for (let i = 0, j = 0; i < al; i++) {
|
||||||
const n1 = charCodeToBase16(hex.charCodeAt(j++));
|
const n1 = asciiToBase16(hex.charCodeAt(j++));
|
||||||
const n2 = charCodeToBase16(hex.charCodeAt(j++));
|
const n2 = asciiToBase16(hex.charCodeAt(j++));
|
||||||
|
if (n1 === undefined || n2 === undefined) {
|
||||||
|
const index = j - 2;
|
||||||
|
const chr = hex[index] + hex[index + 1];
|
||||||
|
throw new Error('hex string expected, got non-hex character "' + chr + '" at index ' + index);
|
||||||
|
}
|
||||||
array[i] = n1 * 16 + n2;
|
array[i] = n1 * 16 + n2;
|
||||||
}
|
}
|
||||||
return array;
|
return array;
|
||||||
|
Loading…
Reference in New Issue
Block a user