Commit 5be37dfa

5be37dfa03deMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

sp_str_rindex_from: O(N) codepoint walk + NULL guard

Follow-up to #1061 (gemini-code-assist review). The merged sp_str_rindex_from reset its codepoint-counting cursor to the start of the string on every strstr match, making it O(N^2) for a short needle in a long repetitive haystack. Hoist the walk cursor (r) and counter (cur_n) out of the match loop so they advance monotonically with the forward-moving strstr results — O(N) total. Also guard a NULL receiver up front. Output is unchanged (str_rindex_position regression test still matches CRuby).

Refs #1061

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
5be37dfa03de
Parent
a4386f0eb4e0

lib/sp_runtime.hmodifiedView file

@@ -1353,7 +1353,7 @@
13531353 /* `s.rindex(sub, pos)` — find the rightmost occurrence of sub at or
13541354 before codepoint index pos. Walks all matches and keeps the last
13551355 one whose codepoint index <= pos. */
1356-static mrb_int sp_str_rindex_from(const char*s,const char*sub,mrb_int pos){if(!sub)sp_raise_cls("TypeError","no implicit conversion of nil into String");mrb_int cl=sp_str_length(s);if(pos<0)pos=cl+pos;if(pos<0)return SP_INT_NIL;size_t sl=strlen(sub);if(sl==0){if(pos>=cl)return cl;return pos;}const char*p=s;mrb_int best=-1;while((p=strstr(p,sub))!=NULL){mrb_int cur_n=0;const char*r=s;while(r<p){r+=sp_utf8_advance(r);cur_n++;}if(cur_n>pos)break;best=cur_n;p++;}return best<0?SP_INT_NIL:best;}
1356+static mrb_int sp_str_rindex_from(const char*s,const char*sub,mrb_int pos){if(!s)return SP_INT_NIL;if(!sub)sp_raise_cls("TypeError","no implicit conversion of nil into String");mrb_int cl=sp_str_length(s);if(pos<0)pos=cl+pos;if(pos<0)return SP_INT_NIL;size_t sl=strlen(sub);if(sl==0){if(pos>=cl)return cl;return pos;}const char*p=s;mrb_int best=-1;const char*r=s;mrb_int cur_n=0;while((p=strstr(p,sub))!=NULL){while(r<p){r+=sp_utf8_advance(r);cur_n++;}if(cur_n>pos)break;best=cur_n;p++;}return best<0?SP_INT_NIL:best;}
13571357
13581358 static char sp_char_cache[256][3];
13591359 static int sp_char_cache_init = 0;