From 8b022e6ec450856b716882e1d52fabf109aff51e Mon Sep 17 00:00:00 2001 From: yppp <304476+yppp@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:57:54 +0900 Subject: [PATCH] Return the remaining bytes of a truncated character from getc StringIO#getc split a truncated multi-byte character at the end of the string into single bytes, while IO#getc returns the remaining bytes of the incomplete character together: io = File.open(path_with_bytes_a\xE3\x81) # UTF-8 io.getc # => "a" io.getc # => "\xE3\x81" sio = StringIO.new("a\xE3\x81".dup.force_encoding(Encoding::UTF_8)) sio.getc # => "a" sio.getc # => "\xE3" (then "\x81") Use rb_enc_precise_mbclen in strio_getc: when the character is incomplete because the string ends (MBCLEN_NEEDMORE), consume all remaining bytes; when it is invalid, keep returning a single byte. --- ext/stringio/stringio.c | 8 +++++++- test/stringio/test_stringio.rb | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) 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))