iucode_tool: add two command-line parser helpers

Add two command-line parser helpers:
 * cmdline_get_int() to parse integer parameters;
 * cmdline_get_enumstr() to parse named parameters;

The helpers work with the notion of a default value which is left
untouched when arg is null (so they handle an optional arg) or when
parsing fails.
parent 3d05f5b9
......@@ -3114,6 +3114,55 @@ static int cmdline_get_date(const char *arg, uint32_t *d)
return 0;
}
static int cmdline_get_int(const char *arg, int pmin, int pmax, int *d)
{
char *p;
long int l;
if (!arg)
return 0;
errno = 0;
l = strtol(arg, &p, 10);
if (errno || p == arg)
return errno ? errno : EINVAL;
if (l > INT32_MAX || l < INT32_MIN)
return ERANGE;
if (l < pmin || l > pmax)
return EINVAL;
while (isspace(*p))
p++;
if (*p)
return EINVAL;
if (d)
*d = (int) l;
return 0;
}
/* note: does not tolerate trailing blanks */
static int cmdline_get_enumstr(const char *arg, const char * const table[],
int *d)
{
int r = 0;
if (!arg || !table)
return 0;
while (table[r]) {
if (!strcasecmp(arg, table[r])) {
if (d)
*d = r;
return 0;
}
r++;
}
return ENOENT;
}
static error_t cmdline_do_parse_arg(int key, char *arg,
struct argp_state *state)
{
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment