Skip to content

Commit

Permalink
[ruby/stringio] Check if closed in loop
Browse files Browse the repository at this point in the history
  • Loading branch information
nobu committed Mar 8, 2021
1 parent 99f54c0 commit 32a1359
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 9 deletions.
22 changes: 13 additions & 9 deletions ext/stringio/stringio.c
@@ -1,3 +1,4 @@
/* -*- mode: c; indent-tabs-mode: t -*- */
/**********************************************************************
stringio.c -
Expand Down Expand Up @@ -599,6 +600,14 @@ strio_closed_write(VALUE self)
return Qtrue;
}

static struct StringIO *
strio_to_read(VALUE self)
{
struct StringIO *ptr = readable(self);
if (ptr->pos < RSTRING_LEN(ptr->string)) return ptr;
return NULL;
}

/*
* call-seq:
* strio.eof -> true or false
Expand All @@ -610,8 +619,7 @@ strio_closed_write(VALUE self)
static VALUE
strio_eof(VALUE self)
{
struct StringIO *ptr = readable(self);
if (ptr->pos < RSTRING_LEN(ptr->string)) return Qfalse;
if (strio_to_read(self)) return Qfalse;
return Qtrue;
}

Expand Down Expand Up @@ -821,11 +829,11 @@ strio_get_sync(VALUE self)
static VALUE
strio_each_byte(VALUE self)
{
struct StringIO *ptr = readable(self);
struct StringIO *ptr;

RETURN_ENUMERATOR(self, 0, 0);

while (ptr->pos < RSTRING_LEN(ptr->string)) {
while ((ptr = strio_to_read(self)) != NULL) {
char c = RSTRING_PTR(ptr->string)[ptr->pos++];
rb_yield(CHR2FIX(c));
}
Expand Down Expand Up @@ -1064,11 +1072,7 @@ strio_each_codepoint(VALUE self)

ptr = readable(self);
enc = get_enc(ptr);
for (;;) {
if (ptr->pos >= RSTRING_LEN(ptr->string)) {
return self;
}

while ((ptr = strio_to_read(self)) != NULL) {
c = rb_enc_codepoint_len(RSTRING_PTR(ptr->string)+ptr->pos,
RSTRING_END(ptr->string), &n, enc);
ptr->pos += n;
Expand Down
27 changes: 27 additions & 0 deletions test/stringio/test_stringio.rb
Expand Up @@ -446,6 +446,15 @@ def test_each_byte
f.close unless f.closed?
end

def test_each_byte_closed
f = StringIO.new("1234")
assert_equal("1".ord, f.each_byte {|c| f.close; break c })
f = StringIO.new("1234")
assert_raise(IOError) do
f.each_byte { f.close }
end
end

def test_getbyte
f = StringIO.new("1234")
assert_equal("1".ord, f.getbyte)
Expand Down Expand Up @@ -520,11 +529,29 @@ def test_each_char
assert_equal(%w(1 2 3 4), f.each_char.to_a)
end

def test_each_char_closed
f = StringIO.new("1234")
assert_equal("1", f.each_char {|c| f.close; break c })
f = StringIO.new("1234")
assert_raise(IOError) do
f.each_char { f.close }
end
end

def test_each_codepoint
f = StringIO.new("1234")
assert_equal([49, 50, 51, 52], f.each_codepoint.to_a)
end

def test_each_codepoint_closed
f = StringIO.new("1234")
assert_equal("1".ord, f.each_codepoint {|c| f.close; break c })
f = StringIO.new("1234")
assert_raise(IOError) do
f.each_codepoint { f.close }
end
end

def test_each_codepoint_enumerator
io = StringIO.new('你好построить')

Expand Down

0 comments on commit 32a1359

Please sign in to comment.