|
1 | 1 | import { assertUint8 } from '../assert.js' |
2 | | -import { nativeEncoder } from './_utils.js' |
| 2 | +import { nativeDecoder, nativeEncoder } from './_utils.js' |
3 | 3 |
|
4 | | -let hexArray |
| 4 | +let hexArray // array of 256 bytes converted to two-char hex strings |
| 5 | +let hexCodes // hexArray converted to u16 code pairs |
5 | 6 | let dehexArray |
6 | 7 | const _00 = 0x30_30 // '00' string in hex, the only allowed char pair to generate 0 byte |
7 | 8 | const _ff = 0x66_66 // 'ff' string in hex, max allowed char pair (larger than 'FF' string) |
@@ -63,6 +64,24 @@ export function toHex(arr) { |
63 | 64 | if (!hexArray) hexArray = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')) |
64 | 65 | const length = arr.length // this helps Hermes |
65 | 66 |
|
| 67 | + // Only old browsers use this, barebone engines don't have TextDecoder |
| 68 | + // But Hermes can use this when it (hopefully) implements TextDecoder |
| 69 | + if (nativeDecoder) { |
| 70 | + if (!hexCodes) { |
| 71 | + hexCodes = new Uint16Array(256) |
| 72 | + const u8 = new Uint8Array(hexCodes.buffer, hexCodes.byteOffset, hexCodes.byteLength) |
| 73 | + for (let i = 0; i < 256; i++) { |
| 74 | + const pair = hexArray[i] |
| 75 | + u8[2 * i] = pair.charCodeAt(0) |
| 76 | + u8[2 * i + 1] = pair.charCodeAt(1) |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + const pairs = new Uint16Array(length) |
| 81 | + for (let i = 0; i < length; i++) pairs[i] = hexCodes[arr[i]] |
| 82 | + return nativeDecoder.decode(new Uint8Array(pairs.buffer, pairs.byteOffset, pairs.byteLength)) |
| 83 | + } |
| 84 | + |
66 | 85 | if (length > 30_000) { |
67 | 86 | // Limit concatenation to avoid excessive GC |
68 | 87 | // Thresholds checked on Hermes |
|
0 commit comments