From: "luke-gru (Luke Gruber) via ruby-core" Date: 2026-12-01T23:42:37+00:00 Subject: [ruby-core:127788] [Ruby Bug#22700] rb_str_subseq copies the coderange of the src string even if substring is 7BIT Issue #22700 has been reported by luke-gru (Luke Gruber). ---------------------------------------- Bug #22700: rb_str_subseq copies the coderange of the src string even if substring is 7BIT https://bugs.ruby-lang.org/issues/22700 * Author: luke-gru (Luke Gruber) * Status: Open * ruby -v: 4.1 * Backport: 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN ---------------------------------------- ### 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-only 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-only 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](https://github.com/ruby/ruby/pull/20339) (too many rescans). We need to come up with a better solution. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/