Skip to content

Commit

Permalink
Don't use input.count in PrefixThrough and PrefixUpTo for speedup. (#354
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.

Co-authored-by: Stephen Celis <[email protected]>
  • Loading branch information
BjornRuud and stephencelis authored Oct 9, 2024
1 parent e1e155c commit b23c636
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 b23c636

Please sign in to comment.