mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-12-01 09:50:16 +00:00
Port striphtml from C to Swift.
This commit is contained in:
1 parent
5aacdab85e
commit
d318ec9e12
7 files changed
+335
-357
No files matched your search
@@ -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 — see `StripHTMLTests.swift`):
|
||||
//
|
||||
// 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 (`&` 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 */
|
||||
@@ -8,73 +8,6 @@
|
||||
|
||||
import XCTest
|
||||
|
||||
// Legacy Swift implementation for comparison testing
|
||||
private extension String {
|
||||
|
||||
/// 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])
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
@@ -115,26 +48,6 @@ final class StripHTMLTests: XCTestCase {
|
||||
XCTAssertEqual(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>
|
||||
@@ -172,30 +85,6 @@ final class StripHTMLTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// 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] = []
|
||||
@@ -218,36 +107,6 @@ final class StripHTMLTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// 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"]
|
||||
|
||||
@@ -271,4 +130,34 @@ final class StripHTMLTests: XCTestCase {
|
||||
XCTAssertEqual(result, expectedOutput, "\(testFile): Implementation should match expected output")
|
||||
}
|
||||
}
|
||||
|
||||
// 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/")
|
||||
// }
|
||||
}
|
||||
Reference in new issue
Block a user