diff --git a/Sources/PotentYAML/Libfyaml.swift b/Sources/PotentYAML/Libfyaml.swift index 4b04907ba..02a716b5b 100644 --- a/Sources/PotentYAML/Libfyaml.swift +++ b/Sources/PotentYAML/Libfyaml.swift @@ -91,6 +91,28 @@ internal enum Libfyaml { return diag } + internal static func hasError(in diag: OpaquePointer?) -> Bool { + + guard let diag else { + return true + } + + return fy_diag_got_error(diag) + } + + internal static func error(from diag: OpaquePointer?) -> (message: String, line: Int, column: Int)? { + + guard let diag else { + return nil + } + + var prev: UnsafeMutableRawPointer? + guard let error = fy_diag_errors_iterate(diag, &prev) else { + return nil + } + + return (String(cString: error.pointee.msg), Int(error.pointee.line), Int(error.pointee.column)) + } } diff --git a/Sources/PotentYAML/YAMLReader.swift b/Sources/PotentYAML/YAMLReader.swift index 89e4fb620..dee950326 100644 --- a/Sources/PotentYAML/YAMLReader.swift +++ b/Sources/PotentYAML/YAMLReader.swift @@ -296,18 +296,11 @@ internal struct YAMLReader { func error(fallback: Error) -> Error { - guard let diag = fy_parser_get_diag(parser) else { + guard let error = Libfyaml.error(from: fy_parser_get_diag(parser)) else { return fallback } - var prev: UnsafeMutableRawPointer? - if let error = fy_diag_errors_iterate(diag, &prev) { - return Error.parserError(message: String(cString: error.pointee.msg), - line: Int(error.pointee.line), - column: Int(error.pointee.column)) - } - - return fallback + return Error.parserError(message: error.message, line: error.line, column: error.column) } func destroy() { diff --git a/Sources/PotentYAML/YAMLWriter.swift b/Sources/PotentYAML/YAMLWriter.swift index 994441fee..d997fb5ac 100644 --- a/Sources/PotentYAML/YAMLWriter.swift +++ b/Sources/PotentYAML/YAMLWriter.swift @@ -193,7 +193,7 @@ internal struct YAMLWriter { private func failIfError() throws { - guard fy_diag_got_error(fy_emitter_get_diag(emitter)) else { + guard Libfyaml.hasError(in: fy_emitter_get_diag(emitter)) else { return } @@ -201,16 +201,12 @@ internal struct YAMLWriter { } private func error() -> Error { - if let diag = fy_emitter_get_diag(emitter) { - var prev: UnsafeMutableRawPointer? - if let error = fy_diag_errors_iterate(diag, &prev) { - - return Error.emitError(message: String(cString: error.pointee.msg)) - } + guard let error = Libfyaml.error(from: fy_emitter_get_diag(emitter)) else { + return .emitError(message: "Unknown emitter error") } - return .emitError(message: "Unknown emitter error") + return .emitError(message: error.message) } private static let emitOutput: Libfyaml.EmitterOutput = { _, _, str, len, userInfo in