1 /* vi: set sw=4 ts=4: */
3 * xgetularg* implementations for busybox
5 * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
18 unsigned long bb_xgetularg_bnd_sfx(const char *arg, int base,
21 const struct suffix_mult *suffixes)
29 /* Disallow '-' and any leading whitespace. Speed isn't critical here
30 * since we're parsing commandline args. So make sure we get the
31 * actual isspace function rather than a larger macro implementaion. */
32 if ((*arg == '-') || (isspace)(*arg)) {
36 /* Since this is a lib function, we're not allowed to reset errno to 0.
37 * Doing so could break an app that is deferring checking of errno.
38 * So, save the old value so that we can restore it if successful. */
41 r = strtoul(arg, &e, base);
42 /* Do the initial validity check. Note: The standards do not
43 * guarantee that errno is set if no digits were found. So we
44 * must test for this explicitly. */
45 if (errno || (arg == e)) { /* error or no digits */
48 errno = old_errno; /* Ok. So restore errno. */
50 /* Do optional suffix parsing. Allow 'empty' suffix tables.
51 * Note that we also all nul suffixes with associated multipliers,
52 * to allow for scaling of the arg by some default multiplier. */
55 while (suffixes->suffix) {
56 if (strcmp(suffixes->suffix, e) == 0) {
57 if (ULONG_MAX / suffixes->mult < r) { /* Overflow! */
68 /* Finally, check for illegal trailing chars and range limits. */
69 /* Note: although we allow leading space (via stroul), trailing space
70 * is an error. It would be easy enough to allow though if desired. */
71 if (*e || (r < lower) || (r > upper)) {
78 long bb_xgetlarg_bnd_sfx(const char *arg, int base,
81 const struct suffix_mult *suffixes)
83 unsigned long u = LONG_MAX;
87 if ((*p == '-') && (p[1] != '+')) {
89 ++u; /* two's complement */
92 r = bb_xgetularg_bnd_sfx(p, base, 0, u, suffixes);
98 if ((r < lower) || (r > upper)) {
105 long bb_xgetlarg10_sfx(const char *arg, const struct suffix_mult *suffixes)
107 return bb_xgetlarg_bnd_sfx(arg, 10, LONG_MIN, LONG_MAX, suffixes);
110 unsigned long bb_xgetularg_bnd(const char *arg, int base,
114 return bb_xgetularg_bnd_sfx(arg, base, lower, upper, NULL);
117 unsigned long bb_xgetularg10_bnd(const char *arg,
121 return bb_xgetularg_bnd(arg, 10, lower, upper);
124 unsigned long bb_xgetularg10(const char *arg)
126 return bb_xgetularg10_bnd(arg, 0, ULONG_MAX);