Commit 9f9489fe

9f9489fef68cMerged

Sam Ruby <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

fix(runtime): two-pass sp_PtrArray_str_join (gemini PR #529 feedback)

sp_String entries carry their own length, so the malloc/realloc-grow pattern mirrored from sp_StrArray_join was the wrong shape here. Switch to two-pass: sum the exact total, sp_str_alloc once, memcpy each element by s->len. Removes the realloc-failure leak path and the long-separator overflow window, drops the intermediate malloc'd buffer, and short-circuits empty arrays to sp_str_empty.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
9f9489fef68c
Parent
b31dd3e289c6

lib/sp_runtime.hmodifiedView file

@@ -885,10 +885,13 @@
885885 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;}
886886 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;}
887887 /* issue #526: join for a sp_PtrArray of sp_String* (mutable_str_ptr_array).
888- Sibling to sp_StrArray_join — same shape, but reads each element's
889- bytes from the sp_String data/len pair (preserves embedded NULs)
890- rather than strlen on a const char*. */
891-static const char*sp_PtrArray_str_join(sp_PtrArray*a,const char*sep){size_t sl=strlen(sep),cap=256;char*buf=(char*)malloc(cap);size_t len=0;for(mrb_int i=0;i<a->len;i++){if(i>0){if(len+sl>=cap){cap*=2;buf=(char*)realloc(buf,cap);}memcpy(buf+len,sep,sl);len+=sl;}sp_String*s=(sp_String*)a->data[i];size_t el=s?(size_t)s->len:0;if(len+el>=cap){cap=(len+el)*2+1;buf=(char*)realloc(buf,cap);}if(el){memcpy(buf+len,s->data,el);len+=el;}}buf[len]=0;char*r=sp_str_alloc(len);memcpy(r,buf,len);free(buf);return r;}
888+ Sibling to sp_StrArray_join, but takes advantage of sp_String's known
889+ length: two-pass — sum the exact total, sp_str_alloc once, then memcpy
890+ each element by its s->len (preserves embedded NULs). Avoids the
891+ realloc-grow loop's leak-on-failure and long-separator overflow
892+ risks, and skips an intermediate malloc'd buffer. NULL entries
893+ contribute zero length. */
894+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;}
892895
893896 #ifdef __FreeBSD__
894897