I have a C function cmark_node *cmark_parse_file(FILE *f, int options);
to which I'd like to pass in a FILE handle. I currently have the following code
public func parse(file: URL, options: Options) throws -> Node? {
var cFileHandle: UnsafeMutablePointer<FILE>?
defer {
if let cFile = cFileHandle {
fclose(cFile)
}
}
cFileHandle = try file.withUnsafeFileSystemRepresentation({ cFileUrl in
if cFileUrl == nil {
throw Errors.invalidFileUrl
}
return fopen(cFileUrl, "r")
})
if cFileHandle == nil {
throw Errors.invalidFile
}
return cmark_parse_file(cFileHandle, options.rawValue)
.map { Node(owned: $0) }
}
Here, I'm trying to
- always close the file handle if opened
- Avoid passing a null pointer to fopen - if the URL cannot be represented by a file system representation
Is there a way to simplify this code? - primarily around this bit
cFileHandle = try file.withUnsafeFileSystemRepresentation({ cFileUrl in
if cFileUrl == nil {
throw Errors.invalidFileUrl
}
return fopen(cFileUrl, "r")
})
if cFileHandle == nil {
throw Errors.invalidFile
}