From 6c153739600dacdbceabf06619555bc299dab311 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 21 Apr 2026 20:23:54 -0700 Subject: [PATCH] Move sanitizedTitle from an Article extension to ArticleStringFormatter, where it belongs. Make it faster. Add tests. --- .../Articles/Sources/Articles/Article.swift | 43 ------ .../Extensions/ArticleStringFormatter.swift | 130 ++++++++++++++++ .../SanitizedTitlePerformanceTests.swift | 54 +++++++ .../SanitizedTitleTests.swift | 143 ++++++++++++++++++ 4 files changed, 327 insertions(+), 43 deletions(-) create mode 100644 Tests/NetNewsWireTests/SanitizedTitlePerformanceTests.swift create mode 100644 Tests/NetNewsWireTests/SanitizedTitleTests.swift diff --git a/Modules/Articles/Sources/Articles/Article.swift b/Modules/Articles/Sources/Articles/Article.swift index 44c417579..56db4e671 100644 --- a/Modules/Articles/Sources/Articles/Article.swift +++ b/Modules/Articles/Sources/Articles/Article.swift @@ -92,46 +92,3 @@ public extension Array where Element == Article { } } -public extension Article { - private static let allowedTags: Set = ["b", "bdi", "bdo", "cite", "code", "del", "dfn", "em", "i", "ins", "kbd", "mark", "q", "s", "samp", "small", "strong", "sub", "sup", "time", "u", "var"] - - func sanitizedTitle(forHTML: Bool = true) -> String? { - guard let title else { - return nil - } - - let scanner = Scanner(string: title) - scanner.charactersToBeSkipped = nil - var result = "" - result.reserveCapacity(title.count) - - while !scanner.isAtEnd { - if let text = scanner.scanUpToString("<") { - result.append(text) - } - - if scanner.scanString("<") != nil { - // All the allowed tags currently don't allow attributes - if let tag = scanner.scanUpToString(">") { - if Self.allowedTags.contains(tag.replacingOccurrences(of: "/", with: "")) { - if forHTML { - result.append("<\(tag)>") - } else { - result.append("") - } - } else { - if forHTML { - result.append("<\(tag)>") - } else { - result.append("<\(tag)>") - } - } - - _ = scanner.scanString(">") - } - } - } - - return result - } -} diff --git a/Shared/Extensions/ArticleStringFormatter.swift b/Shared/Extensions/ArticleStringFormatter.swift index 1a064837d..9b830d99c 100644 --- a/Shared/Extensions/ArticleStringFormatter.swift +++ b/Shared/Extensions/ArticleStringFormatter.swift @@ -128,4 +128,134 @@ import RSParser } return dateFormatter.string(from: date) } + + // MARK: - Title sanitization + + // Stored as UTF-8 byte arrays so tag-name lookup during + // `sanitizedTitle` can be done byte-level without converting the + // scanned tag back to a String per call. + nonisolated private static let allowedTagsBytes: Set<[UInt8]> = { + let names = ["b", "bdi", "bdo", "cite", "code", "del", "dfn", "em", + "i", "ins", "kbd", "mark", "q", "s", "samp", "small", + "strong", "sub", "sup", "time", "u", "var"] + return Set(names.map { Array($0.utf8) }) + }() + + /// Sanitize an article title, which may contain HTML, into + /// either HTML-safe rendering (when `forHTML: true`) or a + /// plain-text form suitable for further processing (when + /// `forHTML: false`). Returns nil iff `title` is nil. + /// + /// Behavior for each of the four (allowed, forHTML) combinations: + /// - allowed tag, forHTML=true: tag preserved as-is (`Bold`). + /// - allowed tag, forHTML=false: tag dropped, contents kept. + /// - disallowed tag, forHTML=true: tag escaped as `<...>` text. + /// - disallowed tag, forHTML=false: tag preserved literally (the + /// caller — typically `strippingHTML` — removes it later). + /// + /// Implementation notes: single pass over UTF-8 bytes. `<`, `>`, + /// `/`, and ASCII tag characters are all single-byte; non-ASCII + /// bytes pass through as-is (correct for multi-byte text + /// content). The previous Scanner-based implementation went + /// through Foundation for every tag boundary, with per-tag + /// `scanUpToString` bridges and String allocations. On the cold + /// scroll path, that cost compounded across every unique article + /// title. + nonisolated static func sanitizedTitle(_ title: String?, forHTML: Bool) -> String? { + guard let title else { + return nil + } + if title.isEmpty { + return "" + } + + let utf8 = Array(title.utf8) + let count = utf8.count + var out = [UInt8]() + out.reserveCapacity(count) + + let lt = UInt8(ascii: "<") + let gt = UInt8(ascii: ">") + let slash = UInt8(ascii: "/") + // `<` and `>` as byte arrays — pre-encoded so the + // escape path doesn't pay a String-to-UTF8 conversion per tag. + let ltEntity: [UInt8] = [ + UInt8(ascii: "&"), UInt8(ascii: "l"), UInt8(ascii: "t"), UInt8(ascii: ";") + ] + let gtEntity: [UInt8] = [ + UInt8(ascii: "&"), UInt8(ascii: "g"), UInt8(ascii: "t"), UInt8(ascii: ";") + ] + + var i = 0 + while i < count { + let b = utf8[i] + if b != lt { + out.append(b) + i += 1 + continue + } + + // Found `<`. Scan forward for matching `>` or end of input. + var j = i + 1 + while j < count && utf8[j] != gt { + j += 1 + } + + // Tag body is utf8[i+1..")` returns nil + // when no characters are scanned (either at end of + // string, or `>` is immediately next). In both cases we + // emit no tag and don't consume the `>` — the outer loop + // handles any trailing `>` as literal text on the next + // iteration. + let tagStart = i + 1 + let tagEnd = j + if tagStart == tagEnd { + i += 1 // past the `<` only + continue + } + + // Build a normalized tag name for lookup. The original + // used `tag.replacingOccurrences(of: "/", with: "")` — + // ALL slashes removed, case preserved. Match that. + var normalized = [UInt8]() + normalized.reserveCapacity(tagEnd - tagStart) + for k in tagStart..` if one was found, else to end of input. + i = (j < count) ? j + 1 : count + } + + return String(decoding: out, as: UTF8.self) + } } diff --git a/Tests/NetNewsWireTests/SanitizedTitlePerformanceTests.swift b/Tests/NetNewsWireTests/SanitizedTitlePerformanceTests.swift new file mode 100644 index 000000000..d3cdcf144 --- /dev/null +++ b/Tests/NetNewsWireTests/SanitizedTitlePerformanceTests.swift @@ -0,0 +1,54 @@ +// +// SanitizedTitlePerformanceTests.swift +// NetNewsWireTests +// +// Created by Brent Simmons on 4/21/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation +import XCTest + +@testable import NetNewsWire + +/// Performance baseline for `ArticleStringFormatter.sanitizedTitle(_:forHTML:)`. +/// +/// Benchmark: release build, M1 Studio. Mean per-call time across +/// a mix of eight titles, with `forHTML=true` and `forHTML=false` +/// +/// Scanner-based (old): 0.00000955 seconds/call +/// Byte-level (current): 0.00000043 seconds/call +/// Speedup: ~22× +/// +/// (The old Scanner-based implementation has been deleted.) +final class SanitizedTitlePerformanceTests: XCTestCase { + + private static let titles: [String] = [ + "Simple plain title", + "Title with bold and italic words inline", + "Mixed allowed and tags", + "Title with entities & ampersand and <escaped> text", + "Long title that stretches on and on without any tags at all", + "Unicode title with emoji 🎉 and accents café résumé", + "Full-tag title with multiple inline tags", + "A somewhat longer realistic title mentioning iOS, macOS, and watchOS updates" + ] + + func testSanitizedTitle() { + let titles = Self.titles + var checksum = 0 + measure { + for _ in 0..<10_000 { + for title in titles { + if let s = ArticleStringFormatter.sanitizedTitle(title, forHTML: true) { + checksum &+= s.utf8.count + } + if let s = ArticleStringFormatter.sanitizedTitle(title, forHTML: false) { + checksum &+= s.utf8.count + } + } + } + } + XCTAssertGreaterThan(checksum, 0) + } +} diff --git a/Tests/NetNewsWireTests/SanitizedTitleTests.swift b/Tests/NetNewsWireTests/SanitizedTitleTests.swift new file mode 100644 index 000000000..da7e6f395 --- /dev/null +++ b/Tests/NetNewsWireTests/SanitizedTitleTests.swift @@ -0,0 +1,143 @@ +// +// SanitizedTitleTests.swift +// NetNewsWireTests +// +// Created by Brent Simmons on 4/21/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation +import Testing + +@testable import NetNewsWire + +/// Tests for `ArticleStringFormatter.sanitizedTitle(_:forHTML:)`. +@Suite struct SanitizedTitleTests { + + // MARK: - No tags + + @Test("Plain text passes through unchanged in both modes", + arguments: [true, false]) + func plainTextPreserved(forHTML: Bool) { + #expect(ArticleStringFormatter.sanitizedTitle("Hello World", forHTML: forHTML) == "Hello World") + } + + @Test("Empty string returns empty string in both modes", + arguments: [true, false]) + func emptyString(forHTML: Bool) { + #expect(ArticleStringFormatter.sanitizedTitle("", forHTML: forHTML) == "") + } + + @Test("Nil title returns nil in both modes", + arguments: [true, false]) + func nilTitleReturnsNil(forHTML: Bool) { + #expect(ArticleStringFormatter.sanitizedTitle(nil, forHTML: forHTML) == nil) + } + + // MARK: - Allowed tags (present in the whitelist — b, i, em, etc.) + + @Test func allowedTagForHTMLIsPreserved() { + #expect(ArticleStringFormatter.sanitizedTitle("Use bold", forHTML: true) == "Use bold") + } + + @Test func allowedTagNotForHTMLIsStripped() { + #expect(ArticleStringFormatter.sanitizedTitle("Use bold", forHTML: false) == "Use bold") + } + + @Test func multipleAllowedTagsForHTML() { + #expect( + ArticleStringFormatter.sanitizedTitle("Bold and italic", forHTML: true) + == "Bold and italic" + ) + } + + @Test func multipleAllowedTagsNotForHTML() { + #expect( + ArticleStringFormatter.sanitizedTitle("Bold and italic", forHTML: false) + == "Bold and italic" + ) + } + + // MARK: - Disallowed tags (not in the whitelist — script, div, etc.) + + @Test("Disallowed tag is escaped with forHTML=true so it renders as text") + func disallowedTagForHTMLIsEscaped() { + #expect( + ArticleStringFormatter.sanitizedTitle("Use ", forHTML: true) + == "Use <script>evil</script>" + ) + } + + // Disallowed tags with forHTML=false are passed through literally. + // Callers (specifically `strippingHTML`) may remove them later. + @Test func disallowedTagNotForHTMLIsPreservedLiterally() { + #expect( + ArticleStringFormatter.sanitizedTitle("Use ", forHTML: false) + == "Use " + ) + } + + // MARK: - Slash handling + + // The implementation strips ALL slashes from the tag name before + // looking it up in the allowed set. That means `` → "b" + // (allowed), `` → "b" (allowed), `
` → "br" (not allowed). + + @Test(" normalizes to b (allowed) — preserved under forHTML", + arguments: [ + (true, "XY"), + (false, "XY") + ]) + func selfClosingAllowedTag(forHTML: Bool, expected: String) { + #expect(ArticleStringFormatter.sanitizedTitle("XY", forHTML: forHTML) == expected) + } + + @Test("
normalizes to br (not allowed) — escaped or passed through", + arguments: [ + (true, "X<br/>Y"), + (false, "X
Y") + ]) + func selfClosingDisallowedTag(forHTML: Bool, expected: String) { + #expect(ArticleStringFormatter.sanitizedTitle("X
Y", forHTML: forHTML) == expected) + } + + // MARK: - Malformed input + + // Unclosed tag (no `>` to terminate). We scan to end of input as + // the tag body and still emit closing punctuation — a slightly + // weird but stable behavior inherited from the Scanner-based + // predecessor, which tests pinned to preserve. + + @Test("Unclosed tag with forHTML=false emits literal `` with synthesized `>`") + func unclosedTagNotForHTML() { + #expect(ArticleStringFormatter.sanitizedTitle("foo ") + } + + @Test("Unclosed tag with forHTML=true emits escaped `<tag>`") + func unclosedTagForHTML() { + #expect(ArticleStringFormatter.sanitizedTitle("foo Café
", forHTML: true) == "Café") + } + + @Test func unicodeInsideAllowedTagNotForHTML() { + #expect(ArticleStringFormatter.sanitizedTitle("Café", forHTML: false) == "Café") + } +}