Commit 89168c65

89168c65acc3Merged

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

Description

Set the result length of regex sub/gsub to the bytes written

sp_re_gsub, sp_re_sub and sp_re_gsub_str_str_hash build into a buffer allocated with slack (cap = slen*2 + ... + 64) but returned it without narrowing the string's stored length, so the result reported the padded capacity. "hello".gsub(/l/, "L").length came back as 71 and p/inspect rendered the value followed by a run of NUL bytes. Operations that read the bytes via strlen (puts, ==, concatenation) stopped at the embedded NUL and looked correct, which is why this stayed hidden -- but any regex sub/gsub result inspected or measured was wrong project-wide.

Call sp_str_set_len(out, olen) before returning so the metadata length matches the bytes actually written. The exact-allocation variants (sp_re_sub_str_str_hash, sp_str_sub_str_str_hash, sp_str_gsub) already size to the content and are unaffected.

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

Details

Commit
89168c65acc3
Parent
4bc5c39cb613

lib/sp_runtime.hmodifiedView file

@@ -2232,7 +2232,10 @@
22322232 size_t rest = slen - pos;
22332233 if (olen+rest+1 >= cap) { cap = olen+rest+64; out = (char*)realloc(out, cap); }
22342234 memcpy(out+olen, str+pos, rest); olen += rest;
2235- out[olen] = 0; return out;
2235+ /* The buffer is over-allocated (cap has slack); set the string's
2236+ stored length to the bytes actually written so #length / inspect
2237+ don't read the trailing slack. */
2238+ out[olen] = 0; sp_str_set_len(out, olen); return out;
22362239 }
22372240
22382241 /* String#gsub(regex, hash) — per-match hash lookup form. CRuby's
@@ -2264,7 +2267,7 @@
22642267 size_t rest = slen - pos;
22652268 if (olen + rest >= cap) { cap = olen + rest + 1; out = (char *)realloc(out, cap); }
22662269 memcpy(out + olen, str + pos, rest); olen += rest;
2267- out[olen] = 0; return out;
2270+ out[olen] = 0; sp_str_set_len(out, olen); return out;
22682271 }
22692272
22702273 /* Issue #910: sub(regex, hash) — same lookup semantics as
@@ -2327,6 +2330,7 @@
23272330 if (olen + rest + 1 >= cap) { cap = olen + rest + 64; out = (char*)realloc(out, cap); }
23282331 memcpy(out+olen, str+caps[1], rest);
23292332 out[olen+rest] = 0;
2333+ sp_str_set_len(out, olen + rest);
23302334 return out;
23312335 }
23322336