MCPcopy Create free account
hub / github.com/Effect-TS/effect / Utf8Input

Class Utf8Input

packages/effect/src/encoding/Xml.ts:2245–2320  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2243// Decodes UTF-8 without streaming state, so that the position of invalid bytes
2244// is known: an incomplete sequence at the end of a chunk is carried over.
2245class Utf8Input implements Machine<Uint8Array, Event> {
2246 private readonly parser: Parser
2247 private carry: Uint8Array | undefined
2248 private started = false
2249
2250 constructor(parser: Parser) {
2251 this.parser = parser
2252 }
2253
2254 get out(): Array<Event> {
2255 return this.parser.out
2256 }
2257 set out(out: Array<Event>) {
2258 this.parser.out = out
2259 }
2260
2261 push(chunk: Uint8Array): void {
2262 if (!this.started && chunk.length > 0) {
2263 const first = this.carry === undefined ? chunk[0] : this.carry[0]
2264 const second = this.carry === undefined ? chunk[1] : chunk[0]
2265 if ((first === 0xFE && second === 0xFF) || (first === 0xFF && second === 0xFE)) {
2266 throw this.parser.error(
2267 "Unsupported",
2268 "UTF-16 is not supported for byte input, decode the bytes to text first",
2269 0
2270 )
2271 }
2272 // Keep a lone BOM prefix pending in the UTF-8 carry below
2273 this.started = second !== undefined || (first !== 0xFE && first !== 0xFF)
2274 }
2275 let start = 0
2276 if (this.carry !== undefined) {
2277 const need = utf8Length(this.carry[0]) - this.carry.length
2278 const head = new Uint8Array(this.carry.length + Math.min(need, chunk.length))
2279 head.set(this.carry)
2280 head.set(chunk.subarray(0, need), this.carry.length)
2281 if (chunk.length < need) {
2282 this.carry = head
2283 return
2284 }
2285 this.carry = undefined
2286 this.decode(head)
2287 start = need
2288 }
2289 const n = chunk.length
2290 let end = n
2291 for (let k = 1; k <= 3 && n - k >= start; k++) {
2292 const b = chunk[n - k]
2293 if ((b & 0xC0) === 0x80) continue
2294 if (b >= 0xC0 && k < utf8Length(b)) end = n - k
2295 break
2296 }
2297 if (end < n) this.carry = chunk.slice(end)
2298 if (end > start) this.decode(start === 0 && end === n ? chunk : chunk.subarray(start, end))
2299 }
2300
2301 end(): void {
2302 // The carried bytes may also be an invalid sequence, such as a single 0xFF

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected