Skip to content

Commit

Permalink
Expose Gumbo initialization options, output status (#2)
Browse files Browse the repository at this point in the history
Allows configuring options like `max_tree_depth` and checking to see
whether the parse was successful.
  • Loading branch information
macdrevx authored Jan 31, 2024
1 parent 509a6e8 commit 1055af6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
12 changes: 8 additions & 4 deletions Sources/SwiftGumbo/SwiftGumbo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,22 @@ public class SwiftGumbo {
private let htmlBuffer: [CChar]
let gumboOutput: UnsafeMutablePointer<GumboOutput>

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<UnsafeMutablePointer<GumboOutput>, Never> in
.success(gumbo_parse_with_options(optionsPointer, htmlBuffer, htmlBuffer.count))
let outputResult = withUnsafePointer(to: options) { (optionsPointer) -> UnsafeMutablePointer<GumboOutput> 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 {
Expand Down
12 changes: 11 additions & 1 deletion Tests/SwiftGumboTests/SwiftGumboTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
// Created by Gabe Shahbazian 2020
//

import CGumboParser
import SwiftGumbo
import XCTest
@testable import SwiftGumbo

final class SwiftGumboTests: XCTestCase {
func testParsingDom() {
Expand Down Expand Up @@ -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: #"<html><body><h1>node too deep</h1></body></html>"#, options: options)

XCTAssertEqual(g.status, GUMBO_STATUS_TREE_TOO_DEEP)
}

static var allTests = [
("testParsingDom", testParsingDom),
("testTextContent", testTextContent),
Expand All @@ -218,5 +227,6 @@ final class SwiftGumboTests: XCTestCase {
("testAttributePrefixSelector", testAttributePrefixSelector),
("testGlobalSelector", testGlobalSelector),
("testNotSelector", testNotSelector),
("testMaxTreeDepthOption", testMaxTreeDepthOption),
]
}

0 comments on commit 1055af6

Please sign in to comment.