| 56 | } |
| 57 | |
| 58 | function isValidUTF8(bytes) { |
| 59 | let i = 0; |
| 60 | while (i < bytes.length) { |
| 61 | const byte = bytes[i]; |
| 62 | |
| 63 | if (byte < 0x80) { |
| 64 | i++; |
| 65 | } else if (byte >> 5 === 0x06) { |
| 66 | if (i + 1 >= bytes.length || bytes[i + 1] >> 6 !== 0x02) return false; |
| 67 | i += 2; |
| 68 | } else if (byte >> 4 === 0x0e) { |
| 69 | if ( |
| 70 | i + 2 >= bytes.length || |
| 71 | bytes[i + 1] >> 6 !== 0x02 || |
| 72 | bytes[i + 2] >> 6 !== 0x02 |
| 73 | ) |
| 74 | return false; |
| 75 | i += 3; |
| 76 | } else if (byte >> 3 === 0x1e) { |
| 77 | if ( |
| 78 | i + 3 >= bytes.length || |
| 79 | bytes[i + 1] >> 6 !== 0x02 || |
| 80 | bytes[i + 2] >> 6 !== 0x02 || |
| 81 | bytes[i + 3] >> 6 !== 0x02 |
| 82 | ) |
| 83 | return false; |
| 84 | i += 4; |
| 85 | } else { |
| 86 | return false; |
| 87 | } |
| 88 | } |
| 89 | return true; |
| 90 | } |
| 91 | |
| 92 | export async function detectEncoding(buffer) { |
| 93 | if (!buffer || buffer.byteLength === 0) { |