Project

General

Profile

Actions

Bug #22700

open

rb_str_subseq copies the coderange of the src string even if substring is ascii-only

Bug #22700: rb_str_subseq copies the coderange of the src string even if substring is ascii-only

Added by luke-gru (Luke Gruber) about 14 hours ago. Updated about 14 hours ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:127788]

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-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 (too many rescans). We need to come up with a better solution.

Actions

Also available in: PDF Atom