Skip to content

Commit 59e6490

Browse files
[6.2] Use unsigned arithmetic for Span bounds checks (#83215)
This allows us to eliminate a comparison; #83172 will allow the compiler to do it for us instead in the future. **Explanation:** Changes the implementation of Span's subscript bounds checks to use a single unsigned comparison instead of two signed compares. **Scope:** Narrow. Does not apply to any other API. **Issues:** rdar://156068535 **Original PRs:** #83150 **Risk:** Low. Minor implementation tweaks to API that is not widely adopted. **Testing:** CI **Reviewers:** @glessard @meg-gupta
1 parent b30ad5c commit 59e6490

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

stdlib/public/core/Span/MutableSpan.swift

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -290,12 +290,18 @@ extension MutableSpan where Element: ~Copyable {
290290
@_alwaysEmitIntoClient
291291
public subscript(_ position: Index) -> Element {
292292
unsafeAddress {
293-
_precondition(indices.contains(position), "index out of bounds")
293+
_precondition(
294+
UInt(bitPattern: position) < UInt(bitPattern: _count),
295+
"Index out of bounds"
296+
)
294297
return unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: position))
295298
}
296299
@lifetime(self: copy self)
297300
unsafeMutableAddress {
298-
_precondition(indices.contains(position), "index out of bounds")
301+
_precondition(
302+
UInt(bitPattern: position) < UInt(bitPattern: _count),
303+
"Index out of bounds"
304+
)
299305
return unsafe _unsafeAddressOfElement(unchecked: position)
300306
}
301307
}

stdlib/public/core/Span/Span.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -419,7 +419,10 @@ extension Span where Element: ~Copyable {
419419
@inline(__always)
420420
@_alwaysEmitIntoClient
421421
internal func _checkIndex(_ position: Index) {
422-
_precondition(indices.contains(position), "Index out of bounds")
422+
_precondition(
423+
UInt(bitPattern: position) < UInt(bitPattern: _count),
424+
"Index out of bounds"
425+
)
423426
}
424427

425428
/// Accesses the element at the specified position in the `Span`.

0 commit comments

Comments
 (0)