Commit dc88f5bb

dc88f5bb7ae8Merged

Ori Pekelman <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

opt: sp_str_index_from -- start codepoint count from start

Per @gemini-code-assist's review on #406, the loop re-counted codepoints from the beginning of the string when it could resume from start (we already have its byte offset). Changes the per- match step from O(N) to O(N - start), which makes the natural "walk all matches" loop O(N) total instead of O(N^2).

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
dc88f5bb7ae8
Parent
98e5f804d223

lib/sp_runtime.hmodifiedView file

@@ -546,8 +546,10 @@
546546 Negative start counts back from the end of the string. Returns the
547547 absolute codepoint offset of the match (not relative to start), or
548548 -1 when no match exists at or after start. Out-of-range starts
549- (start > length) return -1, matching CRuby. */
550-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=0;const char*p=s;while(p<f){p+=sp_utf8_advance(p);n++;}return n;}
549+ (start > length) return -1, matching CRuby. The codepoint counter
550+ begins at `start` and walks from `s + boff`, so the "walk all
551+ matches" loop is O(N) total rather than O(N^2). */
552+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;}
551553 static mrb_int sp_str_rindex(const char*s,const char*sub){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;}
552554 static char sp_char_cache[256][3];
553555 static int sp_char_cache_init = 0;