Skip to content

Commit

Permalink
Merge pull request #1205 from herwinw/io_read_0_bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
seven1m authored Sep 4, 2023
2 parents 486221c + a0d9a00 commit 3148a66
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
4 changes: 1 addition & 3 deletions spec/core/io/read_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -295,9 +295,7 @@
end

it "consumes zero bytes when reading zero bytes" do
NATFIXME 'Empty string when reading zero bytes', exception: SpecFailedException do
@io.read(0).should == ''
end
@io.read(0).should == ''
@io.pos.should == 0

NATFIXME 'Implement IO#getc', exception: NoMethodError, message: "undefined method `getc'" do
Expand Down
20 changes: 13 additions & 7 deletions src/io_object.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -178,31 +178,37 @@ Value IoObject::write_file(Env *env, Value filename, Value string) {

Value IoObject::read(Env *env, Value count_value) const {
raise_if_closed(env);
size_t bytes_read;
ssize_t bytes_read;
if (count_value && !count_value->is_nil()) {
count_value->assert_type(env, Object::Type::Integer, "Integer");
int count = count_value->as_integer()->to_nat_int_t();
if (count < 0)
env->raise("ArgumentError", "negative length {} given", count);
char *buf = new char[count + 1];
auto buf_cleanup = Defer([&]() { delete[] buf; });
bytes_read = ::read(m_fileno, buf, count);
if (bytes_read == 0) {
delete[] buf;
if (bytes_read < 0) {
env->raise_errno();
} else if (bytes_read == 0) {
if (count == 0)
return new StringObject {};
return NilObject::the();
} else {
Value result = new StringObject { buf, bytes_read };
delete[] buf;
Value result = new StringObject { buf, static_cast<size_t>(bytes_read) };
return result;
}
}
char buf[NAT_READ_BYTES + 1];
bytes_read = ::read(m_fileno, buf, NAT_READ_BYTES);
if (bytes_read == 0) {
if (bytes_read < 0) {
env->raise_errno();
} else if (bytes_read == 0) {
return new StringObject { "" };
}
StringObject *str = new StringObject { buf, bytes_read };
StringObject *str = new StringObject { buf, static_cast<size_t>(bytes_read) };
while (1) {
bytes_read = ::read(m_fileno, buf, NAT_READ_BYTES);
if (bytes_read < 0) env->raise_errno();
if (bytes_read == 0) break;
buf[bytes_read] = 0;
str->append(buf, bytes_read);
Expand Down

0 comments on commit 3148a66

Please sign in to comment.