Commit 34b0cc71
34b0cc719aa0Merged
NHH <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified
Description
Fix String#rindex with position argument
The 2-arg form s.rindex(sub, pos) silently dropped the position argument and always returned the last match, so "hello".rindex("l", 2) returned 3 instead of 2. Add sp_str_rindex_from runtime helper that limits the search to codepoint index <= pos (with negative pos support), and route codegen to it when a second argument is present.
Details
- Commit
- 34b0cc719aa0
- Parent
- 25031c1dd270
lib/sp_runtime.hmodifiedView file
@@ -1337,6 +1337,11 @@
13371337
matches" loop is O(N) total rather than O(N^2). */13381338
static mrb_int sp_str_index_from(const char*s,const char*sub,mrb_int start){mrb_int cl=sp_str_length(s);if(start<0)start+=cl;if(start<0)start=0;if(start>cl)return -1;size_t boff=sp_utf8_byte_offset(s,start);const char*f=strstr(s+boff,sub);if(!f)return -1;mrb_int n=start;const char*p=s+boff;while(p<f){p+=sp_utf8_advance(p);n++;}return n;}13391339
static mrb_int sp_str_rindex(const char*s,const char*sub){if(!sub)sp_raise_cls("TypeError","no implicit conversion of nil into String");size_t sl=strlen(sub);if(sl==0)return sp_str_length(s);const char*last=NULL;const char*p=s;while((p=strstr(p,sub))){last=p;p++;}if(!last)return -1;mrb_int n=0;const char*q=s;while(q<last){q+=sp_utf8_advance(q);n++;}return n;}1340+
/* `s.rindex(sub, pos)` — find the rightmost occurrence of sub at or1341+
before codepoint index pos. Walks all matches and keeps the last1342+
one whose codepoint index <= pos. */1343+
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;}1344+
13401345
static char sp_char_cache[256][3];13411346
static int sp_char_cache_init = 0;13421347
/* start/len are codepoint indices/counts. */spinel_codegen.rbmodifiedView file
Loading diff…
test/str_rindex_position.rbaddedView file
Loading diff…
test/str_rindex_position.rb.expectedaddedView file
Loading diff…