Skip to content

Commit 9baf867

Browse files
committed
Implement hash function
Duplicates improvement made to Base's Enums: JuliaLang/julia#30500 **Before:** ```julia julia> @bitflag Flag1 flag1=0 flag2 flag3 flag4 julia> @benchmark hash(flag1) BenchmarkTools.Trial: 10000 samples with 1000 evaluations. Range (min … max): 11.035 ns … 52.801 ns ┊ GC (min … max): 0.00% … 0.00% Time (median): 15.714 ns ┊ GC (median): 0.00% Time (mean ± σ): 16.003 ns ± 1.305 ns ┊ GC (mean ± σ): 0.00% ± 0.00% ▁▃ █▁▄ ▁ ▂▂▂▁▁▁▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▃▃▃▃▃▄▂▃▄██▆███▃▃▂▂▂▂▆▅█▆▆█▅▃▂ ▃ 11 ns Histogram: frequency by time 17.5 ns < Memory estimate: 0 bytes, allocs estimate: 0. ``` **After:** ```julia julia> @benchmark hash(flag1) BenchmarkTools.Trial: 10000 samples with 1000 evaluations. Range (min … max): 1.397 ns … 33.455 ns ┊ GC (min … max): 0.00% … 0.00% Time (median): 4.819 ns ┊ GC (median): 0.00% Time (mean ± σ): 4.907 ns ± 1.042 ns ┊ GC (mean ± σ): 0.00% ± 0.00% ██ ▅▅ ▂▁▁▁▁▂▂▂▁▁▁▁▂▃▂▁▁▁▁▂▂▁▁▁▂▃▃▂▁▁▁▂▂▂▁▁▁▁▂▂▂▁▁▃███▆▁▂▄███▃▁▂▂ ▃ 1.4 ns Histogram: frequency by time 5.66 ns < Memory estimate: 0 bytes, allocs estimate: 0. ```
1 parent 6bd82b3 commit 9baf867

File tree

2 files changed

+7
-0
lines changed

2 files changed

+7
-0
lines changed

src/BitFlags.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,9 @@ macro bitflag(T::Union{Symbol,Expr}, syms...)
239239
BitFlags.haszero(::Type{$(esc(typename))}) = $(esc(maskzero))
240240
Base.typemin(x::Type{$(esc(typename))}) = $(esc(typename))($lo)
241241
Base.typemax(x::Type{$(esc(typename))}) = $(esc(typename))($hi)
242+
let flag_hash = hash($(esc(typename)))
243+
Base.hash(x::$(esc(typename)), h::UInt) = hash(flag_hash, hash(Integer(x), h))
244+
end
242245
let insts = (Any[$(esc(typename))(v) for v in $(values)]...,)
243246
Base.instances(::Type{$(esc(typename))}) = insts
244247
end

test/runtests.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ end
6262
@test Flag1(7) & flag1a == flag1a
6363
@test flag1a < flag1b < flag1c
6464
@test flag1a | flag1b < flag1c
65+
66+
# Hashing
67+
@test Int(flag2a) == Int(flag3a) # same numerical value, but
68+
@test hash(flag2a) != hash(flag3a) # unique hashes as BitFlag
6569
#end
6670

6771
#@testset "Type properties" begin

0 commit comments

Comments
 (0)