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
size_t rest = slen - pos; if (olen+rest+1 >= cap) { cap = olen+rest+64; out = (char*)realloc(out, cap); } memcpy(out+olen, str+pos, rest); olen += rest; out[olen] = 0; return out; /* The buffer is over-allocated (cap has slack); set the string's stored length to the bytes actually written so #length / inspect don't read the trailing slack. */ out[olen] = 0; sp_str_set_len(out, olen); return out;}/* String#gsub(regex, hash) — per-match hash lookup form. CRuby's size_t rest = slen - pos; if (olen + rest >= cap) { cap = olen + rest + 1; out = (char *)realloc(out, cap); } memcpy(out + olen, str + pos, rest); olen += rest; out[olen] = 0; return out; out[olen] = 0; sp_str_set_len(out, olen); return out;}/* Issue #910: sub(regex, hash) — same lookup semantics as if (olen + rest + 1 >= cap) { cap = olen + rest + 64; out = (char*)realloc(out, cap); } memcpy(out+olen, str+caps[1], rest); out[olen+rest] = 0; sp_str_set_len(out, olen + rest); return out;}test/regexp_sub_gsub_length.rbaddedView file
Loading diff…
test/regexp_sub_gsub_length.rb.expectedaddedView file
Loading diff…