Skip to content

Commit

Permalink
Merge pull request BioJulia#12 from samoconnor/patch-1
Browse files Browse the repository at this point in the history
Convenience functions for dealing with .gz files
  • Loading branch information
Ben J. Ward committed Jan 21, 2016
2 parents f3da0ac + 35f3ea2 commit ba42de7
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
19 changes: 19 additions & 0 deletions src/Libz.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ using BufferedStreams

export ZlibInflateInputStream, ZlibDeflateInputStream,
ZlibInflateOutputStream, ZlibDeflateOutputStream,
gzopen, writegz, readgz, readgzstring,
adler32, crc32


Expand All @@ -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


10 changes: 10 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Binary file added test/test.gz
Binary file not shown.

0 comments on commit ba42de7

Please sign in to comment.