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

add overflow checking for abs(::Rational) #48912

Merged
merged 3 commits into from
Mar 10, 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
4 changes: 2 additions & 2 deletions base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,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 @@ -540,7 +540,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 @@ -265,6 +265,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