(str: string)
| 187 | * @since 4.0.0 |
| 188 | */ |
| 189 | export const decode = (str: string): Result.Result<Uint8Array, EncodingError> => { |
| 190 | const length = str.length |
| 191 | // Native `fromHex` accepts exactly the inputs the JS decoder does. On V8 it |
| 192 | // costs about 1 µs, while the JS path stays well below that until the output |
| 193 | // outgrows V8's 64-byte on-heap typed arrays. |
| 194 | const NativeUint8Array = Uint8Array as { readonly fromHex?: (string: string) => Uint8Array } |
| 195 | if (length > 128 && typeof NativeUint8Array.fromHex === "function") { |
| 196 | try { |
| 197 | return Result.succeed(NativeUint8Array.fromHex(str)) |
| 198 | } catch { |
| 199 | return decodeFailure(str) |
| 200 | } |
| 201 | } |
| 202 | if (length % 2 !== 0) return decodeFailure(str) |
| 203 | const result = new Uint8Array(length / 2) |
| 204 | // Invalid characters map to 255. |
| 205 | if (length <= 1024) { |
| 206 | for (let i = 0, j = 0; j < length; i++, j += 2) { |
| 207 | const a = hexCode(str.charCodeAt(j)) |
| 208 | const b = hexCode(str.charCodeAt(j + 1)) |
| 209 | if ((a | b) > 15) return decodeFailure(str) |
| 210 | result[i] = (a << 4) | b |
| 211 | } |
| 212 | return Result.succeed(result) |
| 213 | } |
| 214 | // For longer inputs, encoding to UTF-8 once and reading bytes beats |
| 215 | // `charCodeAt` on V8. Non-ASCII characters encode to bytes above 127, which |
| 216 | // also map to 255, and the first one sits at the same index as in `str`. |
| 217 | const bytes = encoder.encode(str) |
| 218 | for (let i = 0, j = 0; j < length; i++, j += 2) { |
| 219 | const a = hexCodes[bytes[j]] |
| 220 | const b = hexCodes[bytes[j + 1]] |
| 221 | if ((a | b) > 15) return decodeFailure(str, bytes.length) |
| 222 | result[i] = (a << 4) | b |
| 223 | } |
| 224 | return Result.succeed(result) |
| 225 | } |
| 226 | |
| 227 | // The odd-length message reports the UTF-8 byte length, so non-ASCII input |
| 228 | // whose UTF-8 encoding has an even length reports "Invalid input" instead. |
no test coverage detected