Skip to content

Commit

Permalink
make hash(::Xoshiro) compatible with == (#51376)
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet committed Oct 3, 2023
1 parent e1f1cc8 commit 37a1b6f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 17 deletions.
8 changes: 8 additions & 0 deletions stdlib/Random/src/Xoshiro.jl
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ function ==(a::Xoshiro, b::Xoshiro)
a.s0 == b.s0 && a.s1 == b.s1 && a.s2 == b.s2 && a.s3 == b.s3 && a.s4 == b.s4
end

hash(x::Xoshiro, h::UInt) = hash((x.s0, x.s1, x.s2, x.s3, x.s4), h + 0x49a62c2dda6fa9be % UInt)

rng_native_52(::Xoshiro) = UInt64

@inline function rand(rng::Xoshiro, ::SamplerType{UInt64})
Expand Down Expand Up @@ -221,6 +223,12 @@ end

==(a::TaskLocalRNG, b::Xoshiro) = b == a

function hash(x::TaskLocalRNG, h::UInt)
t = current_task()
hash((t.rngState0, t.rngState1, t.rngState2, t.rngState3, t.rngState4), h + 0x49a62c2dda6fa9be % UInt)
end


# for partial words, use upper bits from Xoshiro

rand(r::Union{TaskLocalRNG, Xoshiro}, ::SamplerTrivial{UInt52Raw{UInt64}}) = rand(r, UInt64) >>> 12
Expand Down
51 changes: 34 additions & 17 deletions stdlib/Random/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -594,24 +594,41 @@ guardseed() do
Random.seed!(typemax(UInt128))
end

# copy, == and hash
let seed = rand(UInt32, 10)
r = MersenneTwister(seed)
@test r == MersenneTwister(seed) # r.vals should be all zeros
@test hash(r) == hash(MersenneTwister(seed))
s = copy(r)
@test s == r && s !== r
@test hash(s) == hash(r)
skip, len = rand(0:2000, 2)
for j=1:skip
rand(r)
rand(s)
@testset "copy, == and hash" begin
for RNG = (MersenneTwister, Xoshiro)
seed = rand(UInt32, 10)
r = RNG(seed)
t = RNG(seed)
@test r == t
@test hash(r) == hash(t)
s = copy(r)
@test s == r == t && s !== r
@test hash(s) == hash(r)
skip, len = rand(0:2000, 2)
for j=1:skip
rand(r)
@test r != s
@test hash(r) != hash(s)
rand(s)
end
@test rand(r, len) == rand(s, len)
@test s == r
@test hash(s) == hash(r)
h = rand(UInt)
@test hash(s, h) == hash(r, h)
if RNG == Xoshiro
t = copy(TaskLocalRNG())
@test hash(t) == hash(TaskLocalRNG())
@test hash(t, h) == hash(TaskLocalRNG(), h)
x = rand()
@test hash(t) != hash(TaskLocalRNG())
@test rand(t) == x
@test hash(t) == hash(TaskLocalRNG())
copy!(TaskLocalRNG(), r)
@test hash(TaskLocalRNG()) == hash(r)
@test TaskLocalRNG() == r
end
end
@test rand(r, len) == rand(s, len)
@test s == r
@test hash(s) == hash(r)
h = rand(UInt)
@test hash(s, h) == hash(r, h)
end

# MersenneTwister initialization with invalid values
Expand Down

0 comments on commit 37a1b6f

Please sign in to comment.