Skip to content

Commit 6d2d2ca

Browse files
committed
Add hash method for quantities
1 parent 26cb2e6 commit 6d2d2ca

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

src/Unitful.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
module Unitful
22

3-
import Base: ==, <, <=, +, -, *, /, //, ^, isequal
3+
import Base: ==, <, <=, +, -, *, /, //, ^, isequal, hash
44
import Base: show, convert
55
import Base: abs, abs2, angle, big, float, fma, muladd, inv, sqrt, cbrt
66
import Base: min, max, floor, ceil, real, imag, conj

src/quantities.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,11 @@ for cmp in [:(==), :isequal]
311311
@eval $cmp(x::Number, y::AbstractQuantity) = $cmp(y,x)
312312
end
313313

314+
# For now, hashes of quantities that are equal but have different units are not equal
315+
function hash(x::AbstractQuantity, h::UInt)
316+
hash(x.val, hash(FreeUnits(unit(x)), h))
317+
end
318+
314319
_dimerr(f) = error("$f can only be well-defined for dimensionless ",
315320
"numbers. For dimensionful numbers, different input units yield physically ",
316321
"different results.")

test/runtests.jl

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,16 @@ Unitful.uconvert(U::Unitful.Units, q::QQQ) = uconvert(U, Quantity(q.val, cm))
571571
end
572572
end
573573

574+
@testset "Hashing" begin
575+
@test hash(big(1.0)m) === hash(big(1.0)m)
576+
@test hash(1.0m) === hash(1m)
577+
@test hash(0.5m) === hash((1//2)m)
578+
@test hash(2.0m) === hash(2.0ContextUnits(m, cm))
579+
@test hash(3.0m) === hash(3.0FixedUnits(m))
580+
@test_broken hash(0.5m) === hash(500mm)
581+
@test_broken hash(1rad) === hash(1)
582+
end
583+
574584
@testset "Unit string parsing" begin
575585
@test uparse("m") == m
576586
@test uparse("m,s") == (m,s)
@@ -2100,11 +2110,11 @@ end
21002110
@testset ">> Level" begin
21012111
@test big(3.0)dBm == big(3.0)dBm
21022112
@test isequal(big(3.0)dBm, big(3.0)dBm)
2103-
@test_broken hash(big(3.0)dBm) == hash(big(3.0)dBm)
2113+
@test hash(big(3.0)dBm) == hash(big(3.0)dBm)
21042114

21052115
@test @dB(3.0V/2.0V) == @dB(3V/V)
21062116
@test isequal(@dB(3.0V/2.0V), @dB(3V/V))
2107-
@test_broken hash(@dB(3.0V/2.0V)) == hash(@dB(3V/V))
2117+
@test hash(@dB(3.0V/2.0V)) == hash(@dB(3V/V))
21082118
end
21092119

21102120
@testset ">> Gain" begin

0 commit comments

Comments
 (0)