Skip to content

Commit 1ce3555

Browse files
mameclaude
andcommitted
Do not share the output buffer in Zlib::Deflate#initialize_copy
The copy shared the buffer string with the original, and its next_out still pointed into the original's buffer. z1 = Zlib::Deflate.new z1 << Random.bytes(50_000) z2 = z1.dup z2 << "foo" #=> can't set length of shared string (RuntimeError) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent ccb2d02 commit 1ce3555

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
@@ -1746,7 +1746,13 @@ rb_deflate_init_copy(VALUE self, VALUE orig)
17461746
raise_zlib_error(err, 0);
17471747
}
17481748
z1->input = NIL_P(z2->input) ? Qnil : rb_str_dup(z2->input);
1749-
z1->buf = NIL_P(z2->buf) ? Qnil : rb_str_dup(z2->buf);
1749+
z1->buf = Qnil;
1750+
if (!NIL_P(z2->buf)) {
1751+
/* next_out was copied from orig; point it into our own buffer */
1752+
z1->buf = rb_obj_hide(rb_str_new(RSTRING_PTR(z2->buf), RSTRING_LEN(z2->buf)));
1753+
z1->stream.next_out = (Bytef*)RSTRING_END(z1->buf);
1754+
z1->stream.avail_out = 0;
1755+
}
17501756
z1->flags = z2->flags;
17511757

17521758
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)