Skip to content

Commit 1f1c00e

Browse files
committed
Support defining custom hashes for generated bitflags
Duplicates improvement made to Base's Enums: JuliaLang/julia#49777 and JuliaLang/julia#49964
1 parent 0c029bb commit 1f1c00e

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

src/BitFlags.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ Base.:&(x::T, y::T) where {T<:BitFlag} = T(Integer(x) & Integer(y))
2727

2828
Base.broadcastable(x::BitFlag) = Ref(x)
2929

30+
_bitflag_hash(x::BitFlag, h::UInt) = invoke(hash, Tuple{Any, UInt}, x, h)
31+
Base.hash(x::BitFlag, h::UInt) = _bitflag_hash(x, h)
32+
3033
function Base.print(io::IO, x::T) where T<:BitFlag
3134
compact = get(io, :compact, false)::Bool
3235
xi = Integer(x)
@@ -267,7 +270,7 @@ function _bitflag_impl(__module__::Module, typename::Symbol, basetype::Type{<:Un
267270
Base.typemin(x::Type{$etypename}) = $etypename($lo)
268271
Base.typemax(x::Type{$etypename}) = $etypename($hi)
269272
let flag_hash = hash($etypename)
270-
Base.hash(x::$etypename, h::UInt) = hash(flag_hash, hash(Integer(x), h))
273+
BitFlags._bitflag_hash(x::$etypename, h::UInt) = hash(flag_hash, hash(Integer(x), h))
271274
end
272275
Base.instances(::Type{$etypename}) = ($(instances...),)
273276
$(flagconsts...)

test/runtests.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ end
6666
# Hashing
6767
@test Int(flag2a) == Int(flag3a) # same numerical value, but
6868
@test hash(flag2a) != hash(flag3a) # unique hashes as BitFlag
69+
@test which(hash, (Flag1, UInt)).sig != Tuple{typeof(hash), Flag1, UInt}
70+
struct NonstandardBitFlag <: BitFlags.BitFlag{UInt8} end
71+
let x = NonstandardBitFlag(), h = zero(UInt)
72+
@test hash(x, h) == invoke(hash, Tuple{Any, UInt}, x, h)
73+
end
6974

7075
# Broadcasting
7176
@test [flag1a, flag1b] .| flag1c == [flag1a | flag1c, flag1b | flag1c]

0 commit comments

Comments
 (0)