Skip to content

Commit 27978d1

Browse files
committed
[stdlib] Eliminate an overflow check in U[M]BP.distance
1 parent d52cd82 commit 27978d1

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

stdlib/public/core/UnsafeBufferPointer.swift.gyb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,14 @@ extension Unsafe${Mutable}BufferPointer: ${Mutable}Collection, RandomAccessColle
207207
// optimizer is not capable of creating partial specializations yet.
208208
// NOTE: Range checks are not performed here, because it is done later by
209209
// the subscript function.
210-
return end - start
210+
// NOTE: We allow the subtraction to silently overflow in release builds
211+
// to eliminate a superflous check when `start` and `end` are both valid
212+
// indices. (The operation can only overflow if `start` is negative, which
213+
// implies it's an invalid index.) `Collection` does not specify what
214+
// `distance` should return when given an invalid index pair.
215+
let result = end.subtractingReportingOverflow(start)
216+
_debugPrecondition(!result.overflow)
217+
return result.partialValue
211218
}
212219

213220
@inlinable // unsafe-performance

0 commit comments

Comments
 (0)