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

Remove unsafe ops for Rational #1813

Merged
merged 1 commit into from
Sep 27, 2024
Merged
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
86 changes: 0 additions & 86 deletions src/julia/Rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -193,92 +193,6 @@ function log(a::Rational{T}) where T <: Integer
a != 1 && throw(DomainError(a, "a must be 1"))
end

###############################################################################
#
# Unsafe functions
#
###############################################################################

# No actual mutation is permitted for Julia types
# See #1077

function zero!(a::Rational{T}) where T <: Integer
n = a.num
n = zero!(n)
if a.den == 1
return Rational{T}(n, a.den)
else
return Rational{T}(n, T(1))
end
end

function mul!(a::Rational{T}, b::Rational{T}, c::Rational{T}) where T <: Integer
n = a.num
d = a.den
n = mul!(n, b.num, c.num)
d = mul!(d, b.den, c.den)
if d != 1 && n != 0
g = gcd(n, d)
n = divexact(n, g)
d = divexact(d, g)
end
if n == 0
return Rational{T}(n, T(1))
else
return Rational{T}(n, d)
end
end

function add!(a::Rational{T}, b::Rational{T}, c::Rational{T}) where T <: Integer
if a === b
return add!(a, c)
elseif a == c
return add!(a, b)
else # no aliasing
n = a.num
d = a.den
d = mul!(d, b.den, c.den)
n = mul!(n, b.num, c.den)
n = addmul!(n, b.den, c.num)
if d != 1 && n != 0
g = gcd(n, d)
n = divexact(n, g)
d = divexact(d, g)
end
if n == 0
return Rational{T}(n, T(1))
else
return Rational{T}(n, d)
end
end
end

function add!(a::Rational{T}, b::Rational{T}) where T <: Integer
if a === b
if iseven(a.den)
return Rational{T}(a.num, div(b.den, 2))
else
return Rational{T}(2*a.num, b.den)
end
else
n = a.num
n = mul!(n, n, b.den)
n = addmul!(n, b.num, a.den)
d = a.den
d = mul!(d, d, b.den)
if d != 1 && n != 0
g = gcd(n, d)
n = divexact(n, g)
d = divexact(d, g)
end
if n == 0
return Rational{T}(n, T(1))
else
return Rational{T}(n, d)
end
end
end

###############################################################################
#
# Random generation
Expand Down
Loading