Skip to content

Commit

Permalink
clamp: Turn ifelse into ternary
Browse files Browse the repository at this point in the history
Fixes JuliaLang#54022

Co-authored-by: Klaus Crusius <KlausC@users.noreply.github.com>
  • Loading branch information
barucden and KlausC committed Apr 12, 2024
1 parent 630f754 commit f259c21
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
11 changes: 5 additions & 6 deletions base/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,10 @@ julia> clamp.([11, 8, 5], 10, 6) # an example where lo > hi
10
```
"""
clamp(x::X, lo::L, hi::H) where {X,L,H} =
ifelse(x > hi, convert(promote_type(X,L,H), hi),
ifelse(x < lo,
convert(promote_type(X,L,H), lo),
convert(promote_type(X,L,H), x)))
function clamp(x::X, lo::L, hi::H) where {X,L,H}
T = promote_type(X, L, H)
return (x > hi) ? convert(T, hi) : (x < lo) ? convert(T, lo) : convert(T, x)
end

"""
clamp(x, T)::T
Expand All @@ -120,7 +119,7 @@ julia> trunc(Int, 4pi^2)
39
```
"""
clamp(x, ::Type{T}) where {T<:Integer} = clamp(x, typemin(T), typemax(T)) % T
clamp(x, ::Type{T}) where {T<:Integer} = convert(T, clamp(x, typemin(T), typemax(T)))


"""
Expand Down
6 changes: 6 additions & 0 deletions test/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ has_fma = Dict(
clamp!(x, 1, 3)
@test x == [1.0, 1.0, 2.0, 3.0, 3.0]
end

@test clamp(typemax(UInt64), Int64) === typemax(Int64)
@test clamp(typemin(Int), UInt64) === typemin(UInt64)
@test clamp(Int16(-1), UInt16) === 0x0
@test clamp(-1, 2, UInt(0)) === UInt(2)
@test clamp(typemax(UInt16), Int16) === Int16(32767)
end

@testset "constants" begin
Expand Down

0 comments on commit f259c21

Please sign in to comment.