Skip to content

Commit 37e9279

Browse files
casperisfinebyroot
andauthored
StringIO#pread: handle 0 length like IO#pread (#67)
Fix: #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 Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
1 parent e3ea087 commit 37e9279

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

ext/stringio/stringio.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1602,6 +1602,13 @@ strio_pread(int argc, VALUE *argv, VALUE self)
16021602
rb_raise(rb_eArgError, "negative string size (or size too big): %" PRIsVALUE, rb_len);
16031603
}
16041604

1605+
if (len == 0) {
1606+
if (NIL_P(rb_buf)) {
1607+
return rb_str_new("", 0);
1608+
}
1609+
return rb_buf;
1610+
}
1611+
16051612
if (offset < 0) {
16061613
rb_syserr_fail_str(EINVAL, rb_sprintf("pread: Invalid offset argument: %" PRIsVALUE, rb_offset));
16071614
}

test/stringio/test_stringio.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,13 @@ def test_pread
750750
assert_raise(EOFError) { f.pread(1, 5) }
751751
assert_raise(ArgumentError) { f.pread(-1, 0) }
752752
assert_raise(Errno::EINVAL) { f.pread(3, -1) }
753+
754+
assert_equal "".b, StringIO.new("").pread(0, 0)
755+
assert_equal "".b, StringIO.new("").pread(0, -10)
756+
757+
buf = "stale".b
758+
assert_equal "stale".b, StringIO.new("").pread(0, 0, buf)
759+
assert_equal "stale".b, buf
753760
end
754761

755762
def test_size

0 commit comments

Comments
 (0)