From 90efa885863c49dc735005614ab326c58043de6f Mon Sep 17 00:00:00 2001 From: Andrew Hershberger Date: Wed, 31 Jan 2024 16:03:08 -0500 Subject: [PATCH] Expose Gumbo initialization options, output status --- Sources/SwiftGumbo/SwiftGumbo.swift | 12 ++++++++---- Tests/SwiftGumboTests/SwiftGumboTests.swift | 12 +++++++++++- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/Sources/SwiftGumbo/SwiftGumbo.swift b/Sources/SwiftGumbo/SwiftGumbo.swift index c413d63..314e008 100644 --- a/Sources/SwiftGumbo/SwiftGumbo.swift +++ b/Sources/SwiftGumbo/SwiftGumbo.swift @@ -10,18 +10,22 @@ public class SwiftGumbo { private let htmlBuffer: [CChar] let gumboOutput: UnsafeMutablePointer - public init(html: String) { + public let status: GumboOutputStatus + + public init(html: String, options: GumboOptions = kGumboDefaultOptions) { // CGumboParser and the types returned by SwiftGumbo all share the same buffer in memory. // The class holds it strongly to ensure it has the same lifetime as the parser. let htmlBuffer = html.cString(using: .utf8) ?? [] - let outputResult = withUnsafePointer(to: kGumboDefaultOptions) { (optionsPointer) -> Result, Never> in - .success(gumbo_parse_with_options(optionsPointer, htmlBuffer, htmlBuffer.count)) + let outputResult = withUnsafePointer(to: options) { (optionsPointer) -> UnsafeMutablePointer in + gumbo_parse_with_options(optionsPointer, htmlBuffer, htmlBuffer.count) } self.htmlBuffer = htmlBuffer // Safe to force try here since the outputResult only returns success. - self.gumboOutput = try! outputResult.get() + self.gumboOutput = outputResult + + self.status = outputResult.pointee.status } deinit { diff --git a/Tests/SwiftGumboTests/SwiftGumboTests.swift b/Tests/SwiftGumboTests/SwiftGumboTests.swift index 0f15559..4709f5e 100644 --- a/Tests/SwiftGumboTests/SwiftGumboTests.swift +++ b/Tests/SwiftGumboTests/SwiftGumboTests.swift @@ -3,8 +3,9 @@ // Created by Gabe Shahbazian 2020 // +import CGumboParser +import SwiftGumbo import XCTest -@testable import SwiftGumbo final class SwiftGumboTests: XCTestCase { func testParsingDom() { @@ -199,6 +200,14 @@ final class SwiftGumboTests: XCTestCase { XCTAssertEqual(match.count, 4) } + func testMaxTreeDepthOption() { + var options = kGumboDefaultOptions + options.max_tree_depth = 2 + let g = SwiftGumbo(html: #"

node too deep

"#, options: options) + + XCTAssertEqual(g.status, GUMBO_STATUS_TREE_TOO_DEEP) + } + static var allTests = [ ("testParsingDom", testParsingDom), ("testTextContent", testTextContent), @@ -218,5 +227,6 @@ final class SwiftGumboTests: XCTestCase { ("testAttributePrefixSelector", testAttributePrefixSelector), ("testGlobalSelector", testGlobalSelector), ("testNotSelector", testNotSelector), + ("testMaxTreeDepthOption", testMaxTreeDepthOption), ] }