Repository navigation
String encoding fixes: insert/[]= corrupting multibyte text, tr encodings, start_with? check, codepoints - #107
Merged
Merged
Conversation
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
|
Warning Review limit reachedYou'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. View limit details
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. |
This was referenced Nov 5, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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#insertand#[]=inserted a byte-held value in the middle of a character (data corruption)MutableString.Inserttakes 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.Every
[]=form (index, range, substring, regexp) goes throughReplace, so all of them had the bug, for Shift_JIS and EUC-JP strings too. Values are held as bytes whenever they come fromforce_encoding, binary reads or IO. That makes this ordinary data, not a corner case.The fix:
Insertnow 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#trand#tr_sgave the wrong encoding, or garbagetrchecked the replacement set against the new, empty result string, a check nothing fails. It then wrote the translated characters in the receiver's encoding:"ab".b.tr("a", "é")"\xE9b""éb""ab".b.tr("a", <Shift_JIS あ>)"Bb""あb"12.to_s.tr("1", "①")EncoderFallbackException"①2""é".tr("é", "\xff".b)"ÿ"Encoding::CompatibilityErrorThe result's encoding is now worked out first, as MRI's
tr_transdoes, and an incompatible pair raisesEncoding::CompatibilityError. A call that translates nothing keeps the receiver's encoding.3.
String#start_with?raises for an incompatible prefix;delete_suffixkeeps a broken suffixstart_with?was missing MRI'srb_enc_check, whichend_with?already had. So"é".start_with?("\xff".b)returnedfalse, anddelete_prefixreturned the string unchanged, where CRuby raises.delete_suffixremoved a suffix with broken bytes. MRI'sdeleted_suffix_lengthnever does, unlikedeleted_prefix_length.4.
String#codepointsand#each_codepointgive the encoding's own codes, as#orddoes"あ".encode("Shift_JIS").codepointsreturned[12354](U+3042), while#ordand CRuby return 33440 (0x82A0). Socodepoints.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
tr/tr_s, 84start_with?/delete_prefixand 23codepointsdifferences from CRuby are gone. So are all theinsert/[]=differences, for receivers and values held both ways.insert/[]=cases, 22trcases (tr!, ranges, negation, deletion, squeeze, emoji, frozen, unchanged), 15 prefix/suffix cases, andcodepoints/ord/chracross 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.Integer#chr, library/stringio, and IOread/getsgive the same results as master. That includes 2 errors in core/string that master has too.tron 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
joinand interpolation, plus one%case where CRuby itself builds a broken UTF-8 string. None of them changes any bytes.Generated by Claude Code