From b7ccc521e7ee9e7f6e2813ea951ef44f44718c50 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Fri, 9 Oct 2026 16:53:59 -0700 Subject: [PATCH] Start fixing hex string handling, needs direct character code manipulation. --- src/lib/primordials.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/lib/primordials.ts b/src/lib/primordials.ts index 64c1508..ec734c2 100644 --- a/src/lib/primordials.ts +++ b/src/lib/primordials.ts @@ -50,6 +50,7 @@ const TypedArray = Object.getPrototypeOf(Bytes.prototype) const bytesSet = Function.prototype.call.bind(Bytes.prototype.set) const bytesFill = Function.prototype.call.bind(Bytes.prototype.fill) +const charCodeAt = Function.prototype.call.bind(String.prototype.charCodeAt) function get (target: object, key: PropertyKey): (this: unknown) => T { const found = Object.getOwnPropertyDescriptor(target, key) @@ -169,8 +170,7 @@ export function bytesToHex (bytes: Uint8Array): string { } /** - * Decodes hex string to Bytes. Validates input directly instead of using a - * patchable `RegExp.prototype.test()`. + * Decodes hex string to Bytes.. */ function hexToBytes (hex: string): Bytes { const length = hex.length @@ -178,17 +178,17 @@ function hexToBytes (hex: string): Bytes { throw new TypeError(`Invalid hexadecimal length ${length}`) } const bytes = new Bytes(length >> 1) + let d = 0 for (let i = 0, b = 0; i < length; i += 2, b++) { - const hi = hex[i] - const lo = hex[i + 1] - if (NIBBLE[hi] == null) { - throw new TypeError(`Invalid hexadecimal character ${hi}`) - } - if (NIBBLE[lo] == null) { - throw new TypeError(`Invalid hexadecimal character ${lo}`) - } + const hi = charCodeAt(hex, i) + const lo = charCodeAt(hex, i + 1) + d |= hi | lo bytes[b] = (NIBBLE[hi] << 4) | NIBBLE[lo] } + if (d & 0x100) { + fill(bytes, 0) + throw new TypeError('Invalid hexadecimal character') + } return bytes } /** -- 2.52.0