Merge pull request #6118 from dearblue/io.read

Fixed `IO#read` with `buf`.
This commit is contained in:
Yukihiro "Matz" Matsumoto
2023-12-19 08:00:42 +09:00
committed by GitHub
2 changed files with 36 additions and 1 deletions
+12 -1
View File
@@ -1702,7 +1702,14 @@ io_read(mrb_state *mrb, mrb_value io)
mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative length %d given", length);
}
if (length == 0) {
return mrb_str_new(mrb, NULL, 0);
if (mrb_nil_p(outbuf)) {
outbuf = mrb_str_new(mrb, NULL, 0);
}
else {
mrb_str_modify(mrb, mrb_str_ptr(outbuf));
RSTR_SET_LEN(mrb_str_ptr(outbuf), 0);
}
return outbuf;
}
}
}
@@ -1710,6 +1717,10 @@ io_read(mrb_state *mrb, mrb_value io)
if (mrb_nil_p(outbuf)) {
outbuf = mrb_str_new_capa(mrb, MRB_IO_BUF_SIZE);
}
else {
mrb_str_modify(mrb, mrb_str_ptr(outbuf));
RSTR_SET_LEN(mrb_str_ptr(outbuf), 0);
}
if (!length_given) { /* read as much as possible */
return io_read_all(mrb, fptr, outbuf);
}
+24
View File
@@ -150,6 +150,30 @@ assert "IO#read(n) with n > IO::BUF_SIZE" do
end
end
assert "IO#read(n, buf)" do
IO.open(IO.sysopen($mrbtest_io_rfname)) do |io|
buf = "12345"
assert_same buf, io.read(0, buf)
assert_equal "", buf
buf = "12345"
assert_same buf, io.read(5, buf)
assert_equal "mruby", buf
buf = "12345"
assert_same buf, io.read(nil, buf)
assert_equal " io test\n", buf
buf = "12345"
assert_nil io.read(99, buf)
assert_equal "", buf
buf = "12345"
assert_same buf, io.read(0, buf)
assert_equal "", buf
end
end
assert('IO#readchar', '15.2.20.5.15') do
# almost same as IO#getc
IO.open(IO.sysopen($mrbtest_io_rfname)) do |io|