Commit ad971c0b
ad971c0b747fMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 4 files · +2 added · ~2 modified
Description
runtime,codegen: String#to_i(base) for non-decimal parses
"ff".to_i(16) and similar fell through to the no-base
sp_str_to_i_cruby helper, dropping the base argument and
returning 0.
Add sp_str_to_i_base accepting bases 2..36 with MRI-compatible
semantics (leading sign, 0x / 0b / 0o prefix when base
matches, _ between digits, overflow saturates). Codegen routes
the 1-arg form to the new helper; 0-arg keeps sp_str_to_i_cruby.
Refs #883
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- ad971c0b747f
- Parent
- f12e02f911ef
lib/sp_runtime.hmodifiedView file
@@ -262,6 +262,59 @@
262262
return neg ? -v : v;263263
}264264
265+
/* `String#to_i(base)` with a non-decimal base. Accepts bases 2..36266+
like MRI; `_` is allowed between digits the same way as base 10.267+
Stops at the first invalid digit and returns what's parsed so268+
far. Issue #883. */269+
static mrb_int sp_str_to_i_base(const char *s, mrb_int base) {270+
if (!s) return 0;271+
if (base < 2 || base > 36) base = 10;272+
const char *p = s;273+
while (isspace((unsigned char)*p)) p++;274+
int neg = 0;275+
if (*p == '+') p++;276+
else if (*p == '-') { neg = 1; p++; }277+
/* Optional `0x` / `0b` / `0o` prefix matching the explicit base.278+
CRuby's String#to_i(base) accepts these. */279+
if (*p == '0' && p[1] != 0) {280+
if ((base == 16) && (p[1] == 'x' || p[1] == 'X')) p += 2;281+
else if ((base == 2) && (p[1] == 'b' || p[1] == 'B')) p += 2;282+
else if ((base == 8) && (p[1] == 'o' || p[1] == 'O')) p += 2;283+
}284+
mrb_int v = 0;285+
int any = 0;286+
int saturated = 0;287+
while (*p) {288+
int d = -1;289+
if (*p >= '0' && *p <= '9') d = *p - '0';290+
else if (*p >= 'a' && *p <= 'z') d = *p - 'a' + 10;291+
else if (*p >= 'A' && *p <= 'Z') d = *p - 'A' + 10;292+
if (d < 0 || d >= (int)base) {293+
if (*p == '_' && any) {294+
/* Lookahead: only consume `_` between digits. */295+
int n = -1;296+
char c = p[1];297+
if (c >= '0' && c <= '9') n = c - '0';298+
else if (c >= 'a' && c <= 'z') n = c - 'a' + 10;299+
else if (c >= 'A' && c <= 'Z') n = c - 'A' + 10;300+
if (n >= 0 && n < (int)base) { p++; continue; }301+
}302+
break;303+
}304+
mrb_int t;305+
if (__builtin_mul_overflow(v, base, &t) ||306+
__builtin_add_overflow(t, (mrb_int)d, &v)) {307+
v = INT64_MAX;308+
saturated = 1;309+
}310+
any = 1;311+
p++;312+
}313+
if (!any) return 0;314+
if (saturated) return neg ? INT64_MIN : INT64_MAX;315+
return neg ? -v : v;316+
}317+
265318
/* CRuby's `Integer(s)` raises ArgumentError for unparseable input266319
(empty string, leading/trailing junk, all-whitespace). The bare267320
`(mrb_int)strtoll(s, NULL, 10)` spinel previously emitted silentlyspinel_codegen.rbmodifiedView file
Loading diff…
test/string_to_i_base.rbaddedView file
Loading diff…
test/string_to_i_base.rb.expectedaddedView file
Loading diff…