Skip to content

Commit

Permalink
Make rb_str_rindex return byte index
Browse files Browse the repository at this point in the history
Leave callers to convert byte index to char index, as well as
`rb_str_index`, so that `rb_str_rpartition` does not need to
re-convert char index to byte index.
  • Loading branch information
nobu committed Jul 9, 2023
1 parent e225783 commit 5e79d5a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
18 changes: 18 additions & 0 deletions benchmark/string_rpartition.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
prelude: |
str1 = [*"a".."z",*"0".."9"].join("")
str10 = str1 * 10 + ":"
str100 = str1 * 100 + ":"
str1000 = str1 * 1000 + ":"
nonascii1 = [*"\u{e0}".."\u{ff}"].join("")
nonascii10 = nonascii1 * 10 + ":"
nonascii100 = nonascii1 * 100 + ":"
nonascii1000 = nonascii1 * 1000 + ":"
benchmark:
rpartition-1: str1.rpartition(":")
rpartition-10: str10.rpartition(":")
rpartition-100: str100.rpartition(":")
rpartition-1000: str1000.rpartition(":")
rpartition-nonascii1: nonascii1.rpartition(":")
rpartition-nonascii10: nonascii10.rpartition(":")
rpartition-nonascii100: nonascii100.rpartition(":")
rpartition-nonascii1000: nonascii1000.rpartition(":")
10 changes: 7 additions & 3 deletions string.c
Original file line number Diff line number Diff line change
Expand Up @@ -3807,6 +3807,7 @@ strseq_core(const char *str_ptr, const char *str_ptr_end, long str_len,
return pos + offset;
}

/* found index in byte */
#define rb_str_index(str, sub, offset) rb_strseq_index(str, sub, offset, 0)

static long
Expand Down Expand Up @@ -4068,6 +4069,7 @@ str_rindex(VALUE str, VALUE sub, const char *s, rb_encoding *enc)
}
#endif

/* found index in byte */
static long
rb_str_rindex(VALUE str, VALUE sub, long pos)
{
Expand Down Expand Up @@ -4097,7 +4099,7 @@ rb_str_rindex(VALUE str, VALUE sub, long pos)
}

s = str_nth(sbeg, RSTRING_END(str), pos, enc, singlebyte);
return rb_str_sublen(str, str_rindex(str, sub, s, enc));
return str_rindex(str, sub, s, enc);
}

/*
Expand Down Expand Up @@ -4197,7 +4199,10 @@ rb_str_rindex_m(int argc, VALUE *argv, VALUE str)
else {
StringValue(sub);
pos = rb_str_rindex(str, sub, pos);
if (pos >= 0) return LONG2NUM(pos);
if (pos >= 0) {
pos = rb_str_sublen(str, pos);
return LONG2NUM(pos);
}
}
return Qnil;
}
Expand Down Expand Up @@ -10425,7 +10430,6 @@ rb_str_rpartition(VALUE str, VALUE sep)
if (pos < 0) {
goto failed;
}
pos = rb_str_offset(str, pos);
}

return rb_ary_new3(3, rb_str_subseq(str, 0, pos),
Expand Down

0 comments on commit 5e79d5a

Please sign in to comment.