Add and use new decodingHTMLEntities function.

This commit is contained in:
Brent Simmons committed 2026-04-20 10:55:25 -07:00
1 parent 9b570cc5ed
commit 466dbf73b2
5 files changed
+44 -6

No files matched your search

@@ -43,7 +43,7 @@ final class ArticleSearchInfo: Hashable, Sendable {
}()
self.bodyForIndex = {
let s = preferredText.rsparser_stringByDecodingHTMLEntities()
let s = preferredText.decodingHTMLEntities()
let sanitizedBody = s.strippingHTML()
if let authorsNames {
@@ -179,7 +179,7 @@ private extension JSONFeedParser {
}
if isSpecialCaseTitleWithEntitiesFeed(feedURL) {
return (title as NSString).rsparser_stringByDecodingHTMLEntities()
return title.decodingHTMLEntities()
}
return title
@@ -0,0 +1,39 @@
//
// String+HTMLEntities.swift
// RSParser
//
// Created by Brent Simmons on 4/20/26.
//
// Swift replacement for the old ObjC `-[NSString rsparser_stringByDecodingHTMLEntities]`.
// Scans a string for `&…;` entity references and expands them via `XMLEntities.decode`
// using `.html` mode (predefined XML, numeric, and HTML named entities). Unrecognized
// entities pass through literally — matches libxml2 HTML-parser behavior.
public extension String {
/// Return the string with all HTML entities (named, decimal, hex) decoded.
/// Unknown entities pass through as-is.
func decodingHTMLEntities() -> String {
let bytes = Array(utf8)
// Fast path: if no `&`, the string has no entities — return it unchanged.
if !bytes.contains(UInt8(ascii: "&")) {
return self
}
var out = [UInt8]()
out.reserveCapacity(bytes.count)
var i = 0
while i < bytes.count {
let b = bytes[i]
if b == UInt8(ascii: "&") {
let decoded = XMLEntities.decode(bytes: bytes, at: i, mode: .html)
out.append(contentsOf: decoded.bytes)
i = decoded.nextIndex
} else {
out.append(b)
i += 1
}
}
return String(decoding: out, as: UTF8.self)
}
}
@@ -81,7 +81,7 @@ import RSParser
s = s.replacingOccurrences(of: "\t", with: "")
if !forHTML {
s = s.rsparser_stringByDecodingHTMLEntities()
s = s.decodingHTMLEntities()
}
s = s.trimmingWhitespace
@@ -113,7 +113,7 @@ import RSParser
if let cachedBody = summaryCache[key] {
return cachedBody
}
var s = body.rsparser_stringByDecodingHTMLEntities()
var s = body.decodingHTMLEntities()
s = s.strippingHTML(maxCharacters: 300)
if s == "Comments" { // Hacker News.
s = ""
@@ -288,7 +288,6 @@ private struct CountedSet<Element> where Element: Hashable {
private extension String {
var decodedEntity: String {
// It's possible the implementation will change, but for now it just calls this.
(self as NSString).rsparser_stringByDecodingHTMLEntities() as String
decodingHTMLEntities()
}
}