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

This commit is contained in:
Yukihiro "Matz" Matsumoto
2022-12-30 09:34:45 +09:00
parent d0659b089f
commit af59e30710
2 changed files with 13 additions and 5 deletions
+1 -5
View File
@@ -100,12 +100,8 @@ class IO
return true
end
end
alias_method :eof, :eof?
def pos
raise IOError if closed?
sysseek(0, SEEK_CUR) - @buf.bytesize
end
alias_method :eof, :eof?
alias_method :tell, :pos
def pos=(i)
+12
View File
@@ -1130,6 +1130,17 @@ io_closed(mrb_state *mrb, mrb_value io)
return mrb_true_value();
}
static mrb_value
io_pos(mrb_state *mrb, mrb_value io)
{
struct mrb_io *fptr = io_get_open_fptr(mrb, io);
off_t pos = lseek(fptr->fd, 0, SEEK_CUR);
if (pos == -1) mrb_sys_fail(mrb, 0);
mrb_value buf = mrb_iv_get(mrb, io, MRB_IVSYM(buf));
return mrb_int_value(mrb, pos - RSTRING_LEN(buf));
}
static mrb_value
io_pid(mrb_state *mrb, mrb_value io)
{
@@ -1636,6 +1647,7 @@ mrb_init_io(mrb_state *mrb)
mrb_define_method(mrb, io, "close_on_exec=", io_set_close_on_exec, MRB_ARGS_REQ(1));
mrb_define_method(mrb, io, "close_on_exec?", io_close_on_exec_p, MRB_ARGS_NONE());
mrb_define_method(mrb, io, "closed?", io_closed, MRB_ARGS_NONE()); /* 15.2.20.5.2 */
mrb_define_method(mrb, io, "pos", io_pos, MRB_ARGS_NONE());
mrb_define_method(mrb, io, "pid", io_pid, MRB_ARGS_NONE());
mrb_define_method(mrb, io, "fileno", io_fileno, MRB_ARGS_NONE());
mrb_define_method(mrb, io, "write", io_write, MRB_ARGS_ANY()); /* 15.2.20.5.20 */