mruby-io/io.c: implement IO#getbyte in C

In addition, reimplement `IO#readbyte` using `IO#getbyte`.
This commit is contained in:
Yukihiro "Matz" Matsumoto
2023-01-05 19:18:14 +09:00
parent eec546a9cf
commit b7147bbd8d
2 changed files with 16 additions and 8 deletions
-6
View File
@@ -115,12 +115,6 @@ class IO
end
end
def getbyte
readbyte
rescue EOFError
nil
end
# 15.2.20.5.3
def each(&block)
return to_enum unless block
+16 -2
View File
@@ -1830,9 +1830,12 @@ io_readchar(mrb_state *mrb, mrb_value io)
}
static mrb_value
io_readbyte(mrb_state *mrb, mrb_value io)
io_getbyte(mrb_state *mrb, mrb_value io)
{
io_read_buf(mrb, io);
io_read_buf_noraise(mrb, io);
if (io_get_read_fptr(mrb, io)->eof) {
return mrb_nil_value();
}
mrb_value buf = io_buf(mrb, io);
struct RString *b = RSTRING(buf);
unsigned char c = RSTR_PTR(b)[0];
@@ -1840,6 +1843,16 @@ io_readbyte(mrb_state *mrb, mrb_value io)
return mrb_int_value(mrb, (mrb_int)c);
}
static mrb_value
io_readbyte(mrb_state *mrb, mrb_value io)
{
mrb_value result = io_getbyte(mrb, io);
if (mrb_nil_p(result)) {
eof_error(mrb);
}
return result;
}
static mrb_value
io_flush(mrb_state *mrb, mrb_value io)
{
@@ -1892,6 +1905,7 @@ mrb_init_io(mrb_state *mrb)
mrb_define_method(mrb, io, "write", io_write, MRB_ARGS_ANY()); /* 15.2.20.5.20 */
mrb_define_method(mrb, io, "pread", io_pread, MRB_ARGS_ANY()); /* ruby 2.5 feature */
mrb_define_method(mrb, io, "pwrite", io_pwrite, MRB_ARGS_ANY()); /* ruby 2.5 feature */
mrb_define_method(mrb, io, "getbyte", io_getbyte, MRB_ARGS_NONE());
mrb_define_method(mrb, io, "readbyte", io_readbyte, MRB_ARGS_NONE());
mrb_define_const_id(mrb, io, MRB_SYM(SEEK_SET), mrb_fixnum_value(SEEK_SET));