Skip to content

Commit cac1093

Browse files
authored
improve show method for Channel (#35790)
1 parent d88a897 commit cac1093

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

base/channels.jl

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ julia> chnl = Channel{Char}(1, spawn=true) do ch
118118
put!(ch, c)
119119
end
120120
end
121-
Channel{Char}(sz_max:1,sz_curr:1)
121+
Channel{Char}(1) (1 item available)
122122
123123
julia> String(collect(chnl))
124124
"hello world"
@@ -440,7 +440,24 @@ end
440440

441441
eltype(::Type{Channel{T}}) where {T} = T
442442

443-
show(io::IO, c::Channel) = print(io, "$(typeof(c))(sz_max:$(c.sz_max),sz_curr:$(n_avail(c)))")
443+
show(io::IO, c::Channel) = print(io, typeof(c), "(", c.sz_max, ")")
444+
445+
function show(io::IO, ::MIME"text/plain", c::Channel)
446+
show(io, c)
447+
if !get(io, :compact, false)
448+
if !isopen(c)
449+
print(io, " (closed)")
450+
else
451+
n = n_avail(c)
452+
if n == 0
453+
print(io, " (empty)")
454+
else
455+
s = n == 1 ? "" : "s"
456+
print(io, " (", n_avail(c), " item$s available)")
457+
end
458+
end
459+
end
460+
end
444461

445462
function iterate(c::Channel, state=nothing)
446463
try

test/channels.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,3 +499,15 @@ let t = @async nothing
499499
wait(t)
500500
@test_throws ErrorException("schedule: Task not runnable") schedule(t, nothing)
501501
end
502+
503+
# Channel `show`
504+
let c = Channel(3)
505+
@test repr(c) == "Channel{Any}(3)"
506+
@test repr(MIME("text/plain"), c) == "Channel{Any}(3) (empty)"
507+
put!(c, 0)
508+
@test repr(MIME("text/plain"), c) == "Channel{Any}(3) (1 item available)"
509+
put!(c, 1)
510+
@test repr(MIME("text/plain"), c) == "Channel{Any}(3) (2 items available)"
511+
close(c)
512+
@test repr(MIME("text/plain"), c) == "Channel{Any}(3) (closed)"
513+
end

0 commit comments

Comments
 (0)