Skip to content

Commit dc69903

Browse files
committed
[stdlib] StringGuts.scalarAlign: Preserve encoding flags in returned index
1 parent 4eab835 commit dc69903

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

stdlib/public/core/StringIndex.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,11 @@ extension String.Index {
439439
@_alwaysEmitIntoClient // Swift 5.7
440440
@inline(__always)
441441
internal var __isUTF16: Bool { _rawBits & 0x8 != 0 }
442+
443+
@_alwaysEmitIntoClient // Swift 5.7
444+
internal func _copyEncoding(from index: Self) -> Self {
445+
Self((_rawBits & ~0xC) | (index._rawBits & 0xC))
446+
}
442447
}
443448

444449
extension String.Index: Equatable {

stdlib/public/core/UnicodeHelpers.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ extension _StringGuts {
167167
result = idx
168168
} else {
169169
// TODO(String performance): isASCII check
170-
result = scalarAlignSlow(idx)
170+
result = scalarAlignSlow(idx)._scalarAligned._copyEncoding(from: idx)
171171
}
172172

173173
_internalInvariant(isOnUnicodeScalarBoundary(result),
@@ -183,15 +183,15 @@ extension _StringGuts {
183183

184184
if _slowPath(idx.transcodedOffset != 0 || idx._encodedOffset == 0) {
185185
// Transcoded index offsets are already scalar aligned
186-
return String.Index(_encodedOffset: idx._encodedOffset)._scalarAligned
186+
return String.Index(_encodedOffset: idx._encodedOffset)
187187
}
188188
if _slowPath(self.isForeign) {
189189
// In 5.1 this check was added to foreignScalarAlign, but when this is
190190
// emitted into a client that then runs against a 5.0 stdlib, it calls
191191
// a version of foreignScalarAlign that doesn't check for this, which
192192
// ends up asking CFString for its endIndex'th character, which throws
193193
// an exception. So we duplicate the check here for back deployment.
194-
guard idx._encodedOffset != self.count else { return idx._scalarAligned }
194+
guard idx._encodedOffset != self.count else { return idx }
195195

196196
let foreignIdx = foreignScalarAlign(idx)
197197
_internalInvariant_5_1(foreignIdx._isScalarAligned)
@@ -200,7 +200,7 @@ extension _StringGuts {
200200

201201
return String.Index(_encodedOffset:
202202
self.withFastUTF8 { _scalarAlign($0, idx._encodedOffset) }
203-
)._scalarAligned
203+
)
204204
}
205205

206206
@inlinable

0 commit comments

Comments
 (0)