Commit 32b36563

32b365630f94Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 5 files · +2 added · ~3 modified

Description

runtime,analyze,codegen: String#codepoints returns int_array

"hello".codepoints used to fall through to the unresolved-call fallback. Add sp_str_codepoints runtime helper (one IntArray entry per UTF-8 codepoint), dispatch from compile_string_method and infer as int_array.

each_codepoint without a block deferred (Enumerator gap).

Refs #903

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

Details

Commit
32b365630f94
Parent
7cc64b24149a

lib/sp_runtime.hmodifiedView file

@@ -1596,6 +1596,10 @@
15961596 buffer through size_t overflow. */
15971597 static const char*sp_str_repeat(const char*s,mrb_int n){if(!s||n<=0)return sp_str_empty;size_t l=strlen(s);if(l>0&&(size_t)n>SIZE_MAX/l)return sp_str_empty;char*r=sp_str_alloc_raw(l*n+1);for(mrb_int i=0;i<n;i++)memcpy(r+l*i,s,l);r[l*n]=0;return r;}
15981598 static sp_IntArray*sp_str_bytes(const char*s){sp_IntArray*a=sp_IntArray_new();if(!s)return a;size_t n=sp_str_byte_len(s);for(size_t i=0;i<n;i++)sp_IntArray_push(a,(mrb_int)(unsigned char)s[i]);return a;}
1599+/* Issue #903: String#codepoints -- one IntArray entry per UTF-8
1600+ codepoint (not byte). Replacement-character behaviour mirrors
1601+ sp_utf8_decode (returns the leading byte for malformed seqs). */
1602+static sp_IntArray*sp_str_codepoints(const char*s){sp_IntArray*a=sp_IntArray_new();if(!s)return a;const char*p=s;while(*p){uint32_t cp;int n=sp_utf8_decode(p,&cp);sp_IntArray_push(a,(mrb_int)cp);p+=n;}return a;}
15991603 /* Issue #798: guard NULL inputs (CRuby treats nil/no-op gracefully). */
16001604 static const char*sp_str_tr(const char*s,const char*from,const char*to){if(!s)return sp_str_empty;if(!from||!to)return s;size_t fn,tn;uint32_t*fcps=sp_utf8_decode_all(from,&fn);uint32_t*tcps=sp_utf8_decode_all(to,&tn);size_t bl=strlen(s);size_t cap=bl*4+1;char*buf=(char*)malloc(cap);size_t n=0;const char*p=s;while(*p){uint32_t cp;int cn=sp_utf8_decode(p,&cp);size_t mi=fn;for(size_t j=0;j<fn;j++)if(fcps[j]==cp){mi=j;break;}if(mi<fn&&tn>0){uint32_t rep=mi<tn?tcps[mi]:tcps[tn-1];n+=sp_utf8_encode(rep,buf+n);}else{memcpy(buf+n,p,cn);n+=cn;}p+=cn;}buf[n]=0;char*r=sp_str_alloc(n);memcpy(r,buf,n+1);free(buf);free(fcps);free(tcps);return r;}
16011605 static const char*sp_str_delete(const char*s,const char*chars){if(!s)return sp_str_empty;if(!chars)return s;size_t setn;uint32_t*set=sp_utf8_decode_all(chars,&setn);size_t bl=strlen(s);char*r=sp_str_alloc_raw(bl+1);size_t n=0;const char*p=s;while(*p){uint32_t cp;int cn=sp_utf8_decode(p,&cp);if(!sp_utf8_set_has(set,setn,cp)){memcpy(r+n,p,cn);n+=cn;}p+=cn;}r[n]=0;free(set);return r;}