(str: string)
| 78 | if (cp >= 0 && cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff)) return cp >>> 0; |
| 79 | return REPLACEMENT; |
| 80 | } |
| 81 | |
| 82 | /* ===== UTF-8 ===== */ |
| 83 | |
| 84 | function encodeUtf8(str: string): Uint8Array { |
| 85 | if (typeof TextEncoder !== 'undefined') { |
| 86 | return new TextEncoder().encode(str); |
| 87 | } |
| 88 | // Manual fallback (sufficient for BMP + astral) |
| 89 | const cps = toCodePoints(str); |
| 90 | // worst case 4 bytes/code point |
| 91 | const out: number[] = []; |
| 92 | for (const cp of cps) { |
| 93 | if (cp <= 0x7f) { |
| 94 | out.push(cp); |
| 95 | } else if (cp <= 0x7ff) { |
| 96 | out.push(0b11000000 | (cp >> 6), 0b10000000 | (cp & 0b00111111)); |
| 97 | } else if (cp <= 0xffff) { |
| 98 | out.push(0b11100000 | (cp >> 12), 0b10000000 | ((cp >> 6) & 0b00111111), 0b10000000 | (cp & 0b00111111)); |
| 99 | } else { |
| 100 | out.push( |
| 101 | 0b11110000 | (cp >> 18), |
| 102 | 0b10000000 | ((cp >> 12) & 0b00111111), |
| 103 | 0b10000000 | ((cp >> 6) & 0b00111111), |
| 104 | 0b10000000 | (cp & 0b00111111), |
| 105 | ); |
| 106 | } |
| 107 | } |
| 108 | return Uint8Array.from(out); |
| 109 | } |
| 110 | |
| 111 | function decodeUtf8(bytes: Uint8Array): string { |
| 112 | if (typeof TextDecoder !== 'undefined') { |
| 113 | try { |
| 114 | return new TextDecoder('utf-8', { fatal: false }).decode(bytes); |
| 115 | } catch { |
no test coverage detected