Skip to content

Commit 84765ce

Browse files
committed
Fix Substring.removeSubrange for entire substring (#60744)
fix start and end fix test
1 parent 4c347d2 commit 84765ce

File tree

2 files changed

+40
-6
lines changed

2 files changed

+40
-6
lines changed

stdlib/public/core/StringGutsRangeReplaceable.swift

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -483,9 +483,13 @@ extension _StringGuts {
483483
let newUTF8Count =
484484
oldUTF8Count + newUTF8Subrange.count - oldUTF8SubrangeCount
485485

486-
// Get the character stride in the entire string, not just the substring.
487-
// (Characters in a substring may end beyond the bounds of it.)
488-
let newStride = _opaqueCharacterStride(startingAt: utf8StartOffset)
486+
var newStride = 0
487+
488+
if !newUTF8Subrange.isEmpty {
489+
// Get the character stride in the entire string, not just the substring.
490+
// (Characters in a substring may end beyond the bounds of it.)
491+
newStride = _opaqueCharacterStride(startingAt: utf8StartOffset)
492+
}
489493

490494
startIndex = String.Index(
491495
encodedOffset: utf8StartOffset,
@@ -522,9 +526,14 @@ extension _StringGuts {
522526
// needs to look ahead by more than one Unicode scalar.)
523527
let oldStride = startIndex.characterStride ?? 0
524528
if oldRange.lowerBound <= oldBounds.lowerBound &+ oldStride {
525-
// Get the character stride in the entire string, not just the substring.
526-
// (Characters in a substring may end beyond the bounds of it.)
527-
let newStride = _opaqueCharacterStride(startingAt: newBounds.lowerBound)
529+
var newStride = 0
530+
531+
if !newBounds.isEmpty {
532+
// Get the character stride in the entire string, not just the substring.
533+
// (Characters in a substring may end beyond the bounds of it.)
534+
newStride = _opaqueCharacterStride(startingAt: newBounds.lowerBound)
535+
}
536+
528537
var newStart = String.Index(
529538
encodedOffset: newBounds.lowerBound,
530539
characterStride: newStride

test/stdlib/StringIndex.swift

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,3 +1059,28 @@ suite.test("String.replaceSubrange index validation")
10591059
}
10601060
}
10611061
}
1062+
1063+
suite.test("Substring.removeSubrange entire range") {
1064+
guard #available(SwiftStdlib 5.7, *) else {
1065+
// This is a regression found in 5.7+
1066+
return
1067+
}
1068+
1069+
var a: Substring = "abcdef"
1070+
let aStart = a.startIndex
1071+
let aEnd = a.endIndex
1072+
1073+
a.removeSubrange(aStart ..< aEnd)
1074+
1075+
expectTrue(a.isEmpty)
1076+
1077+
#if _runtime(_ObjC)
1078+
var b: Substring = ("å∫ç∂éƒ" as NSString) as Substring
1079+
let bStart = b.startIndex
1080+
let bEnd = b.endIndex
1081+
1082+
b.removeSubrange(bStart ..< bEnd)
1083+
1084+
expectTrue(b.isEmpty)
1085+
#endif
1086+
}

0 commit comments

Comments
 (0)