Move sanitizedTitle from an Article extension to ArticleStringFormatter, where it belongs. Make it faster. Add tests.

This commit is contained in:
Brent Simmons committed 2026-04-21 20:23:54 -07:00
1 parent 0c8a92c89d
commit 6c15373960
4 files changed
+327 -43

No files matched your search

@@ -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("&lt;\(tag)&gt;")
} else {
result.append("<\(tag)>")
}
}
_ = scanner.scanString(">")
}
}
}
return result
}
}
@@ -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 (`<b>Bold</b>`).
/// - allowed tag, forHTML=false: tag dropped, contents kept.
/// - disallowed tag, forHTML=true: tag escaped as `&lt;...&gt;` 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: "/")
// `&lt;` and `&gt;` 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..<j]. Empty-body edge case matches
// the Scanner quirk: `scanUpToString(">")` 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..<tagEnd {
let byte = utf8[k]
if byte != slash {
normalized.append(byte)
}
}
let isAllowed = Self.allowedTagsBytes.contains(normalized)
if isAllowed {
if forHTML {
// Preserve tag literally (slashes included).
out.append(lt)
out.append(contentsOf: utf8[tagStart..<tagEnd])
out.append(gt)
}
// forHTML=false: tag dropped entirely.
} else {
if forHTML {
// Escape as `&lt;tag&gt;` so the reader sees it
// as text rather than an unknown element.
out.append(contentsOf: ltEntity)
out.append(contentsOf: utf8[tagStart..<tagEnd])
out.append(contentsOf: gtEntity)
} else {
// Preserve literally for a later HTML-stripping
// pass (e.g. `strippingHTML`) to remove.
out.append(lt)
out.append(contentsOf: utf8[tagStart..<tagEnd])
out.append(gt)
}
}
// Advance past `>` if one was found, else to end of input.
i = (j < count) ? j + 1 : count
}
return String(decoding: out, as: UTF8.self)
}
}
@@ -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 <b>bold</b> and <i>italic</i> words inline",
"Mixed <b>allowed</b> and <script>disallowed</script> tags",
"Title with entities &amp; ampersand and &lt;escaped&gt; text",
"Long title that stretches on and on without any tags at all",
"Unicode title with emoji 🎉 and accents café résumé",
"<b>Full-tag</b> <em>title</em> with <code>multiple</code> 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)
}
}
@@ -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 <b>bold</b>", forHTML: true) == "Use <b>bold</b>")
}
@Test func allowedTagNotForHTMLIsStripped() {
#expect(ArticleStringFormatter.sanitizedTitle("Use <b>bold</b>", forHTML: false) == "Use bold")
}
@Test func multipleAllowedTagsForHTML() {
#expect(
ArticleStringFormatter.sanitizedTitle("<b>Bold</b> and <i>italic</i>", forHTML: true)
== "<b>Bold</b> and <i>italic</i>"
)
}
@Test func multipleAllowedTagsNotForHTML() {
#expect(
ArticleStringFormatter.sanitizedTitle("<b>Bold</b> and <i>italic</i>", 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 <script>evil</script>", forHTML: true)
== "Use &lt;script&gt;evil&lt;/script&gt;"
)
}
// Disallowed tags with forHTML=false are passed through literally.
// Callers (specifically `strippingHTML`) may remove them later.
@Test func disallowedTagNotForHTMLIsPreservedLiterally() {
#expect(
ArticleStringFormatter.sanitizedTitle("Use <script>evil</script>", forHTML: false)
== "Use <script>evil</script>"
)
}
// MARK: - Slash handling
// The implementation strips ALL slashes from the tag name before
// looking it up in the allowed set. That means `</b>` → "b"
// (allowed), `<b/>` → "b" (allowed), `<br/>` → "br" (not allowed).
@Test("<b/> normalizes to b (allowed) — preserved under forHTML",
arguments: [
(true, "X<b/>Y"),
(false, "XY")
])
func selfClosingAllowedTag(forHTML: Bool, expected: String) {
#expect(ArticleStringFormatter.sanitizedTitle("X<b/>Y", forHTML: forHTML) == expected)
}
@Test("<br/> normalizes to br (not allowed) — escaped or passed through",
arguments: [
(true, "X&lt;br/&gt;Y"),
(false, "X<br/>Y")
])
func selfClosingDisallowedTag(forHTML: Bool, expected: String) {
#expect(ArticleStringFormatter.sanitizedTitle("X<br/>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 `<tag>` with synthesized `>`")
func unclosedTagNotForHTML() {
#expect(ArticleStringFormatter.sanitizedTitle("foo <bar", forHTML: false) == "foo <bar>")
}
@Test("Unclosed tag with forHTML=true emits escaped `&lt;tag&gt;`")
func unclosedTagForHTML() {
#expect(ArticleStringFormatter.sanitizedTitle("foo <bar", forHTML: true) == "foo &lt;bar&gt;")
}
// Bare `<` at end of input: no tag body, emit nothing for it.
@Test(arguments: [true, false])
func bareLessThanAtEnd(forHTML: Bool) {
#expect(ArticleStringFormatter.sanitizedTitle("foo <", forHTML: forHTML) == "foo ")
}
// MARK: - Unicode
@Test("Plain Unicode content passes through verbatim in both modes",
arguments: [true, false])
func unicodeContentPreserved(forHTML: Bool) {
let input = "Café résumé with emoji 🎉"
#expect(ArticleStringFormatter.sanitizedTitle(input, forHTML: forHTML) == input)
}
@Test func unicodeInsideAllowedTagForHTML() {
#expect(ArticleStringFormatter.sanitizedTitle("<b>Café</b>", forHTML: true) == "<b>Café</b>")
}
@Test func unicodeInsideAllowedTagNotForHTML() {
#expect(ArticleStringFormatter.sanitizedTitle("<b>Café</b>", forHTML: false) == "Café")
}
}