Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion ext/stringio/stringio.c
Original file line number Diff line number Diff line change
Expand Up @@ -1117,7 +1117,13 @@ strio_getc(VALUE self)
return Qnil;
}
p = RSTRING_PTR(str)+pos;
len = rb_enc_mbclen(p, RSTRING_END(str), enc);
len = rb_enc_precise_mbclen(p, RSTRING_END(str), enc);
if (MBCLEN_NEEDMORE_P(len)) {
len = (int)(RSTRING_END(str) - p);
}
else if (MBCLEN_INVALID_P(len)) {
len = 1;
}
ptr->pos += len;
return enc_subseq(str, pos, len, enc);
}
Expand Down
16 changes: 16 additions & 0 deletions test/stringio/test_stringio.rb
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,22 @@ def test_gets_limit_around_truncated_char
end
end

def test_getc_at_truncated_char
# The last character is truncated: only 2 bytes of a 3-byte UTF-8
# character remain. IO#getc returns the remaining bytes of the
# incomplete character together, not one byte at a time.
stringio = StringIO.new("a\xE3\x81".dup.force_encoding(Encoding::UTF_8))
assert_equal("a", stringio.getc)
assert_equal("\xE3\x81".dup.force_encoding(Encoding::UTF_8), stringio.getc)
assert_nil(stringio.getc)
end

def test_readchar_at_truncated_char
stringio = StringIO.new("\xE3\x81".dup.force_encoding(Encoding::UTF_8))
assert_equal("\xE3\x81".dup.force_encoding(Encoding::UTF_8), stringio.readchar)
assert_raise(EOFError) { stringio.readchar }
end

def test_gets_chomp
assert_equal(nil, StringIO.new("").gets(chomp: true))
assert_equal("", StringIO.new("\n").gets(chomp: true))
Expand Down