Skip to content

Return the remaining bytes of a truncated character from StringIO#getc - #246

Open
yppp wants to merge 1 commit into
ruby:masterfrom
yppp:getc-truncated-char
Open

yppp wants to merge 1 commit into
ruby:masterfrom
yppp:getc-truncated-char

Conversation

@yppp

@yppp yppp commented Nov 29, 2026

Copy link
Copy Markdown

StringIO#getc splits 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:

# content: "a" + the first 2 bytes of a 3-byte UTF-8 character
sio = StringIO.new("a\xE3\x81".dup.force_encoding(Encoding::UTF_8))
sio.getc # => "a"
sio.getc # => "\xE3"   # StringIO (before)
sio.getc # => "\x81"

file.getc # => "a"
file.getc # => "\xE3\x81" # IO
file.getc # => nil

This is the getc counterpart of the truncated-character cases already handled for gets with a limit (test_gets_limit_around_truncated_char).

The fix uses rb_enc_precise_mbclen in strio_getc: when the character is incomplete because the string ends (MBCLEN_NEEDMORE), all remaining bytes are consumed; when the byte sequence is invalid, the current single-byte behavior is kept. readchar is fixed through getc. Valid characters and invalid bytes are unchanged.

Tests: test_getc_at_truncated_char and test_readchar_at_truncated_char. Both fail on unpatched master and pass with this change; the rest of the test suite is unchanged (verified against a baseline build).

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant