Skip to content

Commit 243adbd

Browse files
authored
Merge pull request #161 from mame/zlib-deflate-dup-buffer
Do not share the output buffer in Zlib::Deflate#initialize_copy
2 parents b287b45 + 1ce3555 commit 243adbd

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎ext/zlib/zlib.c‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1801,7 +1801,13 @@ rb_deflate_init_copy(VALUE self, VALUE orig)
18011801
raise_zlib_error(err, 0);
18021802
}
18031803
z1->input = NIL_P(z2->input) ? Qnil : rb_str_dup(z2->input);
1804-
z1->buf = NIL_P(z2->buf) ? Qnil : rb_str_dup(z2->buf);
1804+
z1->buf = Qnil;
1805+
if (!NIL_P(z2->buf)) {
1806+
/* next_out was copied from orig; point it into our own buffer */
1807+
z1->buf = rb_obj_hide(rb_str_new(RSTRING_PTR(z2->buf), RSTRING_LEN(z2->buf)));
1808+
z1->stream.next_out = (Bytef*)RSTRING_END(z1->buf);
1809+
z1->stream.avail_out = 0;
1810+
}
18051811
z1->flags = z2->flags;
18061812

18071813
return self;

‎test/zlib/test_zlib.rb‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,17 @@ def test_dup
3939
assert_equal("foobaz", Zlib::Inflate.inflate(s2))
4040
end
4141

42+
def test_dup_with_pending_output
43+
s = Random.new(0).bytes(50_000)
44+
z1 = Zlib::Deflate.new
45+
z1 << s
46+
z2 = z1.dup
47+
z1 << "bar"
48+
z2 << "baz"
49+
assert_equal(s + "bar", Zlib::Inflate.inflate(z1.finish))
50+
assert_equal(s + "baz", Zlib::Inflate.inflate(z2.finish))
51+
end
52+
4253
def test_deflate
4354
s = Zlib::Deflate.deflate("foo")
4455
assert_equal("foo", Zlib::Inflate.inflate(s))

0 commit comments

Comments
 (0)