Skip to content

Use unchecked conversion in clamp #57947

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
8 changes: 7 additions & 1 deletion base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1338,7 +1338,13 @@ function clamp(x, ::Type{T}) where {T<:Integer}
# think of, e.g., clamp(big(2) ^ 200, Int16)
lo = typemin(T)
hi = typemax(T)
return (x > hi) ? hi : (x < lo) ? lo : convert(T, x)
return if x > hi
hi
elseif x < lo
lo
else
x isa Integer ? x % T : T(x)
end
end


Expand Down
3 changes: 3 additions & 0 deletions test/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ has_fma = Dict(
x = clamp(2.0, BigInt)
@test x isa BigInt
@test x == big(2)

@test clamp(2.0, Int) === 2
@test_throws InexactError clamp(2.5, Int)
end
end

Expand Down