Created
September 28, 2018 07:59
-
-
Save ddddxxx/25a157d216c61df8b05c3c4edf3c43b5 to your computer and use it in GitHub Desktop.
Range+Clamp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Comparable { | |
func clamped(to range: ClosedRange<Self>) -> Self { | |
return max(min(self, range.upperBound), range.lowerBound) | |
} | |
func clamped(to range: PartialRangeFrom<Self>) -> Self { | |
return max(self, range.lowerBound) | |
} | |
func clamped(to range: PartialRangeThrough<Self>) -> Self { | |
return min(self, range.upperBound) | |
} | |
} | |
extension Strideable { | |
func clamped(to range: Range<Self>) -> Self { | |
guard !range.isEmpty else { | |
preconditionFailure("Range cannot be empty") | |
} | |
let closedRange = range.lowerBound...range.upperBound.advanced(by: -1) | |
return clamped(to: closedRange) | |
} | |
func clamped(to range: PartialRangeUpTo<Self>) -> Self { | |
// I don't think there's a way to check if the range is empty | |
let closedRange = ...range.upperBound.advanced(by: -1) | |
return clamped(to: closedRange) | |
} | |
} | |
extension BinaryFloatingPoint { | |
func clamped(to range: Range<Self>) -> Self { | |
guard !range.isEmpty else { | |
preconditionFailure("Range cannot be empty") | |
} | |
let closedRange = range.lowerBound...range.upperBound.nextDown | |
return clamped(to: closedRange) | |
} | |
func clamped(to range: PartialRangeUpTo<Self>) -> Self { | |
let closedRange = ...range.upperBound.nextDown | |
return clamped(to: closedRange) | |
} | |
} | |
extension Comparable { | |
mutating func clamp(to range: ClosedRange<Self>) { | |
self = clamped(to: range) | |
} | |
mutating func clamp(to range: PartialRangeThrough<Self>) { | |
self = clamped(to: range) | |
} | |
mutating func clamp(to range: PartialRangeFrom<Self>) { | |
self = clamped(to: range) | |
} | |
} | |
extension Strideable { | |
mutating func clamp(to range: Range<Self>) { | |
self = clamped(to: range) | |
} | |
mutating func clamp(to range: PartialRangeUpTo<Self>) { | |
self = clamped(to: range) | |
} | |
} | |
extension BinaryFloatingPoint { | |
mutating func clamp(to range: Range<Self>) { | |
self = clamped(to: range) | |
} | |
mutating func clamp(to range: PartialRangeUpTo<Self>) { | |
self = clamped(to: range) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment