Project

General

Profile

Actions

Bug #22635

closed

String#byterindex can return an offset inside a character

Bug #22635: String#byterindex can return an offset inside a character

Added by jhawthorn (John Hawthorn) about 22 hours ago. Updated about 5 hours ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 4.0.10 (2026-11-19 revision a704b7cd95) +PRISM [x86_64-linux]
[ruby-core:127705]

Description

String#byterindex can return the offset of a match that starts in the middle of a character. In Shift_JIS the second byte of 表 is 0x5C, the same as \:

s = "C:\\data\\表".encode("Shift_JIS")
s.byterindex("\\") # => 9, expected 7

byterindex clamps its starting offset to bytesize - sub.bytesize, which can land inside a character, and str_rindex compares the substring there with memcmp without checking that it's a character boundary. Every later candidate is checked with rb_enc_left_char_head.

This is broken on Ruby 3.4 and 4.0. Ruby 3.2 and 3.3 and are a bit more confusing because there were different branches per-OS.

Updated by nobu (Nobuyoshi Nakada) about 15 hours ago Actions #1 [ruby-core:127707]

Doesn't byte mean it never considers the encoding information?

Updated by shugo (Shugo Maeda) about 9 hours ago Actions #2 [ruby-core:127719]

nobu (Nobuyoshi Nakada) wrote in #note-1:

Doesn't byte mean it never considers the encoding information?

The "byte" in byteindex/byterindex means that offsets and return values are measured in bytes, not that the encoding is ignored.
They already raise IndexError if the offset does not land on a character boundary.

I'd like to fix this issue.

Updated by jhawthorn (John Hawthorn) about 5 hours ago Actions #3 [ruby-core:127723]

I had to look up the meaning as well, whether the search cared about encoding (it does). I think this example is helpful to see the bug, which only occurs on the last character.

>> "C:\\data\\表".encode("Shift_JIS").byterindex("\\")
=> 9
>> "C:\\data\\表z".encode("Shift_JIS").byterindex("\\")
=> 7

Updated by jhawthorn (John Hawthorn) about 5 hours ago Actions #4

  • Status changed from Open to Closed

Applied in changeset git|fde586b886a4ea6f5ee15dd7ff5a8fb1094e6eac.


Fix String#byterindex returning an offset inside a character

byterindex clamps its starting offset to bytesize - sub.bytesize, which
can be in the middle of a character. str_rindex checked for a match at
that position with memcmp before its main loop, without checking that
it was a character boundary. In Shift_JIS the trail byte of 表 is "\":

s = "C:\\data\\表".encode("Shift_JIS")
s.byterindex("\\") # => 9, rather than 7

The loop already covers that position (memrchr searches through s) and
checks each hit with rb_enc_left_char_head, so this removes the early
check.

[Bug #22635]

Actions

Also available in: PDF Atom