Skip to content

Commit 07ef5f4

Browse files
committed
support open do ... end syntax
1 parent 57a1f80 commit 07ef5f4

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

docs/src/index.md

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,26 +51,46 @@ The following snippet is an example of using CodecZlib.jl, which exports
5151
`TranscodingStream{GzipDecompression,S} where S<:IO`:
5252
```julia
5353
using CodecZlib
54-
stream = GzipDecompressionStream(open("data.gzip"))
54+
stream = GzipDecompressionStream(open("data.txt.gz"))
5555
for line in eachline(stream)
5656
# do something...
5757
end
5858
close(stream)
5959
```
6060

61+
Note that the last `close` call will close the file as well. Alternatively,
62+
`open(<stream type>, <filepath>) do ... end` syntax will close the file at the
63+
end:
64+
```julia
65+
using CodecZlib
66+
open(GzipDecompressionStream, "data.txt.gz") do stream
67+
for line in eachline(stream)
68+
# do something...
69+
end
70+
end
71+
```
72+
6173
### Save a data matrix with Zstd compression
6274

6375
Writing compressed data is easy. One thing you need to keep in mind is to call
6476
`close` after writing data; otherwise, the output file will be incomplete:
6577
```julia
6678
using CodecZstd
67-
mat = randn(100, 100).^2
68-
file = open("data.mat.zst", "w")
69-
stream = ZstdCompressionStream(file)
79+
mat = randn(100, 100)
80+
stream = ZstdCompressionStream(open("data.mat.zst", "w"))
7081
writedlm(stream, mat)
7182
close(stream)
7283
```
7384

85+
Of course, `open(<stream type>, ...) do ... end` works well:
86+
```julia
87+
using CodecZstd
88+
mat = randn(100, 100)
89+
open(ZstdCompressionStream, "data.mat.zst", "w") do stream
90+
writedlm(stream, mat)
91+
end
92+
```
93+
7494
### Explicitly finish transcoding by writing `TOKEN_END`
7595

7696
When writing data, the end of a data stream is indicated by calling `close`,

src/stream.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,17 @@ end
7575
# Base IO Functions
7676
# -----------------
7777

78+
function Base.open(f::Function, ::Type{T}, args...) where T<:TranscodingStream
79+
try
80+
stream = T(open(args...))
81+
f(stream)
82+
catch
83+
rethrow()
84+
finally
85+
close(stream)
86+
end
87+
end
88+
7889
function Base.isopen(stream::TranscodingStream)
7990
return stream.state.state != :close
8091
end

0 commit comments

Comments
 (0)