@@ -448,7 +448,7 @@ extension String.UTF8View {
448
448
}
449
449
450
450
let ( scalar, scalarLen) = _guts. foreignErrorCorrectedScalar (
451
- endingAt: idx)
451
+ endingAt: idx. strippingTranscoding )
452
452
let utf8Len = UTF8 . width ( scalar)
453
453
return idx. encoded (
454
454
offsetBy: - scalarLen
@@ -457,19 +457,18 @@ extension String.UTF8View {
457
457
458
458
@usableFromInline @inline ( never)
459
459
@_effects ( releasenone)
460
- internal func _foreignSubscript( position i : Index ) -> UTF8 . CodeUnit {
460
+ internal func _foreignSubscript( position idx : Index ) -> UTF8 . CodeUnit {
461
461
_internalInvariant ( _guts. isForeign)
462
462
463
- // FIXME: We should need some kind of alignment if given an index into a
464
- // surrogate pair
463
+ let idx = _utf8AlignForeignIndex ( idx)
465
464
466
465
let scalar = _guts. foreignErrorCorrectedScalar (
467
- startingAt: _guts . scalarAlign ( i ) ) . 0
466
+ startingAt: idx . strippingTranscoding ) . 0
468
467
let encoded = Unicode . UTF8. encode ( scalar) . _unsafelyUnwrappedUnchecked
469
- _internalInvariant ( i . transcodedOffset < 1 + encoded. count)
468
+ _internalInvariant ( idx . transcodedOffset < 1 + encoded. count)
470
469
471
470
return encoded [
472
- encoded. index ( encoded. startIndex, offsetBy: i . transcodedOffset) ]
471
+ encoded. index ( encoded. startIndex, offsetBy: idx . transcodedOffset) ]
473
472
}
474
473
475
474
@usableFromInline @inline ( never)
@@ -492,24 +491,27 @@ extension String.UTF8View {
492
491
@_effects ( releasenone)
493
492
internal func _foreignDistance( from i: Index , to j: Index ) -> Int {
494
493
_internalInvariant ( _guts. isForeign)
495
-
494
+
495
+ let i = _utf8AlignForeignIndex ( i)
496
+ let j = _utf8AlignForeignIndex ( j)
497
+
498
+
496
499
#if _runtime(_ObjC)
497
- // Currently, foreign means NSString
500
+ // Currently, foreign means NSString
498
501
if let count = _cocoaStringUTF8Count (
499
502
_guts. _object. cocoaObject,
500
503
range: i. _encodedOffset ..< j. _encodedOffset
501
504
) {
502
- //_cocoaStringUTF8Count gave us the scalar aligned count, but we still
503
- //need to compensate for sub-scalar indexing, e.g. if `i` is in the middle
504
- //of a two-byte UTF8 scalar.
505
+ // _cocoaStringUTF8Count gave us the scalar aligned count, but we still
506
+ // need to compensate for sub-scalar indexing, e.g. if `i` is in the
507
+ // middle of a two-byte UTF8 scalar.
505
508
let refinedCount = count - ( i. transcodedOffset + j. transcodedOffset)
506
509
_internalInvariant ( refinedCount == _distance ( from: i, to: j) )
507
510
return refinedCount
508
511
}
509
512
#endif
510
513
511
514
return _distance ( from: i, to: j)
512
-
513
515
}
514
516
515
517
@usableFromInline @inline ( never)
0 commit comments