Skip to content

String encoding fixes: insert/[]= corrupting multibyte text, tr encodings, start_with? check, codepoints - #107

Merged
Largo merged 4 commits into
masterfrom
claude/tender-pasteur-67de3v
Nov 5, 2026
Merged

Largo merged 4 commits into
masterfrom
claude/tender-pasteur-67de3v

Conversation

@Largo

@Largo Largo commented Nov 5, 2026

Copy link
Copy Markdown
Owner

This PR fixes four String encoding bugs. I found them by comparing IronRuby with CRuby over an encoding matrix: about 100 String operations applied to 11 kinds of receivers and arguments. The kinds were UTF-8 (ASCII, non-ASCII, multibyte, each held as chars and as bytes), binary, US-ASCII, Shift_JIS and ISO-8859-1. Each result is compared as its encoding plus hex bytes, so CRuby's inspect escaping adds no noise. Each commit fixes one group.

1. String#insert and #[]= inserted a byte-held value in the middle of a character (data corruption)

MutableString.Insert takes a CLR char index. When the value's content was bytes, the content inserted it into the receiver's bytes, after switching a char receiver to bytes, and treated the index as a byte offset. The two only agree while every character before the index is one byte.

s = "あい".b.force_encoding("UTF-8")
s.insert(1, "う".b.force_encoding("UTF-8"))   # bytes e3 [e3 81 86] 81 82 …, broken UTF-8
s = +"あいう"; s[1] = line_from_io            # the same

Every []= form (index, range, substring, regexp) goes through Replace, so all of them had the bug, for Shift_JIS and EUC-JP strings too. Values are held as bytes whenever they come from force_encoding, binary reads or IO. That makes this ordinary data, not a corner case.

The fix: Insert now gives the content the byte offset of the characters before the index, in that one case only. That is a byte-held value going into a receiver whose characters are not all single bytes. Every other insert is unchanged.

2. String#tr and #tr_s gave the wrong encoding, or garbage

tr checked the replacement set against the new, empty result string, a check nothing fails. It then wrote the translated characters in the receiver's encoding:

before CRuby
"ab".b.tr("a", "é") ASCII-8BIT "\xE9b" UTF-8 "éb"
"ab".b.tr("a", <Shift_JIS あ>) ASCII-8BIT "Bb" Shift_JIS "あb"
12.to_s.tr("1", "①") EncoderFallbackException UTF-8 "①2"
"é".tr("é", "\xff".b) "ÿ" Encoding::CompatibilityError

The result's encoding is now worked out first, as MRI's tr_trans does, and an incompatible pair raises Encoding::CompatibilityError. A call that translates nothing keeps the receiver's encoding.

3. String#start_with? raises for an incompatible prefix; delete_suffix keeps a broken suffix

  • start_with? was missing MRI's rb_enc_check, which end_with? already had. So "é".start_with?("\xff".b) returned false, and delete_prefix returned the string unchanged, where CRuby raises.
  • delete_suffix removed a suffix with broken bytes. MRI's deleted_suffix_length never does, unlike deleted_prefix_length.

4. String#codepoints and #each_codepoint give the encoding's own codes, as #ord does

"あ".encode("Shift_JIS").codepoints returned [12354] (U+3042), while #ord and CRuby return 33440 (0x82A0). So codepoints.map { |c| c.chr(enc) } did not give the string back. Both now use #ord's conversion. An ASCII character in an ASCII-compatible encoding skips it.

Testing

  • The encoding matrix: all 44 tr/tr_s, 84 start_with?/delete_prefix and 23 codepoints differences from CRuby are gone. So are all the insert/[]= differences, for receivers and values held both ways.
  • Separate case lists, compared with CRuby 3.3: 15 insert/[]= cases, 22 tr cases (tr!, ranges, negation, deletion, squeeze, emoji, frozen, unchanged), 15 prefix/suffix cases, and codepoints/ord/chr across 10 encodings. Everything matches except one case where 3.3 itself returns invalid UTF-8: "abc".b.tr("^b", "é") is "\xE9b\xE9" tagged UTF-8 in 3.3, and "ébé" here.
  • ruby/spec: core/string, symbol, encoding, regexp, array/pack, Integer#chr, library/stringio, and IO read/gets give the same results as master. That includes 2 errors in core/string that master has too.
  • Speed: tr on ASCII text is unchanged within noise.

Left as they are: a few remaining matrix differences are ASCII-only results whose encoding differs from CRuby's in join and interpolation, plus one % case where CRuby itself builds a broken UTF-8 string. None of them changes any bytes.


Generated by Claude Code

Translate checked the receiver against the source set, but checked the
replacement set against the new, empty result string - which nothing
fails - and then appended the translated characters encoded in the
receiver's encoding:

    "ab".b.tr("a", "é")                  # ASCII-8BIT "\xE9b"; CRuby UTF-8 "éb"
    "ab".b.tr("a", <Shift_JIS あ>)        # ASCII-8BIT "Bb";    CRuby Shift_JIS "あb"
    "ab".force_encoding("US-ASCII").tr("a", "é")   # EncoderFallbackException
    12.to_s.tr("1", "①")                 # EncoderFallbackException
    "é".tr("é", "\xff".b)                # "ÿ";  CRuby: CompatibilityError

