Bug #22721
openString#slice!(regexp, capture) returns a string with a stale coderange when capture.to_int modifies the receiver
Description
s = "aéb"
obj = Object.new
obj.define_singleton_method(:to_int) { s.replace("éé"); 0 }
r = s.slice!(/é/, obj)
r #=> "\xA9\xC3"
r.valid_encoding? #=> true (r.b.force_encoding("UTF-8").valid_encoding? #=> false)
rb_str_slice_bang converts the capture argument after the regexp search; the conversion can run Ruby code that modifies the receiver. The existing guard ("Converting the backref may have modified the string.") clamps the offsets to the new length, but the piece is then cut from the new contents at the old offsets and gets the new contents' coderange, so a piece that splits a character is cached as valid.
Possible fixes: raise like other "string modified" checks, take the piece from the MatchData, or clear the piece's coderange in this branch. Since the existing test test_slice_bang_string_modified shows that clamping was chosen deliberately for this spot, I have not prepared a patch.
Reproduces on master and 4.0.10.
No data to display