Merge branch 'task/port-striphtml-5270'

This commit is contained in:
Brent Simmons committed 2026-04-21 08:53:51 -07:00
commit 1d09ce33fe
8 files changed
+468 -460

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ import Articles
import Account
import ErrorLog
import RSCore
import RSCoreObjC
import RSCoreResources
import RSWeb
import Secrets
@@ -8,7 +8,6 @@
import Foundation
import CommonCrypto
import RSCoreObjC
public extension String {
@@ -181,35 +180,6 @@ public extension String {
return self
}
/// Strips HTML from a string.
/// - Parameter maxCharacters: The maximum characters in the return string.
/// If `nil`, the whole string is used.
///
/// This function removes HTML tags and script/style content, collapses whitespace, and trims leading/trailing whitespace.
/// Works on plain text as well to trim and collapse whitespace.
///
/// History: the original implementation, written in Swift, took up about 10% of the work during scrolling the timeline,
/// and was the single biggest chunk of work during scrolling. (According to the Instruments Time Profiler.)
/// This replacement implementation takes up about 2%.
func strippingHTML(maxCharacters: Int? = nil) -> String {
self.withCString { cString in
let inputLength = strlen(cString)
let outputCapacity = inputLength + 1
let outputBuffer = UnsafeMutablePointer<CChar>.allocate(capacity: outputCapacity)
defer { outputBuffer.deallocate() }
_ = stripHTML(
cString,
inputLength,
outputBuffer,
outputCapacity,
maxCharacters ?? 0
)
return String(cString: outputBuffer)
}
}
/// A copy of an HTML string converted to plain text.
///
/// Replaces `p`, `blockquote`, `div`, `br`, and `li` tags with varying quantities
@@ -0,0 +1,304 @@
//
// StripHTML.swift
// RSCore
//
// Created by Brent Simmons on 4/20/26.
// Copyright © 2026 Brent Simmons. All rights reserved.
//
// Swift port of the previous `striphtml.c`. Operates on the string's
// underlying UTF-8 storage and writes directly into a new `String`'s
// uninitialized storage.
//
// Benchmarks (Apple silicon M1, release build, best-of-10
// from XCTest measure blocks):
//
// Benchmark C (before) Swift (after) Speedup
// ------------------------------ ---------- ------------- -------
// Synthetic, 1000 iterations 0.00271 0.00124 2.19x
// Real-world, 100 iterations 0.01783 0.01190 1.50x
// (apple.html + daringfireball.html
// + inessential.html + scripting.html,
// ~437 KB total per pass; times in seconds)
// MARK: - Public entry point
public extension String {
/// Strips HTML from a string.
///
/// - Parameter maxCharacters: The maximum characters in the return string.
/// If `nil`, the whole string is used.
///
/// This function removes HTML tags and script/style content, collapses
/// whitespace, and trims leading/trailing whitespace. Works on plain text
/// as well to trim and collapse whitespace.
///
/// History: the original implementation, written in Swift, took up about
/// 10% of the work during scrolling the timeline, and was the single
/// biggest chunk of work during scrolling. (According to the Instruments
/// Time Profiler.) A subsequent C port dropped that to about 2%; this
/// pure-Swift rewrite (issue #5270) matches or beats the C version —
/// see the benchmark table at the top of this file.
func strippingHTML(maxCharacters: Int? = nil) -> String {
if self.isEmpty {
return ""
}
var source = self
let maxChars = maxCharacters ?? 0
return source.withUTF8 { inBytes -> String in
let capacity = inBytes.count
if capacity == 0 {
return ""
}
return String(unsafeUninitializedCapacity: capacity) { outBytes in
StripHTML.process(input: inBytes, output: outBytes, maxCharacters: maxChars)
}
}
}
}
// MARK: - Implementation
private enum StripHTML {
// MARK: Tags
// Tags are `StaticString`, not the inferred `String`, for two reasons:
// (1) `tag.utf8Start` gives `matches(…)` a direct `UnsafePointer<UInt8>`
// into the binary's UTF-8 bytes — no closure, no bridging, no ARC;
// (2) `tag.utf8CodeUnitCount` is a stored field set by the compiler at
// literal creation, so `someTag.utf8CodeUnitCount` at each call site
// folds to a constant — no need for a separate `…TagLength` let.
//
// `matches(…)` requires ASCII-lowercase tag bytes; that's a convention
// enforced by this comment and the declarations immediately below, not
// by the type system.
// Script/style tags whose bodies are discarded entirely.
private static let scriptTag: StaticString = "script"
private static let styleTag: StaticString = "style"
private static let closeScriptTag: StaticString = "/script"
private static let closeStyleTag: StaticString = "/style"
// Block-level tags — each injects a single space so word boundaries
// survive when the surrounding markup is removed.
private static let pTag: StaticString = "p>"
private static let closePTag: StaticString = "/p>"
private static let divTag: StaticString = "div>"
private static let closeDivTag: StaticString = "/div>"
private static let blockquoteTag: StaticString = "blockquote>"
private static let closeBlockquoteTag: StaticString = "/blockquote>"
private static let brTag: StaticString = "br>"
private static let brSlashTag: StaticString = "br/>"
private static let brSpaceSlashTag: StaticString = "br />"
private static let closeLiTag: StaticString = "/li>"
// MARK: Byte-level helpers
/// Lowercase an ASCII letter. Non-letters are returned unchanged.
@inline(__always)
private static func asciiToLower(_ byte: UInt8) -> UInt8 {
// Uppercase `A`...`Z` differ from lowercase `a`...`z` only in the
// 0x20 bit, so setting that bit is cheaper than a table lookup or
// `tolower`.
if byte >= UInt8(ascii: "A") && byte <= UInt8(ascii: "Z") {
return byte | 0x20
}
return byte
}
/// Number of bytes in the UTF-8 character whose first byte is `leadByte`.
/// Invalid lead bytes are treated as one-byte characters.
@inline(__always)
private static func utf8CharacterByteCount(_ leadByte: UInt8) -> Int {
if (leadByte & 0x80) == 0 { return 1 } // 0xxxxxxx — ASCII
if (leadByte & 0xE0) == 0xC0 { return 2 } // 110xxxxx — 2-byte lead
if (leadByte & 0xF0) == 0xE0 { return 3 } // 1110xxxx — 3-byte lead
if (leadByte & 0xF8) == 0xF0 { return 4 } // 11110xxx — 4-byte lead
return 1 // Invalid — treat as single byte
}
/// Case-insensitively test whether the bytes at `base + position` start
/// with `tag`. `tag` must be ASCII-lowercase — input bytes are lowered
/// before comparison. Callers must ensure the read is in-bounds before
/// calling; the bounds check stays at the call site because short-circuit
/// evaluation there benchmarks ~28% faster on real-world input than
/// pushing the check inside this function. (The cold bounds-fail path is
/// optimized better by the compiler when it lives outside a tight
/// `@inline(__always)` helper.)
@inline(__always)
private static func matches(_ base: UnsafePointer<UInt8>, at position: Int, _ tag: StaticString) -> Bool {
let tagCount = tag.utf8CodeUnitCount
let tagPointer = tag.utf8Start
var offset = 0
while offset < tagCount {
if asciiToLower(base[position + offset]) != tagPointer[offset] {
return false
}
offset += 1
}
return true
}
// MARK: Main entry (called from `String.strippingHTML`)
/// Strip HTML tags from a UTF-8 byte buffer, writing the plain-text
/// result into `output`. Produces byte-for-byte the same output as the
/// previous `striphtml.c`, so the expected-output fixtures in
/// `StripHTMLTests.swift` stay valid.
///
/// Behavior:
/// - Tags (`<…>`) are removed; their inner markup is discarded.
/// - `<script>…</script>` and `<style>…</style>` bodies are discarded
/// entirely.
/// - Common block-level tags (`<p>`, `</p>`, `<div>`, `</div>`,
/// `<blockquote>`, `</blockquote>`, `<br>`, `<br/>`, `<br />`, `</li>`)
/// inject a space so word boundaries aren't lost when the surrounding
/// tags are removed.
/// - Runs of whitespace (space, tab, CR, LF) collapse to a single space.
/// - Leading and trailing spaces are trimmed.
/// - HTML entities (`&amp;` etc.) are **not** decoded.
///
/// State-machine roles:
/// - `tagLevel`: depth of `<`/`>` nesting. Incremented on `<`, decremented
/// on the matching `>` — but see `inScript`/`inStyle` for the exception.
/// - `inScript` / `inStyle`: true between `<script>` and `</script>` (or
/// the style pair). While either is true, a `<` does **not** bump
/// `tagLevel`, so the `>` at the end of the closing tag is what brings
/// `tagLevel` back to zero. That's the one subtle bit of the algorithm.
/// - `lastCharacterWasSpace`: prevents doubled spaces. Starts `true` so
/// leading whitespace is skipped without a separate branch.
/// - `charactersAdded`: counts output characters for the `maxCharacters`
/// cap.
///
/// - Returns: the number of bytes written to `output`.
static func process(input: UnsafeBufferPointer<UInt8>, output: UnsafeMutableBufferPointer<UInt8>, maxCharacters: Int) -> Int {
let inputCount = input.count
let outputCapacity = output.count
guard inputCount > 0, outputCapacity > 0,
let inputBase = input.baseAddress,
let outputBase = output.baseAddress else {
return 0
}
var inputIndex = 0
var outputIndex = 0
var tagLevel = 0
var inScript = false
var inStyle = false
var lastCharacterWasSpace = true
var charactersAdded = 0
while inputIndex < inputCount && outputIndex < outputCapacity {
if maxCharacters > 0 && charactersAdded >= maxCharacters {
break
}
let byte = inputBase[inputIndex]
if byte == UInt8(ascii: "<") {
if !inScript && !inStyle {
tagLevel += 1
}
// Script / style detection.
if inputIndex + scriptTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, scriptTag) {
inScript = true
} else if inputIndex + styleTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, styleTag) {
inStyle = true
} else if inputIndex + closeScriptTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, closeScriptTag) {
inScript = false
} else if inputIndex + closeStyleTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, closeStyleTag) {
inStyle = false
}
// Block-level tags — inject a space so word boundaries survive.
let isBlockTag =
(inputIndex + pTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, pTag)) ||
(inputIndex + closePTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, closePTag)) ||
(inputIndex + divTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, divTag)) ||
(inputIndex + closeDivTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, closeDivTag)) ||
(inputIndex + blockquoteTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, blockquoteTag)) ||
(inputIndex + closeBlockquoteTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, closeBlockquoteTag)) ||
(inputIndex + brTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, brTag)) ||
(inputIndex + brSlashTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, brSlashTag)) ||
(inputIndex + brSpaceSlashTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, brSpaceSlashTag)) ||
(inputIndex + closeLiTag.utf8CodeUnitCount < inputCount && matches(inputBase, at: inputIndex + 1, closeLiTag))
if isBlockTag && !lastCharacterWasSpace && outputIndex < outputCapacity {
outputBase[outputIndex] = UInt8(ascii: " ")
outputIndex += 1
lastCharacterWasSpace = true
charactersAdded += 1
}
inputIndex += 1
continue
}
if byte == UInt8(ascii: ">") {
if !inScript && !inStyle && tagLevel > 0 {
tagLevel -= 1
}
inputIndex += 1
continue
}
if tagLevel > 0 || inScript || inStyle {
inputIndex += 1
continue
}
// Collapse runs of whitespace (space, tab, CR, LF) to a single space.
if byte == UInt8(ascii: " ") || byte == UInt8(ascii: "\t") || byte == UInt8(ascii: "\r") || byte == UInt8(ascii: "\n") {
if !lastCharacterWasSpace {
outputBase[outputIndex] = UInt8(ascii: " ")
outputIndex += 1
lastCharacterWasSpace = true
charactersAdded += 1
}
inputIndex += 1
continue
}
// It’s a content character — copy to output, update state.
lastCharacterWasSpace = false
// ASCII fast path (overwhelming majority of bytes in real HTML).
if byte < 0x80 {
outputBase[outputIndex] = byte
outputIndex += 1
inputIndex += 1
charactersAdded += 1
continue
}
// Multi-byte UTF-8.
let byteCount = utf8CharacterByteCount(byte)
if outputIndex + byteCount <= outputCapacity && inputIndex + byteCount <= inputCount {
var offset = 0
while offset < byteCount {
outputBase[outputIndex + offset] = inputBase[inputIndex + offset]
offset += 1
}
outputIndex += byteCount
inputIndex += byteCount
charactersAdded += 1
} else {
break
}
}
// Trim trailing spaces.
while outputIndex > 0 && outputBase[outputIndex - 1] == UInt8(ascii: " ") {
outputIndex -= 1
}
return outputIndex
}
}
@@ -7,6 +7,5 @@
@import Foundation;
#import "../striphtml.h"
#import "../NSSharingService+Extension.h"
#import "../NSMenuItem+RSCore.h"
@@ -1,155 +0,0 @@
//
// striphtml.c
// RSCore
//
// Created by Brent Simmons on 10/20/25.
// Copyright © 2025 Brent Simmons. All rights reserved.
//
#include "striphtml.h"
#include <string.h>
#include <ctype.h>
// Check if we're at the start of a tag (case-insensitive)
static bool matchesTag(const char *p, const char *tag) {
size_t len = strlen(tag);
for (size_t i = 0; i < len; i++) {
if (tolower(p[i]) != tolower(tag[i])) {
return false;
}
}
return true;
}
// Get the number of bytes in a UTF-8 character
static inline int utf8CharLength(unsigned char firstByte) {
if ((firstByte & 0x80) == 0) return 1; // 0xxxxxxx
if ((firstByte & 0xE0) == 0xC0) return 2; // 110xxxxx
if ((firstByte & 0xF0) == 0xE0) return 3; // 1110xxxx
if ((firstByte & 0xF8) == 0xF0) return 4; // 11110xxx
return 1; // Invalid, treat as single byte
}
size_t stripHTML(const char *input, size_t inputLength,
char *output, size_t outputCapacity,
size_t maxCharacters) {
// Safety checks
if (input == NULL || output == NULL || outputCapacity == 0) {
if (output != NULL && outputCapacity > 0) {
*output = '\0';
}
return 0;
}
const char *in = input;
const char *inEnd = input + inputLength;
char *out = output;
char *outEnd = output + outputCapacity - 1; // Reserve space for null terminator
int tagLevel = 0;
bool inScript = false;
bool inStyle = false;
bool lastCharacterWasSpace = true; // Start as true to skip leading whitespace
size_t charactersAdded = 0;
while (in < inEnd && out < outEnd) {
if (maxCharacters > 0 && charactersAdded >= maxCharacters) {
break;
}
unsigned char c = *in;
// Handle tag opening
if (c == '<') {
// Only track tag level when not inside script/style
if (!inScript && !inStyle) {
tagLevel++;
}
// Check for script or style tags
if (in + 7 < inEnd && matchesTag(in + 1, "script")) {
inScript = true;
} else if (in + 6 < inEnd && matchesTag(in + 1, "style")) {
inStyle = true;
} else if (in + 8 < inEnd && matchesTag(in + 1, "/script")) {
inScript = false;
} else if (in + 7 < inEnd && matchesTag(in + 1, "/style")) {
inStyle = false;
}
// Check for block-level tags that should add whitespace
// Swift preprocessing converts these tags to spaces or newlines, but then
// the main loop (line 263) converts all whitespace to ' ' anyway.
// So we can just insert a space for all block-level elements.
// Tags: <p>, </p>, <div>, </div>, <blockquote>, </blockquote>, <br>, <br/>, <br />, </li>
if ((in + 2 < inEnd && matchesTag(in + 1, "p>")) ||
(in + 3 < inEnd && matchesTag(in + 1, "/p>")) ||
(in + 4 < inEnd && matchesTag(in + 1, "div>")) ||
(in + 5 < inEnd && matchesTag(in + 1, "/div>")) ||
(in + 11 < inEnd && matchesTag(in + 1, "blockquote>")) ||
(in + 12 < inEnd && matchesTag(in + 1, "/blockquote>")) ||
(in + 3 < inEnd && matchesTag(in + 1, "br>")) ||
(in + 4 < inEnd && matchesTag(in + 1, "br/>")) ||
(in + 5 < inEnd && matchesTag(in + 1, "br />")) ||
(in + 4 < inEnd && matchesTag(in + 1, "/li>"))) {
if (!lastCharacterWasSpace && out < outEnd) {
*out++ = ' ';
lastCharacterWasSpace = true;
charactersAdded++;
}
}
in++;
continue;
}
// Handle tag closing
if (c == '>') {
// Only track tag level when not inside script/style
if (!inScript && !inStyle && tagLevel > 0) {
tagLevel--;
}
in++;
continue;
}
// Skip content inside tags, scripts, or styles
if (tagLevel > 0 || inScript || inStyle) {
in++;
continue;
}
// Handle whitespace
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
if (!lastCharacterWasSpace) {
*out++ = ' ';
lastCharacterWasSpace = true;
charactersAdded++;
}
in++;
continue;
}
// Copy character (handle multi-byte UTF-8)
lastCharacterWasSpace = false;
int charLen = utf8CharLength(c);
// Make sure we have room for the entire UTF-8 character
if (out + charLen <= outEnd && in + charLen <= inEnd) {
for (int i = 0; i < charLen; i++) {
*out++ = *in++;
}
charactersAdded++;
} else {
break; // Not enough room
}
}
// Trim trailing whitespace
while (out > output && *(out - 1) == ' ') {
out--;
}
*out = '\0';
return out - output;
}
@@ -1,30 +0,0 @@
//
// striphtml.h
// RSCore
//
// Created by Brent Simmons on 10/20/25.
// Copyright © 2025 Brent Simmons. All rights reserved.
//
#ifndef striphtml_h
#define striphtml_h
#include <stddef.h>
#include <stdbool.h>
/// Strip HTML tags from a UTF-8 encoded string.
///
/// Remove all HTML tags and everything between script and style tags.
/// Also trim outer whitespace and collapse inner whitespace to single spaces.
///
/// @param input UTF-8 encoded HTML string (does not need to be null-terminated if inputLength is correct)
/// @param inputLength Length of input in bytes
/// @param output Pre-allocated buffer for the result (must be at least inputLength + 1 bytes)
/// @param outputCapacity Maximum bytes that can be written to output (including null terminator)
/// @param maxCharacters Maximum characters to output (0 = no limit)
/// @return Number of bytes written to output (not including null terminator)
size_t stripHTML(const char *input, size_t inputLength,
char *output, size_t outputCapacity,
size_t maxCharacters);
#endif /* striphtml_h */
@@ -0,0 +1,58 @@
//
// StripHTMLPerformanceTests.swift
// RSCoreTests
//
// Created by Brent Simmons on 4/21/26.
// Copyright © 2026 Ranchero Software, LLC. All rights reserved.
//
// Performance tests live here in XCTest because Swift Testing has no
// `measure` block equivalent. Behavior tests are in `StripHTMLTests.swift`
// (Swift Testing). Run in Release for meaningful numbers:
//
// cd Modules/RSCore && swift test -c release --filter StripHTMLPerformanceTests
import XCTest
final class StripHTMLPerformanceTests: XCTestCase {
func testStrippingHTMLPerformance() {
let html = """
<html><body>
<p>This is a test article with <b>bold text</b> and <i>italic text</i>.</p>
<script>console.log('test');</script>
<style>body { margin: 0; }</style>
<p>More content with <a href="http://example.com">links</a> and other tags.</p>
<div>Nested <span>tags</span> are common in HTML.</div>
</body></html>
"""
self.measure {
for _ in 0..<1000 {
_ = html.strippingHTML(maxCharacters: 300)
}
}
}
func testStrippingHTMLPerformanceRealWorld() throws {
let testFiles = ["daringfireball", "apple", "inessential", "scripting"]
var htmlFiles: [String] = []
for testFile in testFiles {
guard let url = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
XCTFail("Could not find \(testFile).html")
return
}
let html = try String(contentsOf: url, encoding: .utf8)
htmlFiles.append(html)
}
self.measure {
for _ in 0..<100 {
for html in htmlFiles {
_ = html.strippingHTML(maxCharacters: 300)
}
}
}
}
}
@@ -6,271 +6,132 @@
// Copyright © 2025 Ranchero Software, LLC. All rights reserved.
//
import XCTest
import Foundation
import Testing
// Legacy Swift implementation for comparison testing
private extension String {
struct StripHTMLTests {
/// Removes an HTML tag and everything between its start and end tags.
private func removingTagAndContents(_ tag: String) -> String {
return self.replacingOccurrences(of: "<\(tag)>[\\s\\S]*?</\(tag)>", with: "", options: [.regularExpression, .caseInsensitive])
@Test func basic() {
#expect("<p>Hello <b>world</b>!</p>".strippingHTML() == "Hello world!")
}
/// Legacy Swift-based HTML stripping implementation (kept for comparison testing).
func legacyStrippingHTML(maxCharacters: Int? = nil) -> String {
if !self.contains("<") {
if let maxCharacters = maxCharacters, maxCharacters < count {
let ix = self.index(self.startIndex, offsetBy: maxCharacters)
return String(self[..<ix])
}
return self
}
var preflight = self
// NOTE: If performance on repeated invocations becomes an issue here, the regexes can be cached.
let options: String.CompareOptions = [.regularExpression, .caseInsensitive]
preflight = preflight.replacingOccurrences(of: "</?(?:blockquote|p|div)>", with: " ", options: options)
preflight = preflight.replacingOccurrences(of: "<p>|</?div>|<br(?: ?/)?>|</li>", with: "\n", options: options)
preflight = preflight.removingTagAndContents("script")
preflight = preflight.removingTagAndContents("style")
let preflightCount = preflight.count
let maxChars = maxCharacters ?? preflightCount
var s = String()
s.reserveCapacity(min(maxChars, preflightCount))
var lastCharacterWasSpace = false
var charactersAdded = 0
var level = 0
for char in preflight {
if char == "<" {
level += 1
} else if char == ">" {
level -= 1
} else if level == 0 {
if char == " " || char == "\r" || char == "\t" || char == "\n" {
if lastCharacterWasSpace {
continue
}
lastCharacterWasSpace = true
s.append(" ")
} else {
lastCharacterWasSpace = false
s.append(char)
}
charactersAdded += 1
if charactersAdded >= maxChars {
break
}
}
}
return s
}
}
final class StripHTMLTests: XCTestCase {
func testStrippingHTMLBasic() {
let html = "<p>Hello <b>world</b>!</p>"
let result = html.strippingHTML()
XCTAssertEqual(result, "Hello world!")
@Test func withScript() {
#expect("<p>Before</p><script>alert('test');</script><p>After</p>".strippingHTML() == "Before After")
}
func testStrippingHTMLWithScript() {
let html = "<p>Before</p><script>alert('test');</script><p>After</p>"
let result = html.strippingHTML()
XCTAssertEqual(result, "Before After")
@Test func withStyle() {
#expect("<p>Content</p><style>body { color: red; }</style><p>More</p>".strippingHTML() == "Content More")
}
func testStrippingHTMLWithStyle() {
let html = "<p>Content</p><style>body { color: red; }</style><p>More</p>"
let result = html.strippingHTML()
XCTAssertEqual(result, "Content More")
}
func testStrippingHTMLWithMaxCharacters() {
@Test func withMaxCharacters() {
let html = "<p>This is a long piece of text that should be truncated at some point.</p>"
let result = html.strippingHTML(maxCharacters: 20)
XCTAssertLessThanOrEqual(result.count, 20)
XCTAssertEqual(result, "This is a long piece")
#expect(result.count <= 20)
#expect(result == "This is a long piece")
}
func testStrippingHTMLWithUTF8() {
let html = "<p>Hello 世界 🌍</p>"
let result = html.strippingHTML()
XCTAssertEqual(result, "Hello 世界 🌍")
@Test func withUTF8() {
#expect("<p>Hello 世界 🌍</p>".strippingHTML() == "Hello 世界 🌍")
}
func testStrippingHTMLWhitespaceCollapsing() {
let html = "<p>Too many\n\n\nspaces</p>"
let result = html.strippingHTML()
XCTAssertFalse(result.contains(" "))
XCTAssertEqual(result, "Too many spaces")
@Test func whitespaceCollapsing() {
let result = "<p>Too many\n\n\nspaces</p>".strippingHTML()
#expect(!result.contains(" "))
#expect(result == "Too many spaces")
}
// Commented out because this doesn’t need to run every time.
// Un-comment it when you want to compare legacy performance to C performance.
// func testStrippingHTMLPerformanceLegacySwift() {
// let html = """
// <html><body>
// <p>This is a test article with <b>bold text</b> and <i>italic text</i>.</p>
// <script>console.log('test');</script>
// <style>body { margin: 0; }</style>
// <p>More content with <a href="http://example.com">links</a> and other tags.</p>
// <div>Nested <span>tags</span> are common in HTML.</div>
// </body></html>
// """
//
// self.measure {
// for _ in 0..<1000 {
// let _ = html.legacyStrippingHTML(maxCharacters: 300)
// }
// }
// }
func testStrippingHTMLPerformance() {
let html = """
<html><body>
<p>This is a test article with <b>bold text</b> and <i>italic text</i>.</p>
<script>console.log('test');</script>
<style>body { margin: 0; }</style>
<p>More content with <a href="http://example.com">links</a> and other tags.</p>
<div>Nested <span>tags</span> are common in HTML.</div>
</body></html>
"""
self.measure {
for _ in 0..<1000 {
_ = html.strippingHTML(maxCharacters: 300)
}
}
@Test func scriptAndStyleAreCaseInsensitive() {
#expect("<p>Before</p><SCRIPT>alert('x');</SCRIPT><P>After</P>".strippingHTML() == "Before After")
#expect("<p>x</p><STYLE>body{}</STYLE><p>y</p>".strippingHTML() == "x y")
#expect("<Script>ignored</Script>visible".strippingHTML() == "visible")
}
func testStrippingHTMLWithRealWorldHTML() throws {
let testFiles = ["daringfireball", "apple", "inessential", "scripting"]
for testFile in testFiles {
guard let url = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
XCTFail("Could not find \(testFile).html")
return
}
let html = try String(contentsOf: url, encoding: .utf8)
// Test both implementations can process real-world HTML
let result = html.strippingHTML(maxCharacters: 300)
XCTAssertFalse(result.isEmpty, "\(testFile): Result should not be empty")
XCTAssertLessThanOrEqual(result.count, 300, "\(testFile): Result should respect maxCharacters")
XCTAssertFalse(result.contains("<"), "\(testFile): Result should not contain HTML tags")
XCTAssertFalse(result.contains("//"), "\(testFile): Should fully remove script content")
}
@Test func plainText() {
#expect(" hello world ".strippingHTML() == "hello world")
#expect("no html here".strippingHTML() == "no html here")
#expect("\n\ttabs and\nnewlines\n".strippingHTML() == "tabs and newlines")
}
// Commented out because this doesn’t need to run every time.
// Un-comment it when you want to compare legacy performance to C performance.
// func testStrippingHTMLPerformanceRealWorldLegacySwift() throws {
// let testFiles = ["daringfireball", "apple", "inessential", "scripting"]
// var htmlFiles: [String] = []
//
// for testFile in testFiles {
// guard let url = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
// XCTFail("Could not find \(testFile).html")
// return
// }
// let html = try String(contentsOf: url, encoding: .utf8)
// htmlFiles.append(html)
// }
//
// self.measure {
// for _ in 0..<100 {
// for html in htmlFiles {
// let _ = html.legacyStrippingHTML(maxCharacters: 300)
// }
// }
// }
// }
func testStrippingHTMLPerformanceRealWorld() throws {
let testFiles = ["daringfireball", "apple", "inessential", "scripting"]
var htmlFiles: [String] = []
for testFile in testFiles {
guard let url = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
XCTFail("Could not find \(testFile).html")
return
}
let html = try String(contentsOf: url, encoding: .utf8)
htmlFiles.append(html)
}
self.measure {
for _ in 0..<100 {
for html in htmlFiles {
_ = html.strippingHTML(maxCharacters: 300)
}
}
}
@Test func doesNotDecodeEntities() {
#expect("<p>A &amp; B</p>".strippingHTML() == "A &amp; B")
#expect("<p>&lt;3 &gt;9 &quot;q&quot;</p>".strippingHTML() == "&lt;3 &gt;9 &quot;q&quot;")
#expect("<p>&#169; &#x2014;</p>".strippingHTML() == "&#169; &#x2014;")
}
// Un-comment this to create the .txt files that contain the expected stripped-HTML results.
// func testRegenerateExpectedOutputFiles() throws {
// let testFiles = ["apple", "daringfireball", "inessential", "scripting"]
//
// for testFile in testFiles {
// guard let htmlURL = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
// XCTFail("Could not find \(testFile).html")
// return
// }
//
// let html = try String(contentsOf: htmlURL, encoding: .utf8)
// let result = html.strippingHTML()
//
// print("\n=== \(testFile) ===")
// print("Result length: \(result.count) characters")
// print("First 200 chars: \(String(result.prefix(200)))")
//
// // Write to /tmp first, then user can copy to source
// let tmpPath = "/tmp/\(testFile).txt"
// try result.write(toFile: tmpPath, atomically: true, encoding: .utf8)
// print("Wrote to: \(tmpPath)")
// }
//
// print("\n\nTo update the expected output files, run:")
// print("cp /tmp/apple.txt Tests/RSCoreTests/Resources/")
// print("cp /tmp/daringfireball.txt Tests/RSCoreTests/Resources/")
// print("cp /tmp/inessential.txt Tests/RSCoreTests/Resources/")
// print("cp /tmp/scripting.txt Tests/RSCoreTests/Resources/")
// }
func testStrippingHTMLMatchesExpectedOutput() throws {
let testFiles = ["apple", "daringfireball", "inessential", "scripting"]
for testFile in testFiles {
guard let htmlURL = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
XCTFail("Could not find \(testFile).html")
return
}
guard let txtURL = Bundle.module.url(forResource: testFile, withExtension: "txt", subdirectory: "Resources") else {
XCTFail("Could not find \(testFile).txt")
return
}
let html = try String(contentsOf: htmlURL, encoding: .utf8)
let expectedOutput = try String(contentsOf: txtURL, encoding: .utf8)
// Test implementation produces expected output
let result = html.strippingHTML()
XCTAssertEqual(result, expectedOutput, "\(testFile): Implementation should match expected output")
}
@Test func emptyString() {
#expect("".strippingHTML() == "")
#expect("".strippingHTML(maxCharacters: 10) == "")
#expect("".strippingHTML(maxCharacters: 0) == "")
}
@Test func blockTagsInjectSpaces() {
#expect("a<br>b".strippingHTML() == "a b")
#expect("a<br/>b".strippingHTML() == "a b")
#expect("a<br />b".strippingHTML() == "a b")
#expect("<div>a</div><div>b</div>".strippingHTML() == "a b")
#expect("<blockquote>a</blockquote><blockquote>b</blockquote>".strippingHTML() == "a b")
#expect("<ul><li>a</li><li>b</li></ul>".strippingHTML() == "a b")
#expect("<p>a</p><p>b</p>".strippingHTML() == "a b")
// Adjacent block-tag-injected spaces don't double up.
#expect("<p>a</p><div>b</div>".strippingHTML() == "a b")
}
@Test func maxCharactersBoundaries() {
let source = "hello world"
#expect(source.strippingHTML(maxCharacters: nil) == "hello world")
#expect(source.strippingHTML(maxCharacters: 0) == "hello world")
#expect(source.strippingHTML(maxCharacters: 1) == "h")
#expect(source.strippingHTML(maxCharacters: 5) == "hello")
#expect(source.strippingHTML(maxCharacters: 100) == "hello world")
}
@Test func nestedTags() {
#expect("<div><div><div>x</div></div></div>".strippingHTML() == "x")
#expect("<b><i><u>deeply nested</u></i></b>".strippingHTML() == "deeply nested")
#expect("<a href=\"#\"><span>link</span></a>".strippingHTML() == "link")
}
@Test(arguments: ["daringfireball", "apple", "inessential", "scripting"])
func withRealWorldHTML(testFile: String) throws {
let url = try #require(Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources"))
let html = try String(contentsOf: url, encoding: .utf8)
let result = html.strippingHTML(maxCharacters: 300)
#expect(!result.isEmpty, "Result should not be empty")
#expect(result.count <= 300, "Result should respect maxCharacters")
#expect(!result.contains("<"), "Result should not contain HTML tags")
#expect(!result.contains("//"), "Should fully remove script content")
}
@Test(arguments: ["apple", "daringfireball", "inessential", "scripting"])
func matchesExpectedOutput(testFile: String) throws {
let htmlURL = try #require(Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources"))
let txtURL = try #require(Bundle.module.url(forResource: testFile, withExtension: "txt", subdirectory: "Resources"))
let html = try String(contentsOf: htmlURL, encoding: .utf8)
let expectedOutput = try String(contentsOf: txtURL, encoding: .utf8)
#expect(html.strippingHTML() == expectedOutput, "Implementation should match expected output")
}
// Un-comment this to regenerate the .txt files containing expected stripped-HTML results.
// @Test func regenerateExpectedOutputFiles() throws {
// let testFiles = ["apple", "daringfireball", "inessential", "scripting"]
// for testFile in testFiles {
// let htmlURL = try #require(Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources"))
// let html = try String(contentsOf: htmlURL, encoding: .utf8)
// let result = html.strippingHTML()
// print("\n=== \(testFile) ===")
// print("Result length: \(result.count) characters")
// print("First 200 chars: \(String(result.prefix(200)))")
// let tmpPath = "/tmp/\(testFile).txt"
// try result.write(toFile: tmpPath, atomically: true, encoding: .utf8)
// print("Wrote to: \(tmpPath)")
// }
// print("\n\nTo update the expected output files, run:")
// print("cp /tmp/apple.txt Tests/RSCoreTests/Resources/")
// print("cp /tmp/daringfireball.txt Tests/RSCoreTests/Resources/")
// print("cp /tmp/inessential.txt Tests/RSCoreTests/Resources/")
// print("cp /tmp/scripting.txt Tests/RSCoreTests/Resources/")
// }
}