diff --git a/README.md b/README.md index 94d2b0b..ca23a0b 100644 --- a/README.md +++ b/README.md @@ -39,11 +39,13 @@ for line in eachline(open("data.txt.gz") |> ZlibInflateInputStream) end # write compressed data to a file -stream = open("data.txt.gz", "w") |> ZlibDeflateOutputStream +io = open("data.txt.gz", "w") +stream = ZlibDeflateOutputStream(io) for c in rand(UInt8, 10000) write(stream, c) end close(stream) +close(io) # pointlessly compress and decompress some data readbytes(rand(UInt8, 10000) |> ZlibDeflateInputStream |> ZlibInflateInputStream) diff --git a/src/Libz.jl b/src/Libz.jl index 5f0026a..de22e12 100644 --- a/src/Libz.jl +++ b/src/Libz.jl @@ -6,6 +6,7 @@ using BufferedStreams export ZlibInflateInputStream, ZlibDeflateInputStream, ZlibInflateOutputStream, ZlibDeflateOutputStream, + gzopen, writegz, readgz, readgzstring, adler32, crc32 @@ -29,6 +30,24 @@ end const decompress = inflate +function gzopen(f::Function, filename::AbstractString, mode) + @assert mode == "w" + open(filename, mode) do io + zio = ZlibDeflateOutputStream(io) + try f(zio) + finally close(zio) + end + end +end + +function gzopen(f::Function, filename::AbstractString) + open(io->f(ZlibInflateInputStream(io)), filename) +end + +writegz(filename::AbstractString, data) = gzopen(io->write(io, data), filename, "w") +readgz(filename::AbstractString) = gzopen(readbytes, filename) +readgzstring(filename::AbstractString) = gzopen(readall, filename) + end # module Libz diff --git a/test/runtests.jl b/test/runtests.jl index d3d151e..a8463b3 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -43,3 +43,13 @@ facts("Checksums") do @fact adler32(BufferedInputStream(IOBuffer(data), 1024)) --> a32 end + +facts("Files") do + + testgz = joinpath(Pkg.dir("Libz"), "test/test.gz") + @fact crc32(readgz(testgz)) --> 0x2b082899 + + f = tempname() * ".gz" + writegz(f, "Hello World!") + @fact readgzstring(f) --> "Hello World!" +end diff --git a/test/test.gz b/test/test.gz new file mode 100644 index 0000000..88bf594 Binary files /dev/null and b/test/test.gz differ