From fdf39963490cf2cf95b30d91bb9b35964c2c2350 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Wed, 22 Dec 2021 15:33:12 +0900 Subject: Empty and return the buffer if zero size is given [Bug #18421] In `IO#readpartial` and `IO#read_nonblock`, as well as `IO#read`. --- io.c | 8 ++++++-- test/ruby/test_io.rb | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/io.c b/io.c index dc883f36b4..8ac29083ae 100644 --- a/io.c +++ b/io.c @@ -3161,8 +3161,10 @@ io_getpartial(int argc, VALUE *argv, VALUE io, int no_exception, int nonblock) GetOpenFile(io, fptr); rb_io_check_byte_readable(fptr); - if (len == 0) + if (len == 0) { + io_set_read_length(str, 0, shrinkable); return str; + } if (!nonblock) READ_CHECK(fptr); @@ -3305,8 +3307,10 @@ io_read_nonblock(rb_execution_context_t *ec, VALUE io, VALUE length, VALUE str, GetOpenFile(io, fptr); rb_io_check_byte_readable(fptr); - if (len == 0) + if (len == 0) { + io_set_read_length(str, 0, shrinkable); return str; + } n = read_buffered_data(RSTRING_PTR(str), len, fptr); if (n <= 0) { diff --git a/test/ruby/test_io.rb b/test/ruby/test_io.rb index b46777df5f..4f54052d3b 100644 --- a/test/ruby/test_io.rb +++ b/test/ruby/test_io.rb @@ -1494,6 +1494,13 @@ class TestIO < Test::Unit::TestCase end) end + def test_readpartial_zero_size + File.open(IO::NULL) do |r| + assert_empty(r.readpartial(0, s = "01234567")) + assert_empty(s) + end + end + def test_readpartial_buffer_error with_pipe do |r, w| s = "" @@ -1539,6 +1546,13 @@ class TestIO < Test::Unit::TestCase end) end + def test_read_zero_size + File.open(IO::NULL) do |r| + assert_empty(r.read(0, s = "01234567")) + assert_empty(s) + end + end + def test_read_buffer_error with_pipe do |r, w| s = "" @@ -1576,6 +1590,13 @@ class TestIO < Test::Unit::TestCase } end + def test_read_nonblock_zero_size + File.open(IO::NULL) do |r| + assert_empty(r.read_nonblock(0, s = "01234567")) + assert_empty(s) + end + end + def test_write_nonblock_simple_no_exceptions pipe(proc do |w| w.write_nonblock('1', exception: false) -- cgit v1.2.3