diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index fb885e3..9ce9e65 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -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); } diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index 5de2e03..87e4aa9 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -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))