Commit 448eff1f

448eff1fcaa7Merged

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

Description

String#to_i(0): auto-detect base from the literal prefix

to_i(0) now detects the base from a 0x / 0b / 0o / 0 prefix (defaulting to decimal) instead of raising "invalid radix 0".

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

Details

Commit
448eff1fcaa7
Parent
8482dd6d304b

lib/sp_core.cmodifiedView file

@@ -159,6 +159,21 @@
159159 ArgumentError on invalid input or unsupported base. Issue #887. */
160160 mrb_int sp_str_to_i_strict_base(const char *s, mrb_int base) {
161161 if (!s) sp_raise_cls("ArgumentError", "invalid value for Integer(): nil");
162+ if (base == 0) {
163+ /* auto-detect the base from the literal's prefix */
164+ const char *q = s;
165+ while (isspace((unsigned char)*q)) q++;
166+ if (*q == '+' || *q == '-') q++;
167+ if (*q == '0') {
168+ char n = q[1];
169+ if (n == 'x' || n == 'X') base = 16;
170+ else if (n == 'b' || n == 'B') base = 2;
171+ else if (n == 'o' || n == 'O') base = 8;
172+ else if (n >= '0' && n <= '7') base = 8;
173+ else base = 10;
174+ }
175+ else base = 10;
176+ }
162177 if (base < 2 || base > 36) sp_raise_cls("ArgumentError", sp_sprintf("invalid radix %lld", (long long)base));
163178 const char *p = s;
164179 while (isspace((unsigned char)*p)) p++;