tool_paramhlp: simplify number parsing

Closes #20134
This commit is contained in:
Daniel Stenberg 2025-12-31 18:17:15 +01:00
parent 1ca678472f
commit c7b26b6679
No known key found for this signature in database
GPG key ID: 5CC908FDB71E12C2

View file

@ -203,47 +203,39 @@ ParameterError file2memory(char **bufp, size_t *size, FILE *file)
* getparameter a lot, we must check it for NULL before accessing the str * getparameter a lot, we must check it for NULL before accessing the str
* data. * data.
*/ */
static ParameterError getnum(long *val, const char *str, int base)
{
DEBUGASSERT((base == 8) || (base == 10));
if(str) {
curl_off_t num;
bool is_neg = FALSE;
if(base == 10) {
is_neg = (*str == '-');
if(is_neg)
str++;
if(curlx_str_number(&str, &num, LONG_MAX))
return PARAM_BAD_NUMERIC;
}
else { /* base == 8 */
if(curlx_str_octal(&str, &num, LONG_MAX))
return PARAM_BAD_NUMERIC;
}
if(!curlx_str_single(&str, '\0')) {
*val = (long)num;
if(is_neg)
*val = -*val;
return PARAM_OK; /* Ok */
}
}
return PARAM_BAD_NUMERIC; /* badness */
}
ParameterError str2num(long *val, const char *str) ParameterError str2num(long *val, const char *str)
{ {
return getnum(val, str, 10); curl_off_t num;
bool is_neg = FALSE;
DEBUGASSERT(str);
if(!curlx_str_single(&str, '-'))
is_neg = TRUE;
if(curlx_str_number(&str, &num, LONG_MAX) ||
curlx_str_single(&str, '\0'))
return PARAM_BAD_NUMERIC; /* badness */
*val = (long)num;
if(is_neg)
*val = -*val;
return PARAM_OK; /* Ok */
} }
ParameterError oct2nummax(long *val, const char *str, long max) ParameterError oct2nummax(long *val, const char *str, long max)
{ {
ParameterError result = getnum(val, str, 8); curl_off_t num;
if(result != PARAM_OK) int rc;
return result; DEBUGASSERT(str);
else if(*val > max) rc = curlx_str_octal(&str, &num, max);
return PARAM_NUMBER_TOO_LARGE; if(rc) {
else if(*val < 0) if(STRE_OVERFLOW == rc)
return PARAM_NUMBER_TOO_LARGE;
return PARAM_BAD_NUMERIC;
}
if(curlx_str_single(&str, '\0'))
return PARAM_BAD_NUMERIC;
if(num < 0)
return PARAM_NEGATIVE_NUMERIC; return PARAM_NEGATIVE_NUMERIC;
*val = (long)num;
return PARAM_OK; return PARAM_OK;
} }
@ -259,7 +251,7 @@ ParameterError oct2nummax(long *val, const char *str, long max)
ParameterError str2unum(long *val, const char *str) ParameterError str2unum(long *val, const char *str)
{ {
ParameterError result = getnum(val, str, 10); ParameterError result = str2num(val, str);
if(result != PARAM_OK) if(result != PARAM_OK)
return result; return result;
if(*val < 0) if(*val < 0)