Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Sources/Parsing/ParserPrinters/StartsWith.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
public struct StartsWith<Input: Collection>: Parser where Input.SubSequence == Input {
public let count: Int
public let possiblePrefix: AnyCollection<Input.Element>
public let originalPossiblePrefix: Any
public let startsWith: (Input) -> Bool

/// Initializes a parser that successfully returns `Void` when the initial elements of its input
Expand All @@ -57,13 +58,14 @@ public struct StartsWith<Input: Collection>: Parser where Input.SubSequence == I
where PossiblePrefix.Element == Input.Element {
self.count = possiblePrefix.count
self.possiblePrefix = AnyCollection(possiblePrefix)
self.originalPossiblePrefix = possiblePrefix
self.startsWith = { input in input.starts(with: possiblePrefix, by: areEquivalent) }
}

@inlinable
public func parse(_ input: inout Input) throws {
guard self.startsWith(input) else {
throw ParsingError.expectedInput(formatValue(self.possiblePrefix), at: input)
throw ParsingError.expectedInput(formatValue(self.originalPossiblePrefix), at: input)
}
input.removeFirst(self.count)
}
Expand Down
15 changes: 15 additions & 0 deletions Tests/ParsingTests/StartsWithTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,19 @@ final class StartsWithTests: XCTestCase {
XCTAssertNoThrow(try StartsWith("Hello".utf8).parse(&str))
XCTAssertEqual(", world!", Substring(str))
}

func testParseFailure() {
var input = "Goodnight, Blob!"[...].utf8
XCTAssertThrowsError(try StartsWith("Hello, ".utf8).parse(&input)) { error in
XCTAssertEqual(
"""
error: unexpected input
--> input:1:1
1 | Goodnight, Blob!
| ^ expected "Hello, "
""",
"\(error)"
)
}
}
}