Skip to content

Commit

Permalink
Merge pull request #49 from miyucy/respondtoread
Browse files Browse the repository at this point in the history
Made Brotli.inflate accept objects with a #read method, allowing for more flexible input, such as IO-like objects.
  • Loading branch information
miyucy authored Jul 28, 2024
2 parents ea0e058 + c542532 commit f7f6522
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
7 changes: 7 additions & 0 deletions ext/brotli/brotli.c
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,18 @@ brotli_inflate_no_gvl(void *arg)
return arg;
}

static ID id_read;

static VALUE
brotli_inflate(VALUE self, VALUE str)
{
VALUE value = Qnil;
brotli_inflate_args_t args;

if (rb_respond_to(str, id_read)) {
str = rb_funcall(str, id_read, 0, 0);
}

StringValue(str);

args.str = (uint8_t*)RSTRING_PTR(str);
Expand Down Expand Up @@ -472,6 +478,7 @@ Init_brotli(void)
rb_define_singleton_method(rb_mBrotli, "deflate", RUBY_METHOD_FUNC(brotli_deflate), -1);
rb_define_singleton_method(rb_mBrotli, "inflate", RUBY_METHOD_FUNC(brotli_inflate), 1);
rb_define_singleton_method(rb_mBrotli, "version", RUBY_METHOD_FUNC(brotli_version), 0);
id_read = rb_intern("read");
// Brotli::Writer
id_write = rb_intern("write");
id_flush = rb_intern("flush");
Expand Down
10 changes: 10 additions & 0 deletions test/brotli_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ def testdata2
assert_equal testdata, Brotli.inflate(testdata2)
end

test "works with StringIO" do
testdata3 = StringIO.new testdata2
assert_equal testdata, Brotli.inflate(testdata3)
end

test "works with File" do
f = File.open(File.expand_path(File.join("..", "vendor", "brotli", "tests", "testdata", "alice29.txt.compressed"), __dir__))
assert_equal testdata, Brotli.inflate(f)
end

test "raise error when pass insufficient data" do
assert_raise Brotli::Error do
Brotli.inflate(testdata2[0, 64])
Expand Down
1 change: 1 addition & 0 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
require "test-unit"
require "test/unit/rr"
require "rantly/testunit_extensions"
require "stringio"

0 comments on commit f7f6522

Please sign in to comment.