Skip to content

Commit 4fb92c7

Browse files
authored
Merge pull request #188 from ruby/claude/elegant-colden-8735b1
Keep the input when the inflate block exits on pending output
2 parents 47c0462 + 001e625 commit 4fb92c7

2 files changed

Lines changed: 34 additions & 6 deletions

File tree

‎ext/zlib/zlib.c‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1186,12 +1186,19 @@ zstream_run_try(VALUE value_arg)
11861186
z->stream.avail_out = 0;
11871187
}
11881188

1189-
if (NIL_P(z->input) && len == 0) {
1189+
zstream_append_input(z, src, len);
1190+
1191+
/* expanding the buffer may yield the pending output, and the block
1192+
may exit there, so keep the input in `z->input' until then. */
1193+
if (z->stream.avail_out == 0) {
1194+
zstream_expand_buffer(z);
1195+
}
1196+
1197+
if (NIL_P(z->input)) {
11901198
z->stream.next_in = (Bytef*)"";
11911199
z->stream.avail_in = 0;
11921200
}
11931201
else {
1194-
zstream_append_input(z, src, len);
11951202
/* keep reference to `z->input' so as not to be garbage collected
11961203
after zstream_reset_input() and prevent `z->stream.next_in'
11971204
from dangling. */
@@ -1202,10 +1209,6 @@ zstream_run_try(VALUE value_arg)
12021209
args->rest_in = RSTRING_LEN(old_input) - z->stream.avail_in;
12031210
}
12041211

1205-
if (z->stream.avail_out == 0) {
1206-
zstream_expand_buffer(z);
1207-
}
1208-
12091212
loop:
12101213
err = zstream_run_func(args);
12111214

‎test/zlib/test_zlib.rb‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -738,6 +738,31 @@ def test_inflate_chunked_break
738738
assert_equal 100_000 - chunks.first.length, out.length
739739
end
740740

741+
def test_inflate_chunked_break_with_pending_output
742+
# The first call leaves 16 KiB pending, which the second call yields
743+
# before inflating its input.
744+
src = "a" * 16_384 + "b" * 16_384
745+
deflated = Zlib::Deflate.deflate(src, Zlib::NO_COMPRESSION)
746+
# zlib header, stored block header, and the first 16 KiB of data
747+
head = deflated.byteslice(0, 2 + 5 + 16_384)
748+
rest = deflated.byteslice(head.bytesize..)
749+
750+
[false, true].product([:break, :raise]) do |use_buffer, exit_by|
751+
opts = use_buffer ? {buffer: String.new} : {}
752+
z = Zlib::Inflate.new
753+
inflated = "".dup
754+
z.inflate(head, **opts) { |chunk| inflated << chunk }
755+
if exit_by == :break
756+
z.inflate(rest, **opts) { |chunk| inflated << chunk; break }
757+
else
758+
assert_raise(RuntimeError) { z.inflate(rest, **opts) { |chunk| inflated << chunk; raise } }
759+
end
760+
assert_equal 16_384, inflated.bytesize
761+
z.inflate(nil, **opts) { |chunk| inflated << chunk }
762+
assert_equal src, inflated, "buffer: #{use_buffer}, #{exit_by}"
763+
end
764+
end
765+
741766
def test_inflate_dictionary
742767
dictionary = "foo"
743768

0 commit comments

Comments
 (0)