Skip to content

Commit

Permalink
Do not error when showing invalid enums (#40042) (#41596)
Browse files Browse the repository at this point in the history
(cherry picked from commit 02807b2)
  • Loading branch information
jakobnissen authored and KristofferC committed Jul 19, 2021
1 parent 7f0ac3f commit 388aa28
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
10 changes: 8 additions & 2 deletions base/Enums.jl
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,16 @@ Base.isless(x::T, y::T) where {T<:Enum} = isless(basetype(T)(x), basetype(T)(y))

Base.Symbol(x::Enum) = namemap(typeof(x))[Integer(x)]::Symbol

Base.print(io::IO, x::Enum) = print(io, Symbol(x))
function _symbol(x::Enum)
names = namemap(typeof(x))
x = Integer(x)
get(() -> Symbol("<invalid #$x>"), names, x)::Symbol
end

Base.print(io::IO, x::Enum) = print(io, _symbol(x))

function Base.show(io::IO, x::Enum)
sym = Symbol(x)
sym = _symbol(x)
if !(get(io, :compact, false)::Bool)
from = get(io, :module, Main)
def = typeof(x).name.module
Expand Down
7 changes: 7 additions & 0 deletions test/enums.jl
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ let io = IOBuffer()
@test String(take!(io)) == sprint(print, Fruit)
end

# Test printing of invalid enums
@test repr("text/plain", reinterpret(Fruit, Int32(11))) == "<invalid #11>::Fruit = 11"
@test repr("text/plain", reinterpret(Fruit, Int32(-5))) == "<invalid #-5>::Fruit = -5"

@enum LogLevel DEBUG INFO WARN ERROR CRITICAL
@test DEBUG < CRITICAL

Expand All @@ -160,6 +164,9 @@ end
@test repr("text/plain", sevn) == "$(string(sevn))::UI8 = 0x07"
@test repr("text/plain", fiftn) == "$(string(fiftn))::UI8 = 0xf0"

@test repr("text/plain", reinterpret(UI8, 0x01)) == "<invalid #1>::UI8 = 0x01"
@test repr("text/plain", reinterpret(UI8, 0xff)) == "<invalid #255>::UI8 = 0xff"

# test block form
@enum BritishFood begin
blackpudding = 1
Expand Down

0 comments on commit 388aa28

Please sign in to comment.