Skip to content

Commit dfb1ba5

Browse files
authored
Merge pull request #1977 from Jumhyn/master
Avoid FP arithmetic if unnecessary in CGRect.intersection(_:)
2 parents 4789424 + e0ebd76 commit dfb1ba5

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

Foundation/NSGeometry.swift

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -335,10 +335,28 @@ extension CGRect {
335335
let overlapH = rect1SpanH.clamped(to: rect2SpanH)
336336
let overlapV = rect1SpanV.clamped(to: rect2SpanV)
337337

338+
let width: CGFloat
339+
if overlapH == rect1SpanH {
340+
width = rect1.width
341+
} else if overlapH == rect2SpanH {
342+
width = rect2.width
343+
} else {
344+
width = overlapH.upperBound - overlapH.lowerBound
345+
}
346+
347+
let height: CGFloat
348+
if overlapV == rect1SpanV {
349+
height = rect1.height
350+
} else if overlapV == rect2SpanV {
351+
height = rect2.height
352+
} else {
353+
height = overlapV.upperBound - overlapV.lowerBound
354+
}
355+
338356
return CGRect(x: overlapH.lowerBound,
339357
y: overlapV.lowerBound,
340-
width: overlapH.upperBound - overlapH.lowerBound,
341-
height: overlapV.upperBound - overlapV.lowerBound)
358+
width: width,
359+
height: height)
342360
}
343361

344362
public func intersects(_ r2: CGRect) -> Bool {

TestFoundation/TestNSGeometry.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,13 @@ class TestNSGeometry : XCTestCase {
653653
XCTAssertEqual(i9.origin.y, 0)
654654
XCTAssertEqual(i9.size.width, 0)
655655
XCTAssertEqual(i9.size.height, 0)
656+
657+
let r8 = CGRect(x: 10.33333333333333333, y: 0, width: 10, height: 10)
658+
let i10 = CGRect.infinite.intersection(r8)
659+
XCTAssertEqual(r8.origin.x, i10.origin.x)
660+
XCTAssertEqual(r8.origin.y, i10.origin.y)
661+
XCTAssertEqual(r8.size.width, i10.size.width)
662+
XCTAssertEqual(r8.size.height, i10.size.height)
656663
}
657664

658665
func test_CGRect_Intersects() {

0 commit comments

Comments
 (0)