Skip to content

Instantly share code, notes, and snippets.

@NikolaiRuhe
Created April 8, 2022 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NikolaiRuhe/a1b137bad0dfd8bee0d6d1dcba79f2e4 to your computer and use it in GitHub Desktop.
Save NikolaiRuhe/a1b137bad0dfd8bee0d6d1dcba79f2e4 to your computer and use it in GitHub Desktop.
func testCSV() throws {
let plainField = Prefix { $0 != .init(ascii: ",") && $0 != .init(ascii: "|") && $0 != .init(ascii: "\n") }
let quotedField = Parse {
"|".utf8
Many {
OneOf {
Parse { "||".utf8 }.map { Substring("").utf8 }
Prefix { $0 != .init(ascii: "|") }
}
} separator: {
"".utf8
}
"|".utf8
}.map { array in
array.map(Substring.init).joined(separator: "")[...].utf8
}
// .eraseToAnyParser()
let field = OneOf {
quotedField
plainField
}
.map { String(Substring($0)) }
let line = Many {
field
} separator: {
",".utf8
}
let csv = Many {
line
} separator: {
"\n".utf8
} terminator: {
End()
}
let input = #"""
123,Alice
789,|Clarice|
456,|Bob ||Baumeister|||
"""#
let result = try csv.parse(input)
XCTAssertNoDifference([["123", "Alice"], ["789", "Clarice"], ["456", "Bob |Baumeister|"]], result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment