Skip to content

Commit bef686b

Browse files
committed
Handle advancing with possibile sub-character end.
When searching in a substring with an endIndex that isn't on a character boundary, advancing from the penultimate character position to the substring's endIndex can end up failing, since advancing by a character finds the character-aligned index that is _past_ the substring end. This change handles that case.
1 parent 16ba9d0 commit bef686b

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

Sources/_StringProcessing/Engine/Processor.swift

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -175,14 +175,25 @@ extension Processor {
175175
// save point was restored
176176
mutating func consume(_ n: Distance) -> Bool {
177177
// TODO: needs benchmark coverage
178-
guard let idx = input.index(
178+
if let idx = input.index(
179179
currentPosition, offsetBy: n.rawValue, limitedBy: end
180-
) else {
181-
signalFailure()
182-
return false
180+
) {
181+
currentPosition = idx
182+
return true
183183
}
184-
currentPosition = idx
185-
return true
184+
185+
// If `end` falls in the middle of a character, and we are trying to advance
186+
// by one "character", then we should max out at `end` even though the above
187+
// advancement will result in `nil`.
188+
if n == 1, let idx = input.unicodeScalars.index(
189+
currentPosition, offsetBy: n.rawValue, limitedBy: end
190+
) {
191+
currentPosition = idx
192+
return true
193+
}
194+
195+
signalFailure()
196+
return false
186197
}
187198

188199
// Advances in unicode scalar view

0 commit comments

Comments
 (0)