Bug #22635
closedString#byterindex can return an offset inside a character
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 \:
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
Doesn't byte mean it never considers the encoding information?
Updated by shugo (Shugo Maeda) about 9 hours ago
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
Updated by jhawthorn (John Hawthorn) about 5 hours ago
- 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 "\":
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]