Commit 6c7ddb81

6c7ddb812e8cMerged

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

Description

Merge pull request #529 from rubys/fix/issue-526-mutable-str-ptr-array-join

fix(codegen,runtime): Array#join on mutable_str_ptr_array (#526)

Details

Commit
6c7ddb812e8c
Parent
7b3434c2a5bf
Merge parent
9f9489fef68c

lib/sp_runtime.hmodifiedView file

@@ -887,6 +887,14 @@
887887 static const char*sp_FloatArrayPtrArray_inspect(sp_PtrArray*a){sp_String*s=sp_String_new("[");for(mrb_int i=0;i<a->len;i++){if(i>0)sp_String_append(s,", ");sp_String_append(s,sp_FloatArray_inspect((sp_FloatArray*)a->data[i]));}sp_String_append(s,"]");return s->data;}
888888 static const char*sp_StrArrayPtrArray_inspect(sp_PtrArray*a){sp_String*s=sp_String_new("[");for(mrb_int i=0;i<a->len;i++){if(i>0)sp_String_append(s,", ");sp_String_append(s,sp_StrArray_inspect((sp_StrArray*)a->data[i]));}sp_String_append(s,"]");return s->data;}
889889 static const char*sp_SymArrayPtrArray_inspect(sp_PtrArray*a){sp_String*s=sp_String_new("[");for(mrb_int i=0;i<a->len;i++){if(i>0)sp_String_append(s,", ");sp_String_append(s,sp_SymArray_inspect((sp_IntArray*)a->data[i]));}sp_String_append(s,"]");return s->data;}
890+/* issue #526: join for a sp_PtrArray of sp_String* (mutable_str_ptr_array).
891+ Sibling to sp_StrArray_join, but takes advantage of sp_String's known
892+ length: two-pass — sum the exact total, sp_str_alloc once, then memcpy
893+ each element by its s->len (preserves embedded NULs). Avoids the
894+ realloc-grow loop's leak-on-failure and long-separator overflow
895+ risks, and skips an intermediate malloc'd buffer. NULL entries
896+ contribute zero length. */
897+static const char*sp_PtrArray_str_join(sp_PtrArray*a,const char*sep){mrb_int al=a->len;if(al==0)return sp_str_empty;size_t sl=strlen(sep),total=0;for(mrb_int i=0;i<al;i++){if(i>0)total+=sl;sp_String*s=(sp_String*)a->data[i];if(s)total+=(size_t)s->len;}char*r=sp_str_alloc(total);size_t cur=0;for(mrb_int i=0;i<al;i++){if(i>0){memcpy(r+cur,sep,sl);cur+=sl;}sp_String*s=(sp_String*)a->data[i];if(s&&s->len){memcpy(r+cur,s->data,(size_t)s->len);cur+=(size_t)s->len;}}return r;}
890898
891899 #ifdef __FreeBSD__
892900