Skip to content

Commit 311f772

Browse files
LilithHafnerDrvi
authored andcommitted
Fix edge cases where inexact conversions to UInt don't throw (JuliaLang#51095)
(cherry picked from commit fb76136)
1 parent fca98fc commit 311f772

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

base/float.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -882,7 +882,10 @@ for Ti in (Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UIn
882882
end
883883
end
884884
function (::Type{$Ti})(x::$Tf)
885-
if ($(Tf(typemin(Ti))) <= x <= $(Tf(typemax(Ti)))) && isinteger(x)
885+
# When typemax(Ti) is not representable by Tf but typemax(Ti) + 1 is,
886+
# then < Tf(typemax(Ti) + 1) is stricter than <= Tf(typemax(Ti)). Using
887+
# the former causes us to throw on UInt64(Float64(typemax(UInt64))+1)
888+
if ($(Tf(typemin(Ti))) <= x < $(Tf(typemax(Ti))+one(Tf))) && isinteger(x)
886889
return unsafe_trunc($Ti,x)
887890
else
888891
throw(InexactError($(Expr(:quote,Ti.name.name)), $Ti, x))

test/floatfuncs.jl

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,3 +256,34 @@ end
256256
@test isapprox(typemin(T), 0.0, rtol=1)
257257
end
258258
end
259+
260+
@testset "Conversion from floating point to unsigned integer near extremes (#51063)" begin
261+
@test_throws InexactError UInt32(4.2949673f9)
262+
@test_throws InexactError UInt64(1.8446744f19)
263+
@test_throws InexactError UInt64(1.8446744073709552e19)
264+
@test_throws InexactError UInt128(3.402823669209385e38)
265+
end
266+
267+
@testset "Conversion from floating point to integer near extremes (exhaustive)" begin
268+
for Ti in Base.BitInteger_types, Tf in (Float16, Float32, Float64), x in (typemin(Ti), typemax(Ti))
269+
y = Tf(x)
270+
for i in -3:3
271+
z = nextfloat(y, i)
272+
273+
result = isfinite(z) ? round(BigInt, z) : error
274+
result = result !== error && typemin(Ti) <= result <= typemax(Ti) ? result : error
275+
276+
if result === error
277+
# @test_throws InexactError round(Ti, z) Broken because of #51113
278+
@test_throws InexactError Ti(z)
279+
else
280+
@test result == round(Ti, z)
281+
if isinteger(z)
282+
@test result == Ti(z)
283+
else
284+
@test_throws InexactError Ti(z)
285+
end
286+
end
287+
end
288+
end
289+
end

0 commit comments

Comments
 (0)