Commit e1f1ebb7

e1f1ebb73901Merged

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

Description

Tuple-returning methods: minmax, divmod, partition, rpartition

Fixed-arity "tuple" results lower to typed arrays: Array#minmax -> [min, max] (same element kind), Integer#divmod(n) -> [quotient, remainder] (int array, floored), and String#partition/#rpartition(sep) -> the three-part split (str array; new sp_str_partition / sp_str_rpartition runtime helpers). Each is typed accordingly so a chained .inspect works.

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

Details

Commit
e1f1ebb73901
Parent
6c4e6179309c

lib/sp_runtime.hmodifiedView file

@@ -1428,6 +1428,34 @@
14281428 ASCII whitespace, skip leading whitespace. Issue #507: the no-arg
14291429 form previously emitted `sp_str_split(s, 0)` and segfaulted at
14301430 strlen(NULL). */
1431+static const char*sp_str_byteslice(const char*s,mrb_int start,mrb_int len); /* fwd */
1432+/* partition: [before, sep, after] at the first sep; no match -> [s, "", ""]. */
1433+static sp_StrArray *sp_str_partition(const char *s, const char *sep) {
1434+ SP_GC_ROOT(s); SP_GC_ROOT(sep);
1435+ sp_StrArray *r = sp_StrArray_new();
1436+ mrb_int bl = (mrb_int)sp_str_byte_len(s), sl = (mrb_int)strlen(sep);
1437+ const char *f = sl > 0 ? strstr(s, sep) : s;
1438+ if (!f) { sp_StrArray_push(r, s); sp_StrArray_push(r, sp_str_empty); sp_StrArray_push(r, sp_str_empty); return r; }
1439+ mrb_int pre = (mrb_int)(f - s);
1440+ sp_StrArray_push(r, sp_str_byteslice(s, 0, pre));
1441+ sp_StrArray_push(r, sp_str_byteslice(s, pre, sl));
1442+ sp_StrArray_push(r, sp_str_byteslice(s, pre + sl, bl - pre - sl));
1443+ return r;
1444+}
1445+/* rpartition: split at the last sep; no match -> ["", "", s]. */
1446+static sp_StrArray *sp_str_rpartition(const char *s, const char *sep) {
1447+ SP_GC_ROOT(s); SP_GC_ROOT(sep);
1448+ sp_StrArray *r = sp_StrArray_new();
1449+ mrb_int bl = (mrb_int)sp_str_byte_len(s), sl = (mrb_int)strlen(sep);
1450+ const char *last = NULL;
1451+ if (sl > 0) { const char *p = s; while ((p = strstr(p, sep))) { last = p; p++; } }
1452+ if (!last) { sp_StrArray_push(r, sp_str_empty); sp_StrArray_push(r, sp_str_empty); sp_StrArray_push(r, s); return r; }
1453+ mrb_int pre = (mrb_int)(last - s);
1454+ sp_StrArray_push(r, sp_str_byteslice(s, 0, pre));
1455+ sp_StrArray_push(r, sp_str_byteslice(s, pre, sl));
1456+ sp_StrArray_push(r, sp_str_byteslice(s, pre + sl, bl - pre - sl));
1457+ return r;
1458+}
14311459 static sp_StrArray*sp_str_split_ws(const char*s){
14321460 SP_GC_ROOT(s);
14331461 sp_StrArray*a=sp_StrArray_new();