Skip to content

Commit c1c2973

Browse files
stevengjtkelman
authored andcommitted
display something useful for text/plain output of invalid String (#18296)
(cherry picked from commit 2b2894c)
1 parent 8d4ef37 commit c1c2973

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

base/replutil.jl

+10
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,16 @@ end
153153
show(io::IO, ::MIME"text/plain", X::AbstractArray) = showarray(io, X, false)
154154
show(io::IO, ::MIME"text/plain", r::Range) = show(io, r) # always use the compact form for printing ranges
155155

156+
# display something useful even for strings containing arbitrary
157+
# (non-UTF8) binary data:
158+
function show(io::IO, ::MIME"text/plain", s::String)
159+
if isvalid(s)
160+
show(io, s)
161+
else
162+
println(io, sizeof(s), "-byte String of invalid UTF-8 data:")
163+
showarray(io, s.data, false; header=false)
164+
end
165+
end
156166

157167
# showing exception objects as descriptive error messages
158168

test/show.jl

+3
Original file line numberDiff line numberDiff line change
@@ -572,3 +572,6 @@ end
572572
@test repr(:(f.(X,Y))) == ":(f.(X,Y))"
573573
@test repr(:(f.(X))) == ":(f.(X))"
574574
@test repr(:(f.())) == ":(f.())"
575+
576+
# Test that REPL/mime display of invalid UTF-8 data doesn't throw an exception:
577+
@test isa(stringmime("text/plain", String(UInt8[0x00:0xff;])), String)

0 commit comments

Comments
 (0)