Skip to content

Commit 9714f97

Browse files
committed
[stdlib] Substring: round indices down to nearest character in indexing operations
Distances between indices aren’t well-defined without this.
1 parent 755712a commit 9714f97

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

stdlib/public/core/Substring.swift

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,8 @@ extension Substring: StringProtocol {
354354
// `Substring`'s bounds do not fall on grapheme boundaries in `base`.
355355

356356
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
357-
var i = _validateInclusiveScalarIndex(i)
357+
var i = _roundDownToNearestCharacter(
358+
_validateInclusiveScalarIndex(i))
358359
if distance >= 0 {
359360
for _ in stride(from: 0, to: distance, by: 1) {
360361
_precondition(i < endIndex, "String index is out of bounds")
@@ -390,7 +391,7 @@ extension Substring: StringProtocol {
390391
let limit = _wholeGuts.ensureMatchingEncoding(limit)
391392
let start = _wholeGuts.ensureMatchingEncoding(i)
392393

393-
var i = _validateInclusiveScalarIndex(i)
394+
var i = _roundDownToNearestCharacter(_validateInclusiveScalarIndex(i))
394395
if distance >= 0 {
395396
for _ in stride(from: 0, to: distance, by: 1) {
396397
guard limit < start || i < limit else { return nil }
@@ -422,8 +423,10 @@ extension Substring: StringProtocol {
422423
// grapheme breaks -- swapping `start` and `end` may change the magnitude of
423424
// the result.
424425

425-
let start = _validateInclusiveScalarIndex(start)
426-
let end = _validateInclusiveScalarIndex(end)
426+
let start = _roundDownToNearestCharacter(
427+
_validateInclusiveScalarIndex(start))
428+
let end = _roundDownToNearestCharacter(
429+
_validateInclusiveScalarIndex(end))
427430

428431
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
429432

0 commit comments

Comments
 (0)