diff --git a/Modules/RSParser/Sources/Swift/XML/XMLEntities.swift b/Modules/RSParser/Sources/Swift/XML/XMLEntities.swift new file mode 100644 index 000000000..18c9e1868 --- /dev/null +++ b/Modules/RSParser/Sources/Swift/XML/XMLEntities.swift @@ -0,0 +1,392 @@ +// +// XMLEntities.swift +// RSParser +// +// Created by Brent Simmons on 4/18/26. +// + +import Foundation + +// Entity decoding for the XML SAX parser. +// +// "Predefined XML entities" = the five entities XML 1.0 requires every parser +// to recognize without a DTD: & < > " '. +// +// Two modes: +// +// - `.normal`: used in regular character content and attribute values. Expands +// the predefined XML entities, numeric entities (&#NNN; and &#xHH;), and all +// HTML named entities. +// +// - `.preservePredefinedXML`: used inside CDATA sections. Leaves the predefined +// XML entities literal (so `&` stays `&`) but expands numeric entities +// and all HTML named entities. This matches how real feeds use CDATA to wrap +// HTML content. +// +// Unknown or malformed entities pass through literally (liberal mode). + +enum XMLEntities { + + /// Result of trying to decode an entity. + struct DecodedEntity { + /// UTF-8 bytes to emit in place of the entity reference. + let bytes: [UInt8] + /// Index in the input just past the closing `;`, or just past whatever + /// bytes were consumed (e.g. malformed entity — just the `&` itself). + let nextIndex: Int + } + + enum Mode { + /// Expand predefined XML entities as well as HTML named and numeric entities. + case normal + /// Leave predefined XML entities literal but still expand HTML named and numeric entities. + case preservePredefinedXML + } + + /// Attempt to decode an entity starting at the `&` in `bytes[at]`. + /// `mode` controls whether the predefined XML entities are expanded. + /// + /// If a valid entity is recognized, returns the decoded UTF-8 bytes and + /// the next-index. If not, returns a DecodedEntity with a single `&` byte and + /// the next-index advanced past the `&`, so the caller can append it + /// literally (liberal mode). + static func decode(bytes: [UInt8], at: Int, mode: Mode) -> DecodedEntity { + assert(bytes[at] == .asciiAmpersand) + let searchEnd = Swift.min(bytes.count, at + 1 + maxEntityLength) + var semicolonIndex: Int? + var i = at + 1 + while i < searchEnd { + let b = bytes[i] + if b == .asciiSemicolon { + semicolonIndex = i + break + } + // Whitespace or another `&` means we've left the entity. + if b.isASCIIWhitespace || b == .asciiAmpersand || b == .asciiLessThan { + break + } + i += 1 + } + + guard let semicolonIndex else { + return literalAmpersand(at: at) + } + + let nameStart = at + 1 + let nameEndExclusive = semicolonIndex + // Empty name: the input is literally "&;" — not an entity. + if nameStart == nameEndExclusive { + return literalAmpersand(at: at) + } + + // Numeric entity? + if bytes[nameStart] == .asciiHash { + if let result = decodeNumeric(bytes: bytes, start: nameStart + 1, end: nameEndExclusive) { + return DecodedEntity(bytes: result, nextIndex: semicolonIndex + 1) + } + return literalAmpersand(at: at) + } + + // Named entity. + let name = bytes[nameStart.. DecodedEntity { + DecodedEntity(bytes: ampersandBytes, nextIndex: at + 1) + } + + /// Decode `&#NNN;` or `&#xHH;`. `start` is just past the `#`, `end` is exclusive. + static func decodeNumeric(bytes: [UInt8], start: Int, end: Int) -> [UInt8]? { + guard start < end else { + return nil + } + + var codepoint: UInt32 = 0 + let firstByte = bytes[start] + let isHex = (firstByte == .asciiLowerX) || (firstByte == .asciiUpperX) + if isHex { + // Hex. Accept `x` or `X`. + // If the input is just `&#x;` with no digits, the loop exits without + // incrementing `codepoint` and the `codepoint == 0` check below rejects it. + var i = start + 1 + while i < end { + guard let v = bytes[i].asciiHexValue else { + return nil + } + codepoint = codepoint &* 16 &+ v + if codepoint > 0x10FFFF { + return nil + } + i += 1 + } + } else { + // Decimal. + var i = start + while i < end { + let b = bytes[i] + guard b.isASCIIDigit else { + return nil + } + codepoint = codepoint &* 10 &+ UInt32(b - .ascii0) + if codepoint > 0x10FFFF { + return nil + } + i += 1 + } + } + + // Remap Windows-1252 extension codepoints. WebKit's HTMLEntityParser does this + // because historical HTML authors used `€` etc. expecting Windows-1252 + // characters. Applied in HTML parsing; XML parsing in practice needs this too + // for the same authors. + // + // Example: `€` → U+0080 (a C1 control character — unprintable) in strict + // Unicode, but in Windows-1252 byte 0x80 is €. Authors typed `€` + // intending €, so we remap to U+20AC. Same story for `…` → U+2026 (…), + // `’` → U+2019 (’), etc. + // + // The mask `~0x1F` checks "upper bits are 0b100" — i.e. codepoint is in + // [0x80, 0x9F], the Windows-1252 extension range. + if (codepoint & ~0x1F) == 0x80 { + codepoint = windowsLatin1Extension[Int(codepoint - 0x80)] + } + + // Post-remap, `codepoint` can't exceed 0x10FFFF — the Windows-1252 table + // only contains values ≤ 0x20AC, and the pre-remap upper bound was already + // enforced inside the digit loops. + if codepoint == 0 { + return nil + } + // Surrogates are not valid code points. + if codepoint >= 0xD800 && codepoint <= 0xDFFF { + return nil + } + + return utf8Bytes(forCodepoint: codepoint) + } + + /// Encode a Unicode scalar as UTF-8 bytes. + static func utf8Bytes(forCodepoint codepoint: UInt32) -> [UInt8] { + // 1-byte: ASCII (U+0000–U+007F). + if codepoint < 0x80 { + return [UInt8(codepoint)] + } + // 2-byte: U+0080–U+07FF (Latin-1 Supplement through most Arabic). + if codepoint < 0x800 { + return [ + UInt8(0xC0 | (codepoint >> 6)), + UInt8(0x80 | (codepoint & 0x3F)) + ] + } + // 3-byte: U+0800–U+FFFF (most of the BMP — CJK, symbols, punctuation). + if codepoint < 0x10000 { + return [ + UInt8(0xE0 | (codepoint >> 12)), + UInt8(0x80 | ((codepoint >> 6) & 0x3F)), + UInt8(0x80 | (codepoint & 0x3F)) + ] + } + // 4-byte: U+10000–U+10FFFF (emoji, rare scripts, supplementary planes). + return [ + UInt8(0xF0 | (codepoint >> 18)), + UInt8(0x80 | ((codepoint >> 12) & 0x3F)), + UInt8(0x80 | ((codepoint >> 6) & 0x3F)), + UInt8(0x80 | (codepoint & 0x3F)) + ] + } + + static func xmlPredefinedEntity(name: ArraySlice) -> [UInt8]? { + if name.equals("amp") { + return ampersandBytes + } + if name.equals("lt") { + return lessThanBytes + } + if name.equals("gt") { + return greaterThanBytes + } + if name.equals("quot") { + return doubleQuoteBytes + } + if name.equals("apos") { + return singleQuoteBytes + } + return nil + } + + static func asciiString(from slice: ArraySlice) -> String { + // Entity names are short (≤ ~15 bytes in practice), so the String usually + // fits in Swift's inline small-string representation and doesn't hit the heap. + String(decoding: slice, as: UTF8.self) + } + + // HTML named entities commonly seen in RSS and Atom feeds. + // Matches the table in NSString+RSParser.m so behavior is identical to the old path. + // Values are pre-encoded to UTF-8 bytes at init so lookup doesn't build a fresh + // [UInt8] from a String per hit. + static let htmlNamedEntities: [String: [UInt8]] = htmlNamedEntityStrings + .mapValues { Array($0.utf8) } + + static let htmlNamedEntityStrings: [String: String] = [ + "AElig": "Æ", + "Aacute": "Á", + "Acirc": "Â", + "Agrave": "À", + "Aring": "Å", + "Atilde": "Ã", + "Auml": "Ä", + "Ccedil": "Ç", + "Dstrok": "Ð", + "ETH": "Ð", + "Eacute": "É", + "Ecirc": "Ê", + "Egrave": "È", + "Euml": "Ë", + "Iacute": "Í", + "Icirc": "Î", + "Igrave": "Ì", + "Iuml": "Ï", + "Ntilde": "Ñ", + "Oacute": "Ó", + "Ocirc": "Ô", + "Ograve": "Ò", + "Oslash": "Ø", + "Otilde": "Õ", + "Ouml": "Ö", + "Pi": "Π", + "THORN": "Þ", + "Uacute": "Ú", + "Ucirc": "Û", + "Ugrave": "Ù", + "Uuml": "Ü", + "Yacute": "Y", + "aacute": "á", + "acirc": "â", + "acute": "´", + "aelig": "æ", + "agrave": "à", + "aring": "å", + "atilde": "ã", + "auml": "ä", + "brkbar": "¦", + "brvbar": "¦", + "ccedil": "ç", + "cedil": "¸", + "cent": "¢", + "copy": "©", + "CounterClockwiseContourIntegral": "∳", + "curren": "¤", + "deg": "°", + "die": "¨", + "divide": "÷", + "eacute": "é", + "ecirc": "ê", + "egrave": "è", + "eth": "ð", + "euml": "ë", + "euro": "€", + "frac12": "½", + "frac14": "¼", + "frac34": "¾", + "hearts": "♥", + "hellip": "…", + "iacute": "í", + "icirc": "î", + "iexcl": "¡", + "igrave": "ì", + "iquest": "¿", + "iuml": "ï", + "laquo": "«", + "ldquo": "“", + "lsquo": "‘", + "macr": "¯", + "mdash": "—", + "micro": "µ", + "middot": "·", + "ndash": "–", + "not": "¬", + "ntilde": "ñ", + "oacute": "ó", + "ocirc": "ô", + "ograve": "ò", + "ordf": "ª", + "ordm": "º", + "oslash": "ø", + "otilde": "õ", + "ouml": "ö", + "para": "¶", + "pi": "π", + "plusmn": "±", + "pound": "£", + "raquo": "»", + "rdquo": "”", + "reg": "®", + "rsquo": "’", + "sect": "§", + "smallcircle": "◦", + "shy": "\u{00AD}", // U+00AD SOFT HYPHEN — invisible, so keep escaped + "sup1": "¹", + "sup2": "²", + "sup3": "³", + "szlig": "ß", + "thorn": "þ", + "times": "×", + "trade": "™", + "uacute": "ú", + "ucirc": "û", + "ugrave": "ù", + "uml": "¨", + "uuml": "ü", + "yacute": "y", + "yen": "¥", + "yuml": "ÿ", + "infin": "∞", + "nbsp": "\u{00A0}" // U+00A0 NO-BREAK SPACE — looks like plain space, so keep escaped + ] +} diff --git a/Modules/RSParser/Tests/RSParserTests/EntityDecodingBenchmark.swift b/Modules/RSParser/Tests/RSParserTests/EntityDecodingBenchmark.swift new file mode 100644 index 000000000..95d7d252e --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/EntityDecodingBenchmark.swift @@ -0,0 +1,104 @@ +// +// EntityDecodingBenchmark.swift +// RSParserTests +// +// Created by Brent Simmons on 4/19/26. +// + +import XCTest +@testable import RSParser +import RSParserObjC + +// One-shot comparison benchmark: old ObjC `rsparser_stringByDecodingHTMLEntities` +// vs a Swift wrapper around `XMLEntities.decode`. Prints absolute times and the +// speedup ratio. Not meant to be run as part of every test suite. + +final class EntityDecodingBenchmark: XCTestCase { + + /// A realistic mix: plain text, predefined XML entities, named HTML entities, + /// numeric decimal, numeric hex, a worst-case ampersand-heavy input, and an + /// entity-free input (exercises the no-op path). + private let inputs: [String] = [ + "Tom & Jerry — “Episode 5” (™ 2025)", + "Café, résumé, naïve. © 2025 – all rights reserved.", + "No entities here, just plain text content that's a typical paragraph from a feed article — should exercise the no-work path efficiently.", + "“Hello, "world" & everything else” — said the fox.", + String(repeating: "&", count: 200), + "

