Skip to content

Commit

Permalink
Initial hashing support
Browse files Browse the repository at this point in the history
The performance can be improved but this already works.
  • Loading branch information
barucden committed Oct 16, 2024
1 parent 90748c1 commit 8e8b383
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/decimal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,26 @@ end
# sign
Base.signbit(x::Decimal) = x.s

function isdivisible(x::BigInt, n::Int)
return x % n == 0
end

function Base.decompose(x::Decimal)
if iszero(x)
return (big(0), 0, big((-1)^x.s))
end

coef = (-1)^x.s * x.c

if x.q 0
return (coef * big(5)^x.q, x.q, big(1))
else
q = -x.q
while q > 0 && isdivisible(coef, 5)
coef = coef ÷ 5
q -= 1
end
return (coef, x.q, big(5) ^ q)
end
end

18 changes: 18 additions & 0 deletions test/test_decimal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,22 @@ end
@test string(number(Decimal(false, 543, -1))) == "54.3"
end

@testset "Hashing" begin
@test hash(Decimal(0.)) == hash(0.)
@test hash(Decimal(-0.)) == hash(-0.)
@test hash(Decimal(3)) == hash(3)
@test hash(Decimal(0.09375)) == hash(0.09375)
@test hash(Decimal(-3)) == hash(-3)
@test hash(Decimal(-0.09375)) == hash(-0.09375)

# Equality implies same hash
@test hash(Decimal(0, 100, 0)) == hash(Decimal(0, 10, 1))
@test hash(Decimal(0, 100, 0)) == hash(Decimal(0, 1, 2))
@test hash(Decimal(1, 100, 0)) == hash(Decimal(1, 10, 1))
@test hash(Decimal(1, 100, 0)) == hash(Decimal(1, 1, 2))

@test hash(Decimal(0, 310, -2)) == hash(Decimal(0, 31, -1))
end

end

0 comments on commit 8e8b383

Please sign in to comment.