// // HTMLScanner.swift // RSParser // // Created by Brent Simmons on 4/19/26. // // Liberal, byte-oriented HTML scanner with a SAX-style delegate. // // Byte slices throughout. Entity references (named, decimal, hex) are expanded // via `XMLEntities.decode`. Comments, DOCTYPE, and PIs are silently consumed. // // Differs from the XML scanner in ways HTML requires: // - Tag names compared case-insensitively (but emitted as they appear). // - Content of `` / `` ends the block. // - Attributes may have no value (``), single-quoted values, // or unquoted values (``). // - No void-element tracking. Consumers that care (both of ours don't) // apply their own void-element list at the delegate level. // // Not re-entrant. Callbacks happen on the thread that called `parse(_:)`. public final class HTMLScanner { public weak var delegate: HTMLScannerDelegate? public init(delegate: HTMLScannerDelegate) { self.delegate = delegate } public func parse(_ bytes: [UInt8]) { self.input = bytes self.pos = 0 drive() delegate?.htmlScannerDidEnd(self) } // MARK: - Private state private var input: [UInt8] = [] private var pos: Int = 0 } // MARK: - Private private extension HTMLScanner { // Tag names that enter raw-text mode. Their content isn't parsed as markup; // only the matching or ends the block. static let scriptBytes: [UInt8] = Array("script".utf8) static let styleBytes: [UInt8] = Array("style".utf8) func drive() { while pos < input.count { let b = input[pos] if b == .asciiLessThan { scanMarkup() } else { scanCharacters() } } } // MARK: - Markup dispatch /// Handle everything starting with `<`. Consumes silent markup in place, /// emits delegate callbacks for tags and character content. func scanMarkup() { assert(input[pos] == .asciiLessThan) let next = peek(1) if next == .asciiExclamation { if matchPrefix("