From 1bfacb8fe9720cc690d73c69a99febd40d1ddfad Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Tue, 6 Feb 2024 18:53:47 -0500 Subject: [PATCH] Fix crash when converting malformed HTML with unmatched closing tag --- Sources/HTMLStreamer/AttributedStringConverter.swift | 8 +++++--- Sources/HTMLStreamer/TextConverter.swift | 8 +++++--- .../AttributedStringConverterTests.swift | 4 ++++ Tests/HTMLStreamerTests/TextConverterTests.swift | 4 ++++ 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Sources/HTMLStreamer/AttributedStringConverter.swift b/Sources/HTMLStreamer/AttributedStringConverter.swift index 7dd826f..5375086 100644 --- a/Sources/HTMLStreamer/AttributedStringConverter.swift +++ b/Sources/HTMLStreamer/AttributedStringConverter.swift @@ -75,10 +75,12 @@ public struct AttributedStringConverter { case .endTag(let name): handleEndTag(name) // if we have a non-default action for the current element, the run finishes here - if actionStack.last != .default { - finishRun() + if let action = actionStack.last { + if action != .default { + finishRun() + } + actionStack.removeLast() } - actionStack.removeLast() case .doctype: // ignored continue diff --git a/Sources/HTMLStreamer/TextConverter.swift b/Sources/HTMLStreamer/TextConverter.swift index b302582..8271aa6 100644 --- a/Sources/HTMLStreamer/TextConverter.swift +++ b/Sources/HTMLStreamer/TextConverter.swift @@ -55,10 +55,12 @@ public struct TextConverter { handleStartTag(name, selfClosing: selfClosing, attributes: attributes) case .endTag(let name): handleEndTag(name) - if actionStack.last != .default { - finishRun() + if let action = actionStack.last { + if action != .default { + finishRun() + } + actionStack.removeLast() } - actionStack.removeLast() case .comment, .doctype: break } diff --git a/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift b/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift index e574a31..6df0da9 100644 --- a/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift +++ b/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift @@ -352,4 +352,8 @@ final class AttributedStringConverterTests: XCTestCase { XCTAssertEqual(convert(#"example.com"#, callbacks: Callbacks.self), result) } + func testMalformedOnlyClosingTag() { + XCTAssertEqual(convert(""), .init()) + } + } diff --git a/Tests/HTMLStreamerTests/TextConverterTests.swift b/Tests/HTMLStreamerTests/TextConverterTests.swift index 09858f9..0ad8ff1 100644 --- a/Tests/HTMLStreamerTests/TextConverterTests.swift +++ b/Tests/HTMLStreamerTests/TextConverterTests.swift @@ -83,4 +83,8 @@ final class TextConverterTests: XCTestCase { XCTAssertEqual(convert(#"example.com"#, callbacks: Callbacks.self), "example.com") } + func testMalformedOnlyClosingTag() { + XCTAssertEqual(convert(""), "") + } + }