Project

General

Profile

Actions

Bug #22721

open

String#slice!(regexp, capture) returns a string with a stale coderange when capture.to_int modifies the receiver

Bug #22721: String#slice!(regexp, capture) returns a string with a stale coderange when capture.to_int modifies the receiver

Added by saddestmartian (sad mart) 1 day ago.

Status:
Open
Assignee:
-
Target version:
-
ruby -v:
ruby 4.1.0dev (2026-12-03T23:00:19Z master bcd243e8e8) +PRISM [x86_64-linux]
[ruby-core:127851]

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

Actions

Also available in: PDF Atom