2022-11-19 14:43:09 +00:00
|
|
|
#include <NumberParsing.h>
|
|
|
|
|
2022-11-19 21:48:20 +00:00
|
|
|
// This function assumes you have called is_valid_digit_for_base() to validate the digit first.
|
|
|
|
static isize parse_digit_unchecked(char c)
|
|
|
|
{
|
|
|
|
if (_isdigit(c)) return c - '0';
|
|
|
|
if (_islower(c)) return (c - 'a') + 10;
|
|
|
|
return (c - 'A') + 10;
|
|
|
|
}
|
2022-11-19 14:43:09 +00:00
|
|
|
|
2022-11-20 08:24:21 +00:00
|
|
|
static bool is_valid_digit_for_base(int base, char c)
|
|
|
|
{
|
|
|
|
if (!_isalnum(c)) return false;
|
|
|
|
if (parse_digit_unchecked(c) >= (isize)base) return false;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2022-11-19 21:48:20 +00:00
|
|
|
usize _strtou(const char* str, const char** endptr, int base)
|
|
|
|
{
|
|
|
|
usize val = 0;
|
2022-11-19 14:43:09 +00:00
|
|
|
|
|
|
|
while (_isspace(*str)) str++;
|
|
|
|
|
|
|
|
if ((base == 0 || base == 16) && *str == '0')
|
|
|
|
{
|
|
|
|
str++;
|
|
|
|
if (_tolower(*str) == 'x')
|
|
|
|
{
|
|
|
|
base = 16;
|
|
|
|
str++;
|
|
|
|
}
|
|
|
|
else if (base == 0)
|
|
|
|
base = 8;
|
|
|
|
}
|
|
|
|
else if (base == 0)
|
|
|
|
base = 10;
|
|
|
|
|
2022-11-19 21:48:20 +00:00
|
|
|
while (is_valid_digit_for_base(base, *str))
|
2022-11-19 14:43:09 +00:00
|
|
|
{
|
2022-11-19 21:48:20 +00:00
|
|
|
val = (base * val) + parse_digit_unchecked(*str);
|
2022-11-19 14:43:09 +00:00
|
|
|
str++;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (endptr) *endptr = str;
|
|
|
|
|
|
|
|
return val;
|
|
|
|
}
|
|
|
|
|
|
|
|
isize _strtoi(const char* str, const char** endptr, int base)
|
|
|
|
{
|
|
|
|
bool negative = false;
|
|
|
|
|
|
|
|
while (_isspace(*str)) str++;
|
|
|
|
|
|
|
|
if (*str == '-' || *str == '+')
|
|
|
|
{
|
|
|
|
if (*str == '-') negative = true;
|
|
|
|
str++;
|
|
|
|
}
|
|
|
|
|
2022-11-19 21:52:08 +00:00
|
|
|
usize rc = _strtou(str, endptr,
|
|
|
|
base); // FIXME: Check for overflow (the unsigned usize value might not fit into a signed isize)
|
2022-11-19 14:43:09 +00:00
|
|
|
|
2022-11-19 21:52:08 +00:00
|
|
|
return negative ? -(isize)rc : (isize)rc;
|
2022-11-19 14:43:09 +00:00
|
|
|
}
|
2022-11-20 08:28:17 +00:00
|
|
|
|
|
|
|
usize _atou(const char** str)
|
|
|
|
{
|
|
|
|
return _strtou(*str, str, 10);
|
|
|
|
}
|
|
|
|
|
|
|
|
isize _atos(const char** str)
|
|
|
|
{
|
|
|
|
return _strtoi(*str, str, 10);
|
|
|
|
}
|