Bug #22700
openrb_str_subseq copies the coderange of the src string even if substring is ascii-only
Description
Background¶
Ruby's encoding and coderange system has a few invariants. One of them is:
- If a String is ascii-only it needs to be tagged has having a coderange of
7BIT
This means if a String has a coderange of VALID, it can't contain only ascii characters. Also, a coderange of UNKNOWN (cleared) is always correct. It will be re-scanned when needed. Rescanning can be expensive, so the coderange is cached and clearing is avoided if possible.
Uses¶
rb_str_subseq is used in many places, including:
- Splitting (split, partition, ...)
- Iteration (each_line, each_char, chars, ...)
- Trimming (chop, chomp, lstrip, rstrip ...)
- Regexp (scan, ...)
It's also used for MatchData and $~ accessors ($`, $', $&) and more.
The Bug¶
Currently, rb_str_subseq copies the coderange of the src string. However, because the substring could contain only ascii characters, it should either rescan the substring or clear its coderange. This violates an invariant of Strings, and causes methods like String#ascii_only? to work incorrectly in some situations. Other String functions also rely on this invariant.
I merged https://github.com/ruby/ruby/pull/20136 but reverted it shortly afterwards because it caused a regression (too many rescans). We need to come up with a better solution.
Updated by luke-gru (Luke Gruber) about 17 hours ago
- Subject changed from rb_str_subseq copies the coderange of the src string even if substring is 7BIT to rb_str_subseq copies the coderange of the src string even if substring is ascii-only
Updated by luke-gru (Luke Gruber) about 1 hour ago
- Description updated (diff)