Skip to content

[stdlib] Refactor Range Overlaps for Performance #23293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion stdlib/public/core/ClosedRange.swift
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,12 @@ extension ClosedRange where Bound: Strideable, Bound.Stride : SignedInteger {
extension ClosedRange {
@inlinable
public func overlaps(_ other: ClosedRange<Bound>) -> Bool {
return self.contains(other.lowerBound) || other.contains(lowerBound)
// Disjoint iff the other range is completely before or after our range.
// Unlike a `Range`, a `ClosedRange` can *not* be empty, so no check for
// that case is needed here.
let isDisjoint = other.upperBound < self.lowerBound
|| self.upperBound < other.lowerBound
return !isDisjoint
}

@inlinable
Expand Down
20 changes: 16 additions & 4 deletions stdlib/public/core/Range.swift
Original file line number Diff line number Diff line change
Expand Up @@ -943,14 +943,26 @@ extension Range {
/// common; otherwise, `false`.
@inlinable
public func overlaps(_ other: Range<Bound>) -> Bool {
return (!other.isEmpty && self.contains(other.lowerBound))
|| (!self.isEmpty && other.contains(self.lowerBound))
// Disjoint iff the other range is completely before or after our range.
// Additionally either `Range` (unlike a `ClosedRange`) could be empty, in
// which case it is disjoint with everything as overlap is defined as having
// an element in common.
let isDisjoint = other.upperBound <= self.lowerBound
|| self.upperBound <= other.lowerBound
|| self.isEmpty || other.isEmpty
return !isDisjoint
}

@inlinable
public func overlaps(_ other: ClosedRange<Bound>) -> Bool {
return self.contains(other.lowerBound)
|| (!self.isEmpty && other.contains(self.lowerBound))
// Disjoint iff the other range is completely before or after our range.
// Additionally the `Range` (unlike the `ClosedRange`) could be empty, in
// which case it is disjoint with everything as overlap is defined as having
// an element in common.
let isDisjoint = other.upperBound < self.lowerBound
|| self.upperBound <= other.lowerBound
|| self.isEmpty
return !isDisjoint
}
}

Expand Down