Move a few repeated lambdas into their own functions

This commit is contained in:
apio 2022-11-19 22:48:20 +01:00
parent af267772f0
commit 30a7d760ae

View File

@ -37,32 +37,35 @@ isize _atos(const char** str)
return neg ? -val : val;
}
usize _strtou(const char* str, const char** endptr, int base)
static bool is_valid_digit_for_base(int base, char c)
{
usize val = 0;
auto valid_digit = [](int _base, char c) -> bool {
if (_base <= 10)
if (base <= 10)
{
if (!_isdigit(c)) return false;
if ((c - '0') < _base) return true;
if (!_isdigit(c)) return false; // Bases lower than 10 only use decimal digits.
if ((c - '0') < base) return true;
return false;
}
else
{
if (!_isalnum(c)) return false;
if (_isdigit(c)) return true;
if (!_isalnum(c)) return false; // Any valid base (2-36) only uses 0-9 and a-z.
if (_isdigit(c)) return true; // Any base higher than decimal will include all decimal digits.
bool lower = _islower(c);
if (((c - lower ? 'a' : 'A') + 10) < _base) return true;
if (((c - lower ? 'a' : 'A') + 10) < base) return true;
return false;
}
};
}
auto to_digit = [](char c) -> usize {
// 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;
};
}
usize _strtou(const char* str, const char** endptr, int base)
{
usize val = 0;
while (_isspace(*str)) str++;
@ -80,9 +83,9 @@ usize _strtou(const char* str, const char** endptr, int base)
else if (base == 0)
base = 10;
while (valid_digit(base, *str))
while (is_valid_digit_for_base(base, *str))
{
val = (base * val) + to_digit(*str);
val = (base * val) + parse_digit_unchecked(*str);
str++;
}
@ -96,29 +99,6 @@ isize _strtoi(const char* str, const char** endptr, int base)
isize val = 0;
bool negative = false;
auto valid_digit = [](int _base, char c) -> bool {
if (_base <= 10)
{
if (!_isdigit(c)) return false;
if ((c - '0') < _base) return true;
return false;
}
else
{
if (!_isalnum(c)) return false;
if (_isdigit(c)) return true;
bool lower = _islower(c);
if (((c - lower ? 'a' : 'A') + 10) < _base) return true;
return false;
}
};
auto to_digit = [](char c) -> isize {
if (_isdigit(c)) return c - '0';
if (_islower(c)) return (c - 'a') + 10;
return (c - 'A') + 10;
};
while (_isspace(*str)) str++;
if (*str == '-' || *str == '+')
@ -141,9 +121,9 @@ isize _strtoi(const char* str, const char** endptr, int base)
else if (base == 0)
base = 10;
while (valid_digit(base, *str))
while (is_valid_digit_for_base(base, *str))
{
val = (base * val) + to_digit(*str);
val = (base * val) + parse_digit_unchecked(*str);
str++;
}