Skip to content

Commit

Permalink
Don't use input.count in PrefixThrough and PrefixUpTo for speedup.
Browse files Browse the repository at this point in the history
Calling Substring.count will calculate the length of the string the first
time it is called which for large strings can be slow.
  • Loading branch information
BjornRuud committed Oct 9, 2024
1 parent 19457ac commit d3fa32f
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 7 deletions.
9 changes: 4 additions & 5 deletions Sources/Parsing/ParserPrinters/PrefixThrough.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,11 @@ public struct PrefixThrough<Input: Collection>: Parser where Input.SubSequence =
let original = input
while let index = input.firstIndex(where: { self.areEquivalent(first, $0) }) {
input = input[index...]
if input.count >= count,
zip(input[index...], self.possibleMatch).allSatisfy(self.areEquivalent)
if let matchEndIndex = input.index(index, offsetBy: count, limitedBy: input.endIndex),
zip(input[..<matchEndIndex], self.possibleMatch).allSatisfy(self.areEquivalent)
{
let index = input.index(index, offsetBy: count)
input = input[index...]
return original[..<index]
input = input[matchEndIndex...]
return original[..<matchEndIndex]
}
input.removeFirst()
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Parsing/ParserPrinters/PrefixUpTo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ public struct PrefixUpTo<Input: Collection>: Parser where Input.SubSequence == I
let original = input
while let index = input.firstIndex(where: { self.areEquivalent(first, $0) }) {
input = input[index...]
if input.count >= count,
zip(input[index...], self.possibleMatch).allSatisfy(self.areEquivalent)
if let matchEndIndex = input.index(index, offsetBy: count, limitedBy: input.endIndex),
zip(input[..<matchEndIndex], self.possibleMatch).allSatisfy(self.areEquivalent)
{
return original[..<index]
}
Expand Down

0 comments on commit d3fa32f

Please sign in to comment.