The result's encoding is now worked out first, as tr_trans does: the
receiver must be compatible with both character sets (and they with each
other when those two answers differ), and an incompatible pair raises
Encoding::CompatibilityError. It differs from the receiver's encoding
only when the receiver is ASCII-only, so the result - or the receiver,
for tr! - takes it before any character is read or written. A call that
translates nothing keeps the receiver's encoding, as in MRI. The code
point path (surrogate pairs) builds its result in that encoding too.

An encoding matrix of 7 x 7 receiver/argument encodings: all 44 tr and
tr_s differences from CRuby are gone. 22 more cases (tr!, ranges,
negation, deletion, squeeze, emoji, frozen, unchanged): the same as
CRuby 3.3 but for one, where 3.3 itself writes an invalid UTF-8 string
("abc".b.tr("^b", "é") gives "\xE9b\xE9" tagged UTF-8; IronRuby gives
"ébé"). spec/core/string: the same as master. tr speed on ASCII text is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW
MutableString.Insert takes a CLR char index, but when the value's content
is bytes the content inserts it into the receiver's bytes - switching a
char receiver to bytes first - and takes the index as a byte offset.
That is the same only while every character before the index is one
byte, so a multibyte string got the value inserted inside a character:

    s = "あい".b.force_encoding("UTF-8")
    s.insert(1, "う".b.force_encoding("UTF-8"))   # e3 [e38186] 8182 e38184
    s = +"あいう"; s[1] = io_line                 # the same, for any byte-held value

Every String#[]= form (index, range, substring, regexp) goes through
Replace, so all of them did it; Shift_JIS and EUC-JP strings too. Values
are held as bytes whenever they come from force_encoding, binary reads or
IO, so this is ordinary data, not a corner case.

Insert now gives the content the byte offset of the characters before
the index in that one case (a byte-held value, a receiver whose
characters are not all single bytes). Every other insert is unchanged.

Against CRuby: 15 insert/[]= cases mixing char- and byte-held UTF-8
receivers and values (including an invalid byte), plus Shift_JIS and
EUC-JP - all the same now. spec/core/string, core/symbol, core/array/pack,
core/regexp, library/stringio, io read/gets: the same as master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW
…eeps a broken suffix

start_with? compared bytes without MRI's rb_enc_check, so an incompatible
non-ASCII prefix answered false where CRuby raises - unlike end_with?,
which already checked:

    "é".start_with?("\xff".b)       # false; CRuby: Encoding::CompatibilityError
    "é".delete_prefix("\xff".b)     # "é";   CRuby: Encoding::CompatibilityError

(delete_prefix goes through start_with?, so it now raises too.)

And delete_suffix removed a suffix with broken bytes, which MRI's
deleted_suffix_length never does - unlike deleted_prefix_length, which
still compares a broken prefix and only skips the encoding check:

    "ab\xff".delete_suffix("\xff")  # "ab"; CRuby: "ab\xFF"

The 7 x 7 encoding matrix: all 84 start_with?/delete_prefix differences
from CRuby are gone. 15 more cases (broken and valid prefixes and
suffixes, Regexp and multiple prefixes, UTF-16, delete_prefix!) match
CRuby 3.3. spec/core/string and core/symbol: the same as master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW
…, as #ord does

For a non-Unicode multibyte encoding they answered the character's
Unicode code point, while #ord - and CRuby - answer its code in the
string's encoding:

    s = "あ".encode("Shift_JIS")
    s.ord          # 33440 (0x82A0)
    s.codepoints   # [12354] (U+3042); CRuby [33440]

so s.codepoints.map { |c| c.chr(s.encoding) } did not give s back. Both
now go through #ord's NativeCode; an ASCII character in an ASCII
compatible encoding is answered as is, without encoding it.

Shift_JIS, EUC-JP, Windows-31J, ISO-8859-1, Windows-1252, GBK, Big5,
UTF-16LE, UTF-8 and KOI8-R: codepoints, each_codepoint, ord and the chr
round trip are the same as CRuby's, as is an invalid byte. spec/core/string,
core/encoding and Integer#chr: the same as master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW
@coderabbitai

coderabbitai Bot commented Nov 5, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 34 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3805dcf8-5bd9-4794-9902-17760fc5ffee
Commits

Reviewing files that changed from the base of the PR and between df7765d and be03980.

Files selected for processing: 3

  • Src/Libraries/Builtins/MutableStringOps.cs
  • Src/Ruby/Builtins/MutableString.cs
  • Src/StdLib/ironruby/ruby4.rb
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@Largo
Largo merged commit 1d69b18 into master Nov 5, 2026
8 checks passed
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.

2 participants