From 388aa285d9c52131a94290789c9a114743574082 Mon Sep 17 00:00:00 2001 From: Jakob Nybo Nissen Date: Mon, 19 Jul 2021 13:28:03 +0200 Subject: [PATCH] Do not error when showing invalid enums (#40042) (#41596) (cherry picked from commit 02807b279a5e6d5acaeb7095e4c0527e2a5c190e) --- base/Enums.jl | 10 ++++++++-- test/enums.jl | 7 +++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/base/Enums.jl b/base/Enums.jl index 06860402fbcb1..7b5e9587d5f6c 100644 --- a/base/Enums.jl +++ b/base/Enums.jl @@ -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(""), 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 diff --git a/test/enums.jl b/test/enums.jl index d3c585678c572..5a83e1b4dfa42 100644 --- a/test/enums.jl +++ b/test/enums.jl @@ -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))) == "::Fruit = 11" +@test repr("text/plain", reinterpret(Fruit, Int32(-5))) == "::Fruit = -5" + @enum LogLevel DEBUG INFO WARN ERROR CRITICAL @test DEBUG < CRITICAL @@ -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)) == "::UI8 = 0x01" +@test repr("text/plain", reinterpret(UI8, 0xff)) == "::UI8 = 0xff" + # test block form @enum BritishFood begin blackpudding = 1