Skip to content
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

Fix edge cases where inexact conversions to UInt don't throw #51095

Merged
merged 5 commits into from
Aug 30, 2023
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
5 changes: 4 additions & 1 deletion base/float.jl
Original file line number Diff line number Diff line change
Expand Up @@ -939,7 +939,10 @@ for Ti in (Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UIn
end
end
function (::Type{$Ti})(x::$Tf)
if ($(Tf(typemin(Ti))) <= x <= $(Tf(typemax(Ti)))) && isinteger(x)
# When typemax(Ti) is not representable by Tf but typemax(Ti) + 1 is,
# then < Tf(typemax(Ti) + 1) is stricter than <= Tf(typemax(Ti)). Using
# the former causes us to throw on UInt64(Float64(typemax(UInt64))+1)
if ($(Tf(typemin(Ti))) <= x < $(Tf(typemax(Ti))+one(Tf))) && isinteger(x)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this deserves a source comment about why this isn't equivalent to <=.

return unsafe_trunc($Ti,x)
else
throw(InexactError($(Expr(:quote,Ti.name.name)), $Ti, x))
Expand Down
31 changes: 31 additions & 0 deletions test/floatfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,34 @@ end
@test isapprox(typemin(T), 0.0, rtol=1)
end
end

@testset "Conversion from floating point to unsigned integer near extremes (#51063)" begin
@test_throws InexactError UInt32(4.2949673f9)
@test_throws InexactError UInt64(1.8446744f19)
@test_throws InexactError UInt64(1.8446744073709552e19)
@test_throws InexactError UInt128(3.402823669209385e38)
end

@testset "Conversion from floating point to integer near extremes (exhaustive)" begin
for Ti in Base.BitInteger_types, Tf in (Float16, Float32, Float64), x in (typemin(Ti), typemax(Ti))
y = Tf(x)
for i in -3:3
z = nextfloat(y, i)

result = isfinite(z) ? round(BigInt, z) : error
result = result !== error && typemin(Ti) <= result <= typemax(Ti) ? result : error

if result === error
# @test_throws InexactError round(Ti, z) Broken because of #51113
@test_throws InexactError Ti(z)
else
@test result == round(Ti, z)
if isinteger(z)
@test result == Ti(z)
else
@test_throws InexactError Ti(z)
end
end
end
end
end