1 /* Convert decimal strings with bounds checking and exit on error.
3 Copyright (C) 2014-2015 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "xdectoint.h"
30 /* Parse numeric string N_STR of base BASE, and return the value.
31 Exit on parse error or if MIN or MAX are exceeded.
32 Strings can have multiplicative SUFFIXES if specified.
33 ERR is printed along with N_STR on error. */
36 __xnumtoint (const char *n_str
, int base
, __xdectoint_t min
, __xdectoint_t max
,
37 const char *suffixes
, const char *err
, int err_exit
)
42 s_err
= __xstrtol (n_str
, NULL
, base
, &tnum
, suffixes
);
44 if (s_err
== LONGINT_OK
)
46 if (tnum
< min
|| max
< tnum
)
48 s_err
= LONGINT_OVERFLOW
;
49 /* Use have the INT range as a heuristic to distinguish
50 type overflow rather than other min/max limits. */
53 #if __xdectoint_signed
54 else if (tnum
< INT_MIN
/2)
61 else if (s_err
== LONGINT_OVERFLOW
)
63 else if (s_err
== LONGINT_INVALID_SUFFIX_CHAR_WITH_OVERFLOW
)
64 errno
= 0; /* Don't show ERANGE errors for invalid numbers. */
66 if (s_err
!= LONGINT_OK
)
68 /* EINVAL error message is redundant in this context. */
69 error (err_exit
? err_exit
: EXIT_FAILURE
, errno
== EINVAL
? 0 : errno
,
70 "%s: %s", err
, quote (n_str
));
76 /* Parse decimal string N_STR, and return the value.
77 Exit on parse error or if MIN or MAX are exceeded.
78 Strings can have multiplicative SUFFIXES if specified.
79 ERR is printed along with N_STR on error. */
82 __xdectoint (const char *n_str
, __xdectoint_t min
, __xdectoint_t max
,
83 const char *suffixes
, const char *err
, int err_exit
)
85 return __xnumtoint (n_str
, 10, min
, max
, suffixes
, err
, err_exit
);