Mixed markup & entities: <script> 😀 ❤ — works?

", + "&invalidEntity; & � &xyz &; & &;" + ] + + private let iterations = 5_000 + + func testCompareImplementations() { + // Warm up: run both implementations a few times so the first iteration doesn't + // pay for cold caches / lazy dict init (the ObjC path builds its entity dict + // on first call via dispatch_once). + for _ in 0..<100 { + for s in inputs { + _ = (s as NSString).rsparser_stringByDecodingHTMLEntities() + _ = Self.swiftDecode(s) + } + } + + // Correctness sanity — outputs should be identical for our inputs. + for s in inputs { + let objc = (s as NSString).rsparser_stringByDecodingHTMLEntities() + let swift = Self.swiftDecode(s) + XCTAssertEqual(objc, swift, "divergence for input \(s.debugDescription)") + } + + let objcTime = time(label: "ObjC ") { + for _ in 0.. Void) -> Double { + let start = DispatchTime.now() + block() + let end = DispatchTime.now() + let ms = Double(end.uptimeNanoseconds - start.uptimeNanoseconds) / 1_000_000 + let perCall = (ms * 1000) / Double(iterations * inputs.count) + print(String(format: "%@: %7.2f ms total, %5.2f µs/call", label, ms, perCall)) + return ms + } + + /// Swift equivalent of `rsparser_stringByDecodingHTMLEntities`: + /// scan a string, expanding every `&…;` entity via `XMLEntities.decode`. + private static func swiftDecode(_ s: String) -> String { + let bytes = Array(s.utf8) + var out: [UInt8] = [] + out.reserveCapacity(bytes.count) + var i = 0 + while i < bytes.count { + let b = bytes[i] + if b == .asciiAmpersand { + let d = XMLEntities.decode(bytes: bytes, at: i, mode: .normal) + out.append(contentsOf: d.bytes) + i = d.nextIndex + } else { + out.append(b) + i += 1 + } + } + return String(decoding: out, as: UTF8.self) + } +} diff --git a/Modules/RSParser/Tests/RSParserTests/XMLEntitiesTests.swift b/Modules/RSParser/Tests/RSParserTests/XMLEntitiesTests.swift new file mode 100644 index 000000000..cf7e4d1d9 --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/XMLEntitiesTests.swift @@ -0,0 +1,292 @@ +// +// XMLEntitiesTests.swift +// RSParserTests +// +// Created by Brent Simmons on 4/19/26. +// + +import Foundation +import Testing +@testable import RSParser + +// Unit tests for XMLEntities.decode. The scanner also exercises this code end-to-end +// via feed parsing, but these tests pin down the contract at the single-entity level. + +@Suite struct XMLEntitiesTests { + + // MARK: - Helpers + + /// Decode a single entity at the start of `input` and return the decoded UTF-8 as a String. + private func decodeOne(_ input: String, mode: XMLEntities.Mode = .normal) -> (text: String, nextIndex: Int) { + let bytes = Array(input.utf8) + let result = XMLEntities.decode(bytes: bytes, at: 0, mode: mode) + return (String(decoding: result.bytes, as: UTF8.self), result.nextIndex) + } + + // MARK: - Predefined XML entities + + @Test("The five predefined XML entities expand in .normal mode", + arguments: [ + ("&", "&"), + ("<", "<"), + (">", ">"), + (""", "\""), + ("'", "'") + ]) + func predefinedEntitiesNormalMode(_ input: String, _ expected: String) { + let (text, nextIndex) = decodeOne(input) + #expect(text == expected) + #expect(nextIndex == input.utf8.count) + } + + @Test("The five predefined XML entities stay literal in .preservePredefinedXML mode", + arguments: ["&", "<", ">", """, "'"]) + func predefinedEntitiesPreserveMode(_ input: String) { + let (text, nextIndex) = decodeOne(input, mode: .preservePredefinedXML) + // Returns a bare `&` and advances only past the `&` so the caller can re-emit the literal. + #expect(text == "&") + #expect(nextIndex == 1) + } + + // MARK: - Numeric entities — decimal + + @Test("Decimal numeric entities decode", + arguments: [ + ("A", "A"), + ("™", "\u{2122}"), // ™ + ("“", "\u{201C}"), // “ + ("☃", "\u{2603}") // ☃ + ]) + func decimalNumericEntities(_ input: String, _ expected: String) { + let (text, nextIndex) = decodeOne(input) + #expect(text == expected) + #expect(nextIndex == input.utf8.count) + } + + @Test func decimalZeroIsRejected() { + let (text, nextIndex) = decodeOne("�") + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test func decimalWithNonDigitIsRejected() { + let (text, nextIndex) = decodeOne(" a;") + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test func decimalEmptyIsRejected() { + let (text, nextIndex) = decodeOne("&#;") + #expect(text == "&") + #expect(nextIndex == 1) + } + + // MARK: - Numeric entities — hex + + @Test("Hex numeric entities decode", + arguments: [ + ("A", "A"), + ("A", "A"), // uppercase X accepted + ("—", "\u{2014}"), // — + ("­", "\u{00AD}"), // soft hyphen + ("😀", "\u{1F600}") // 😀 (4-byte UTF-8) + ]) + func hexNumericEntities(_ input: String, _ expected: String) { + let (text, nextIndex) = decodeOne(input) + #expect(text == expected) + #expect(nextIndex == input.utf8.count) + } + + @Test func hexZeroIsRejected() { + let (text, nextIndex) = decodeOne("�") + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test func hexEmptyIsRejected() { + let (text, nextIndex) = decodeOne("&#x;") + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test func hexWithNonHexIsRejected() { + let (text, nextIndex) = decodeOne("&#xZZ;") + #expect(text == "&") + #expect(nextIndex == 1) + } + + // MARK: - Surrogate and out-of-range codepoints + + @Test("Surrogate codepoints are rejected", + arguments: ["�", "�", "�", "�"]) // 0xD800 decimal + func surrogatesRejected(_ input: String) { + let (text, nextIndex) = decodeOne(input) + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test func outOfRangeCodepointRejected() { + // 0x110000 — one past the maximum Unicode codepoint. + let (text, nextIndex) = decodeOne("�") + #expect(text == "&") + #expect(nextIndex == 1) + } + + // MARK: - Windows-1252 remap + + @Test("Codepoints in [0x80, 0x9F] are remapped via Windows-1252 extension", + arguments: [ + ("€", "\u{20AC}"), // € + ("…", "\u{2026}"), // … + ("‘", "\u{2018}"), // ‘ + ("’", "\u{2019}"), // ’ + ("“", "\u{201C}"), // “ + ("”", "\u{201D}"), // ” + ("–", "\u{2013}"), // – + ("—", "\u{2014}"), // — + ("™", "\u{2122}") // ™ + ]) + func windows1252Remap(_ input: String, _ expected: String) { + let (text, _) = decodeOne(input) + #expect(text == expected) + } + + @Test("Codepoint 0x7F and 0xA0 are NOT remapped (boundary check)") + func windows1252BoundariesNotRemapped() { + // 0x7F DEL — below the remap range. + var (text, _) = decodeOne("") + #expect(text == "\u{007F}") + // 0xA0 NBSP — above the remap range. + (text, _) = decodeOne(" ") + #expect(text == "\u{00A0}") + } + + // MARK: - HTML named entities + + @Test("Common HTML named entities expand", + arguments: [ + ("©", "©"), + ("—", "—"), + ("–", "–"), + ("“", "“"), + ("”", "”"), + ("…", "…"), + ("™", "™"), + ("é", "é"), + (" ", "\u{00A0}"), + ("­", "\u{00AD}") + ]) + func htmlNamedEntities(_ input: String, _ expected: String) { + let (text, nextIndex) = decodeOne(input) + #expect(text == expected) + #expect(nextIndex == input.utf8.count) + } + + @Test func longestHTMLNamedEntity() { + // CounterClockwiseContourIntegral is our longest entry — confirms we + // don't accidentally trip `maxEntityLength` on it. + let (text, _) = decodeOne("∳") + #expect(text == "∳") + } + + @Test("HTML named entities are case-sensitive") + func htmlNamedEntityCaseSensitive() { + // `copy` exists; `COPY` doesn't. (Some uppercase variants like `AElig` do exist.) + let (text, nextIndex) = decodeOne("©") + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test("Uppercase HTML entities expand (case-sensitive, distinct entry)") + func htmlNamedEntityUppercase() { + // AElig is present in the table with its own mapping. + let (text, _) = decodeOne("Æ") + #expect(text == "Æ") + } + + @Test func unknownHTMLNamedEntityIsRejected() { + let (text, nextIndex) = decodeOne("¬ARealEntity;") + #expect(text == "&") + #expect(nextIndex == 1) + } + + // MARK: - Malformed inputs + + @Test func noSemicolonReturnsLiteral() { + let (text, nextIndex) = decodeOne("&") + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test func emptyEntityReturnsLiteral() { + // `&;` — no name at all. + let (text, nextIndex) = decodeOne("&;") + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test("Whitespace terminates the scan before `;`", + arguments: ["& ", "&\t", "&\n"]) + func whitespaceTerminatesScan(_ input: String) { + let (text, nextIndex) = decodeOne(input) + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test func nestedAmpersandTerminatesScan() { + // `&<` — the inner `&` ends the scan for the outer entity. + let (text, nextIndex) = decodeOne("&<") + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test func lessThanTerminatesScan() { + // `&<` — scanner stops because `<` is illegal inside an entity name. + let (text, nextIndex) = decodeOne("&<") + #expect(text == "&") + #expect(nextIndex == 1) + } + + @Test func tooLongEntityIsRejected() { + // More than maxEntityLength bytes before the `;` — refuses to scan further. + let longName = String(repeating: "x", count: 100) + let input = "&\(longName);" + let (text, nextIndex) = decodeOne(input) + #expect(text == "&") + #expect(nextIndex == 1) + } + + // MARK: - `at` parameter honored + + @Test func decodesAtNonZeroIndex() { + // Entity in the middle of a byte buffer. + let bytes = Array("Hello & world".utf8) + let ampIndex = 6 // position of `&` + let result = XMLEntities.decode(bytes: bytes, at: ampIndex, mode: .normal) + #expect(String(decoding: result.bytes, as: UTF8.self) == "&") + #expect(result.nextIndex == ampIndex + 5) // past `&` + } + + // MARK: - Modes don't affect numeric or HTML named entities + + @Test func preserveModeStillExpandsNumericEntities() { + let (text, _) = decodeOne("A", mode: .preservePredefinedXML) + #expect(text == "A") + } + + @Test func preserveModeStillExpandsHTMLNamedEntities() { + let (text, _) = decodeOne("©", mode: .preservePredefinedXML) + #expect(text == "©") + } + + // MARK: - Windows-1252 extension table exposure + + @Test func windowsLatin1ExtensionTableSize() { + #expect(XMLEntities.windowsLatin1Extension.count == 32) + } + + @Test func windowsLatin1ExtensionKnownEntries() { + #expect(XMLEntities.windowsLatin1Extension[0] == 0x20AC) // € + #expect(XMLEntities.windowsLatin1Extension[0x99 - 0x80] == 0x2122) // ™ + } +}