Skip to content

Commit 02807b2

Browse files
authored
Do not error when showing invalid enums (#40042) (#41596)
1 parent 0dbd3f7 commit 02807b2

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

base/Enums.jl

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,16 @@ Base.isless(x::T, y::T) where {T<:Enum} = isless(basetype(T)(x), basetype(T)(y))
2525

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

28-
Base.print(io::IO, x::Enum) = print(io, Symbol(x))
28+
function _symbol(x::Enum)
29+
names = namemap(typeof(x))
30+
x = Integer(x)
31+
get(() -> Symbol("<invalid #$x>"), names, x)::Symbol
32+
end
33+
34+
Base.print(io::IO, x::Enum) = print(io, _symbol(x))
2935

3036
function Base.show(io::IO, x::Enum)
31-
sym = Symbol(x)
37+
sym = _symbol(x)
3238
if !(get(io, :compact, false)::Bool)
3339
from = get(io, :module, Main)
3440
def = typeof(x).name.module

test/enums.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,10 @@ let io = IOBuffer()
143143
@test String(take!(io)) == sprint(print, Fruit)
144144
end
145145

146+
# Test printing of invalid enums
147+
@test repr("text/plain", reinterpret(Fruit, Int32(11))) == "<invalid #11>::Fruit = 11"
148+
@test repr("text/plain", reinterpret(Fruit, Int32(-5))) == "<invalid #-5>::Fruit = -5"
149+
146150
@enum LogLevel DEBUG INFO WARN ERROR CRITICAL
147151
@test DEBUG < CRITICAL
148152

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

167+
@test repr("text/plain", reinterpret(UI8, 0x01)) == "<invalid #1>::UI8 = 0x01"
168+
@test repr("text/plain", reinterpret(UI8, 0xff)) == "<invalid #255>::UI8 = 0xff"
169+
163170
# test block form
164171
@enum BritishFood begin
165172
blackpudding = 1

0 commit comments

Comments
 (0)