Skip to content

Commit

Permalink
add overflow checking for abs(::Rational) (#48912)
Browse files Browse the repository at this point in the history
  • Loading branch information
vmpyr committed Mar 10, 2023
1 parent ba1d565 commit ad304ea
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
4 changes: 2 additions & 2 deletions base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ signbit(x::Rational) = signbit(x.num)
copysign(x::Rational, y::Real) = unsafe_rational(copysign(x.num, y), x.den)
copysign(x::Rational, y::Rational) = unsafe_rational(copysign(x.num, y.num), x.den)

abs(x::Rational) = Rational(abs(x.num), x.den)
abs(x::Rational) = unsafe_rational(checked_abs(x.num), x.den)

typemin(::Type{Rational{T}}) where {T<:Signed} = unsafe_rational(T, -one(T), zero(T))
typemin(::Type{Rational{T}}) where {T<:Integer} = unsafe_rational(T, zero(T), one(T))
Expand Down Expand Up @@ -545,7 +545,7 @@ function hash(x::Rational{<:BitInteger64}, h::UInt)
pow = trailing_zeros(den)
den >>= pow
pow = -pow
if den == 1 && abs(num) < 9007199254740992
if den == 1 && uabs(num) < UInt64(maxintfloat(Float64))
return hash(ldexp(Float64(num),pow),h)
end
end
Expand Down
3 changes: 3 additions & 0 deletions test/hashing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ end
@test hash(nextfloat(2.0^63)) == hash(UInt64(nextfloat(2.0^63)))
@test hash(prevfloat(2.0^64)) == hash(UInt64(prevfloat(2.0^64)))

# issue #48744
@test hash(typemin(Int)//1) === hash(big(typemin(Int)//1))

# issue #9264
@test hash(1//6,zero(UInt)) == invoke(hash, Tuple{Real, UInt}, 1//6, zero(UInt))
@test hash(1//6) == hash(big(1)//big(6))
Expand Down
3 changes: 3 additions & 0 deletions test/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,9 @@ end
@test read(io2, typeof(rational2)) == rational2
end
end
@testset "abs overflow for Rational" begin
@test_throws OverflowError abs(typemin(Int) // 1)
end
@testset "parse" begin
# Non-negative Int in which parsing is expected to work
@test parse(Rational{Int}, string(10)) == 10 // 1
Expand Down

0 comments on commit ad304ea

Please sign in to comment.