Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Zlib.gzip and Zlib.gunzip #2529

Merged
merged 5 commits into from
Jan 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions lib/zlib.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,28 @@ def self.inflate(...)
Inflate.inflate(...)
end

def self.gunzip(input)
# windowBits can also be greater than 15 for optional gzip encoding. Add
# 16 to windowBits to write a simple gzip header and trailer around the
# compressed data instead of a zlib wrapper.
zstream = Zlib::Inflate.new(MAX_WBITS | 16)
zstream << input
zstream.finish.tap do
zstream.close
end
end

def self.gzip(src, level: nil, strategy: nil)
# windowBits can also be greater than 15 for optional gzip encoding. Add
# 16 to windowBits to write a simple gzip header and trailer around the
# compressed data instead of a zlib wrapper.
zstream = Zlib::Deflate.new(level || DEFAULT_COMPRESSION, MAX_WBITS | 16, DEF_MEM_LEVEL, strategy || DEFAULT_STRATEGY)
zstream << src
zstream.finish.tap do
zstream.close
end
end

class ZStream
__bind_method__ :adler, :Zlib_ZStream_adler, 0
__bind_method__ :avail_in, :Zlib_ZStream_avail_in, 0
Expand Down
14 changes: 14 additions & 0 deletions spec/library/zlib/gunzip_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
require_relative '../../spec_helper'
require 'zlib'

describe "Zlib.gunzip" do
before :each do
@data = '12345abcde'
@zip = [31, 139, 8, 0, 44, 220, 209, 71, 0, 3, 51, 52, 50, 54, 49, 77,
76, 74, 78, 73, 5, 0, 157, 5, 0, 36, 10, 0, 0, 0].pack('C*')
end

it "decodes the given gzipped string" do
Zlib.gunzip(@zip).should == @data
end
end
15 changes: 15 additions & 0 deletions spec/library/zlib/gzip_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
require_relative '../../spec_helper'
require 'zlib'

describe "Zlib.gzip" do
before :each do
@data = '12345abcde'
@zip = [31, 139, 8, 0, 44, 220, 209, 71, 0, 3, 51, 52, 50, 54, 49, 77,
76, 74, 78, 73, 5, 0, 157, 5, 0, 36, 10, 0, 0, 0].pack('C*')
end

it "gzips the given string" do
# skip gzip header for now
Zlib.gzip(@data)[10..-1].should == @zip[10..-1]
end
end
Loading