From 39409a574500f4387bbdc337466261cf18aef374 Mon Sep 17 00:00:00 2001 From: Nathan Zimmerberg <39104088+nhz2@users.noreply.github.com> Date: Sun, 24 Mar 2024 14:46:14 -0400 Subject: [PATCH] Implement `isreadable` and `iswritable` (#185) --- ext/TestExt.jl | 1 + src/stream.jl | 12 +++++++++++- test/codecnoop.jl | 28 ++++++++++++++++++---------- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/ext/TestExt.jl b/ext/TestExt.jl index cac67dd8..71aa1226 100644 --- a/ext/TestExt.jl +++ b/ext/TestExt.jl @@ -90,6 +90,7 @@ function TranscodingStreams.test_chunked_read(Encoder, Decoder) stream = TranscodingStream(Decoder(), buffer, stop_on_end=true) ok &= hash(read(stream)) == hash(chunk) ok &= eof(stream) + ok &= isreadable(stream) close(stream) end Test.@test ok diff --git a/src/stream.jl b/src/stream.jl index d4d8625e..53dcd8e0 100644 --- a/src/stream.jl +++ b/src/stream.jl @@ -103,7 +103,7 @@ julia> using TranscodingStreams julia> file = open(joinpath(dirname(dirname(pathof(TranscodingStreams))), "README.md")); -julia> stream = NoopStream(file); +julia> stream = TranscodingStream(Noop(), file); julia> readline(file) "TranscodingStreams.jl" @@ -182,6 +182,16 @@ function Base.isopen(stream::TranscodingStream) return stream.state.mode != :close && stream.state.mode != :panic end +function Base.isreadable(stream::TranscodingStream)::Bool + mode = stream.state.mode + (mode === :idle || mode === :read || mode === :stop) && isreadable(stream.stream) +end + +function Base.iswritable(stream::TranscodingStream)::Bool + mode = stream.state.mode + (mode === :idle || mode === :write) && iswritable(stream.stream) +end + function Base.close(stream::TranscodingStream) mode = stream.state.mode if mode != :panic diff --git a/test/codecnoop.jl b/test/codecnoop.jl index 1c4a0d77..2bff031e 100644 --- a/test/codecnoop.jl +++ b/test/codecnoop.jl @@ -240,18 +240,26 @@ TranscodingStreams.test_roundtrip_write(NoopStream, NoopStream) TranscodingStreams.test_roundtrip_lines(NoopStream, NoopStream) - # switch write => read - stream = NoopStream(IOBuffer(b"foobar", read=true, write=true)) - @test_throws ArgumentError begin - write(stream, b"xyz") - read(stream, 3) + @testset "switch write => read" begin + stream = NoopStream(IOBuffer(collect(b"foobar"), read=true, write=true)) + @test isreadable(stream) + @test iswritable(stream) + @test_throws ArgumentError begin + write(stream, b"xyz") + read(stream, 3) + end + @test !isreadable(stream) + @test iswritable(stream) end - # switch read => write - stream = NoopStream(IOBuffer(b"foobar", read=true, write=true)) - @test_throws ArgumentError begin - read(stream, 3) - write(stream, b"xyz") + @testset "switch read => write" begin + stream = NoopStream(IOBuffer(collect(b"foobar"), read=true, write=true)) + @test_throws ArgumentError begin + read(stream, 3) + write(stream, b"xyz") + end + @test isreadable(stream) + @test !iswritable(stream) end stream = NoopStream(IOBuffer(""))