Commit 0c7545a4
0c7545a4e3cfMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified
Description
String#rpartition with a regex pattern
Plain-string rpartition already worked; the regex arm only covered partition. Add a sp_re_rpartition helper that finds the rightmost match START (MRI reverse-search semantics) and returns [before, match, after], plus the codegen dispatch for a regex literal argument.
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- 0c7545a4e3cf
- Parent
- 48144b27853b
lib/sp_runtime.hmodifiedView file
@@ -2185,6 +2185,43 @@
21852185
return last;21862186
}21872187
2188+
/* `s.rpartition(regex)` -> [before, last_match, after]. On no match Ruby2189+
returns ["", "", s] (the whole string lands in the last slot). Walks2190+
forward to the final match span, mirroring sp_re_rindex. */2191+
static sp_StrArray *sp_re_rpartition(mrb_regexp_pattern *pat, const char *str) {2192+
int64_t slen = (int64_t)strlen(str);2193+
int caps[2];2194+
int64_t pos = 0;2195+
mrb_int ms = -1, me = -1;2196+
while (pos <= slen) {2197+
int n = re_exec(pat, str, slen, pos, caps, 2);2198+
if (n <= 0) break;2199+
ms = caps[0]; me = caps[1];2200+
/* rpartition keys on the rightmost match START (MRI reverse search),2201+
so step one past this start to look for a later-starting match. */2202+
pos = caps[0] + 1;2203+
}2204+
sp_StrArray *r = sp_StrArray_new();2205+
if (ms < 0) {2206+
sp_StrArray_push(r, SPL(""));2207+
sp_StrArray_push(r, SPL(""));2208+
sp_StrArray_push(r, str);2209+
return r;2210+
}2211+
char *before = sp_str_alloc_raw(ms + 1);2212+
memcpy(before, str, ms); before[ms] = 0;2213+
int mlen = (int)(me - ms);2214+
char *mid = sp_str_alloc_raw(mlen + 1);2215+
memcpy(mid, str + ms, mlen); mid[mlen] = 0;2216+
int alen = (int)(slen - me);2217+
char *after = sp_str_alloc_raw(alen + 1);2218+
memcpy(after, str + me, alen); after[alen] = 0;2219+
sp_StrArray_push(r, before);2220+
sp_StrArray_push(r, mid);2221+
sp_StrArray_push(r, after);2222+
return r;2223+
}2224+
21882225
static mrb_bool sp_re_match_p(mrb_regexp_pattern *pat, const char *str) {21892226
int64_t slen = (int64_t)strlen(str);21902227
int caps[2];src/codegen.cmodifiedView file
Loading diff…