Skip to content

Commit

Permalink
Fix edge cases where inexact conversions to UInt don't throw (#51095)
Browse files Browse the repository at this point in the history
(cherry picked from commit fb76136)
  • Loading branch information
LilithHafner authored and KristofferC committed Jan 24, 2024
1 parent 3552d36 commit 7d3c68e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
5 changes: 4 additions & 1 deletion base/float.jl
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,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)
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 @@ -256,3 +256,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

0 comments on commit 7d3c68e

Please sign in to comment.