Project

General

Profile

Actions

Bug #22636

closed

String#rindex misses a match when its first byte repeats within the first character

Bug #22636: String#rindex misses a match when its first byte repeats within the first character

Added by jhawthorn (John Hawthorn) 4 days ago. Updated 3 days ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 4.1.0dev (2026-11-25T00:33:09Z HEAD 6698249e41) +PRISM [x86_64-linux]
[ruby-core:127706]

Description

String#rindex misses a match when the substring's first byte appears again later in its first character. = is "\x81\x81" in Shift_JIS:

s = "=A".encode("Shift_JIS")
s.index("=".encode("Shift_JIS"))  # => 0
s.rindex("=".encode("Shift_JIS")) # => nil, expected 0

str_rindex searches backwards for the substring's first byte with memrchr. Here that finds the second \x81. That byte is inside a character, so str_rindex moves the end of the search back to just before that character. The next memrchr never looks at the character's first byte, so the match that starts there is skipped.

Updated by jhawthorn (John Hawthorn) 3 days ago Actions #1

  • Status changed from Open to Closed

Applied in changeset git|13cf4db246dfc03e5cf2c1e1a522fcbc6c58d1c7.


Fix String#rindex missing a match whose first byte repeats

str_rindex looks for the first byte of the substring with memrchr. When
that byte turned out to be inside a character, it moved the search end
to before that character, so a match starting there was never checked:

"=A".encode("Shift_JIS").rindex("=".encode("Shift_JIS")) # => nil

"=" is "\x81\x81" in Shift_JIS, and memrchr finds the second "\x81"
first. A match on any character whose first byte appears again later in
it can be missed this way, and byterindex has the same problem.

[Bug #22636]

Actions

Also available in: PDF Atom