Skip to content

Commit

Permalink
Add Base.hash(::Quaternion, ::UInt) (#136)
Browse files Browse the repository at this point in the history
* add `Base.hash(::Quaternion)`

* add tests for `hash`

* update hash for more readability

* replace `==` with `===` in hash test
  • Loading branch information
hyrodium committed Feb 5, 2024
1 parent 6d90f17 commit 3f5c5c1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Quaternion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,17 @@ function Base.isequal(q::Quaternion, w::Quaternion)
isequal(q.s, w.s) & isequal(q.v1, w.v1) & isequal(q.v2, w.v2) & isequal(q.v3, w.v3)
end

if UInt === UInt64
const h_imags = 0xfa29df508725c1bf, 0x5e6c4b26a400626d, 0x8dfd375bac9f9403
else
const h_imags = 0x62802719, 0x5a9b072e, 0x209019b1
end
const hash_0_imags = hash.(0, h_imags)

function Base.hash(z::Quaternion, h::UInt)
hash(real(z), h xor(xor.(hash.(imag_part(z), h_imags), hash_0_imags)...))
end

"""
extend_analytic(f, q::Quaternion)
Expand Down
10 changes: 10 additions & 0 deletions test/Quaternion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ end
@test !isequal(Quaternion(NaN, 0.0, Inf, -Inf), Quaternion(NaN, -0.0, Inf, -Inf))
end

@testset "hash" begin
# https://github.com/JuliaGeometry/Quaternions.jl/issues/135
@test hash(0) === hash(quat(0)) === hash(0.0) === hash(quat(0.0))
@test hash(1) === hash(quat(1)) === hash(1.0) === hash(quat(1.0))
@test hash(quat(-0.0)) hash(quat(+0.0))
@test allunique([hash(quat(1,0,0,0)), hash(quat(0,1,0,0)), hash(quat(0,0,1,0)), hash(quat(0,0,0,1))])
@test hash(57, UInt(42)) === hash(quat(57), UInt(42))
@test length(unique(Quaternion[quat(2), quat(big"2")])) == 1
end

@testset "convert" begin
@test convert(Quaternion{Float64}, 1) === Quaternion(1.0)
@test convert(Quaternion{Float64}, Quaternion(1, 2, 3, 4)) ===
Expand Down

0 comments on commit 3f5c5c1

Please sign in to comment.