@@ -258,9 +258,10 @@ extension String.UTF16View: BidirectionalCollection {
258
258
return result
259
259
}
260
260
261
+ @_effects ( releasenone)
261
262
public func distance( from start: Index , to end: Index ) -> Int {
262
- let start = _guts. ensureMatchingEncoding ( start)
263
- let end = _guts. ensureMatchingEncoding ( end)
263
+ var start = _guts. ensureMatchingEncoding ( start)
264
+ var end = _guts. ensureMatchingEncoding ( end)
264
265
265
266
// FIXME: This method used to not properly validate indices before 5.7;
266
267
// temporarily allow older binaries to keep invoking undefined behavior as
@@ -293,6 +294,11 @@ extension String.UTF16View: BidirectionalCollection {
293
294
// code unit will map to a single UTF-8 code unit, i.e., the worst
294
295
// possible (a.k.a. most compact) case with all ASCII scalars.
295
296
// FIXME: Figure out if a more optimistic threshold would work better.
297
+ start = _utf16AlignNativeIndex ( start)
298
+ end = _utf16AlignNativeIndex ( end)
299
+ guard start <= end else {
300
+ return - _utf16Distance( from: end, to: start)
301
+ }
296
302
return _utf16Distance ( from: start, to: end)
297
303
}
298
304
@@ -737,8 +743,7 @@ extension String.UTF16View {
737
743
return utf16Count
738
744
}
739
745
#endif
740
-
741
- @inline ( __always)
746
+
742
747
internal func _utf16Distance( from start: Index , to end: Index ) -> Int {
743
748
_internalInvariant ( end. transcodedOffset == 0 || end. transcodedOffset == 1 )
744
749
0 commit comments