From f087f2c74c99ec5fed04896d3dc91ff76c2b16b8 Mon Sep 17 00:00:00 2001 From: Jean byroot Boussier Date: Thu, 5 Oct 2023 09:43:59 +0200 Subject: [PATCH] [ruby/stringio] StringIO#pread: handle 0 length like IO#pread (https://github.com/ruby/stringio/pull/67) Fix: https://github.com/ruby/stringio/issues/66 If length is 0, IO#pread don't even try to read the IO, it simply return the buffer untouched if there is one or a new empty buffer otherwise. It also doesn't validate the offset when length is 0. cc @jdelStrother @kou https://github.com/ruby/stringio/commit/37e9279337 Co-authored-by: Jean Boussier --- ext/stringio/stringio.c | 7 +++++++ test/stringio/test_stringio.rb | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index 1feb9231db..d5753a97a0 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -1602,6 +1602,13 @@ strio_pread(int argc, VALUE *argv, VALUE self) rb_raise(rb_eArgError, "negative string size (or size too big): %" PRIsVALUE, rb_len); } + if (len == 0) { + if (NIL_P(rb_buf)) { + return rb_str_new("", 0); + } + return rb_buf; + } + if (offset < 0) { rb_syserr_fail_str(EINVAL, rb_sprintf("pread: Invalid offset argument: %" PRIsVALUE, rb_offset)); } diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index d2d96c5719..cb82841231 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -750,6 +750,13 @@ class TestStringIO < Test::Unit::TestCase assert_raise(EOFError) { f.pread(1, 5) } assert_raise(ArgumentError) { f.pread(-1, 0) } assert_raise(Errno::EINVAL) { f.pread(3, -1) } + + assert_equal "".b, StringIO.new("").pread(0, 0) + assert_equal "".b, StringIO.new("").pread(0, -10) + + buf = "stale".b + assert_equal "stale".b, StringIO.new("").pread(0, 0, buf) + assert_equal "stale".b, buf end def test_size