Commit ae5e77de

ae5e77deb9c7Merged

NHH <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified

Description

Fix String#tr/tr_s with empty replacement string

"abc".tr("a", "") returned "abc" instead of "bc". When the to-set is empty, characters matching the from-set should be deleted, not passed through. The condition mi<fn && tn>0 meant empty to-sets fell into the else branch and copied the original char. Now when mi<fn and tn==0 the character is skipped entirely in both sp_str_tr and sp_str_tr_s.

Details

Commit
ae5e77deb9c7
Parent
f19990f805ef

lib/sp_runtime.hmodifiedView file

@@ -1416,7 +1416,7 @@
14161416 sp_utf8_decode (returns the leading byte for malformed seqs). */
14171417 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;}
14181418 /* Issue #798: guard NULL inputs (CRuby treats nil/no-op gracefully). */
1419-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_charset(from,&fn);uint32_t*tcps=sp_utf8_decode_charset(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;}
1419+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_charset(from,&fn);uint32_t*tcps=sp_utf8_decode_charset(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){if(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;}
14201420 /* Issue #902: String#tr_s -- translate AND squeeze consecutive
14211421 identical results into one. Walks codepoint-by-codepoint and
14221422 collapses adjacent duplicates only among the translated bytes
@@ -1439,9 +1439,13 @@
14391439 for(size_t j=0;j<fn;j++)if(fcps[j]==cp){mi=j;break;}
14401440 uint32_t emit_cp;
14411441 int translated=0;
1442- if(mi<fn&&tn>0){
1443- emit_cp=mi<tn?tcps[mi]:tcps[tn-1];
1444- translated=1;
1442+ if(mi<fn){
1443+ if(tn>0){
1444+ emit_cp=mi<tn?tcps[mi]:tcps[tn-1];
1445+ translated=1;
1446+ } else {
1447+ p+=cn; continue;
1448+ }
14451449 } else {
14461450 emit_cp=cp;
14471451 translated=0;