| 2216 | |
| 2217 | // Returns the length of the valid UTF-8 prefix of `bytes` |
| 2218 | const validUtf8 = (bytes: Uint8Array): number => { |
| 2219 | let i = 0 |
| 2220 | while (i < bytes.length) { |
| 2221 | const lead = bytes[i] |
| 2222 | if (lead < 0x80) { |
| 2223 | i++ |
| 2224 | continue |
| 2225 | } |
| 2226 | const length = lead >= 0xC2 && lead <= 0xF4 ? utf8Length(lead) : 0 |
| 2227 | if (length === 0 || i + length > bytes.length) return i |
| 2228 | let code = lead & (0xFF >> (length + 1)) |
| 2229 | for (let k = 1; k < length; k++) { |
| 2230 | const c = bytes[i + k] |
| 2231 | if ((c & 0xC0) !== 0x80) return i |
| 2232 | code = (code << 6) | (c & 0x3F) |
| 2233 | } |
| 2234 | const min = length === 2 ? 0x80 : length === 3 ? 0x800 : 0x10000 |
| 2235 | if (code < min || code > 0x10FFFF || (code >= 0xD800 && code <= 0xDFFF)) return i |
| 2236 | i += length |
| 2237 | } |
| 2238 | return i |
| 2239 | } |
| 2240 | |
| 2241 | const utf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }) |
| 2242 | |