1 | /* error-checking interface to strtod-like functions
|
---|
2 |
|
---|
3 | Copyright (C) 1996, 1999, 2000, 2003, 2004, 2005, 2006 Free
|
---|
4 | Software Foundation, Inc.
|
---|
5 |
|
---|
6 | This program is free software; you can redistribute it and/or modify
|
---|
7 | it under the terms of the GNU General Public License as published by
|
---|
8 | the Free Software Foundation; either version 2, or (at your option)
|
---|
9 | any later version.
|
---|
10 |
|
---|
11 | This program is distributed in the hope that it will be useful,
|
---|
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
14 | GNU General Public License for more details.
|
---|
15 |
|
---|
16 | You should have received a copy of the GNU General Public License
|
---|
17 | along with this program; if not, write to the Free Software Foundation,
|
---|
18 | Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
|
---|
19 |
|
---|
20 | /* Written by Jim Meyering. */
|
---|
21 |
|
---|
22 | #include <config.h>
|
---|
23 |
|
---|
24 | #include "xstrtod.h"
|
---|
25 |
|
---|
26 | #include <errno.h>
|
---|
27 | #include <limits.h>
|
---|
28 | #include <stdio.h>
|
---|
29 |
|
---|
30 | #if LONG
|
---|
31 | # define XSTRTOD xstrtold
|
---|
32 | # define DOUBLE long double
|
---|
33 | #else
|
---|
34 | # define XSTRTOD xstrtod
|
---|
35 | # define DOUBLE double
|
---|
36 | #endif
|
---|
37 |
|
---|
38 | /* An interface to a string-to-floating-point conversion function that
|
---|
39 | encapsulates all the error checking one should usually perform.
|
---|
40 | Like strtod/strtold, but upon successful
|
---|
41 | conversion put the result in *RESULT and return true. Return
|
---|
42 | false and don't modify *RESULT upon any failure. CONVERT
|
---|
43 | specifies the conversion function, e.g., strtod itself. */
|
---|
44 |
|
---|
45 | bool
|
---|
46 | XSTRTOD (char const *str, char const **ptr, DOUBLE *result,
|
---|
47 | DOUBLE (*convert) (char const *, char **))
|
---|
48 | {
|
---|
49 | DOUBLE val;
|
---|
50 | char *terminator;
|
---|
51 | bool ok = true;
|
---|
52 |
|
---|
53 | errno = 0;
|
---|
54 | val = convert (str, &terminator);
|
---|
55 |
|
---|
56 | /* Having a non-zero terminator is an error only when PTR is NULL. */
|
---|
57 | if (terminator == str || (ptr == NULL && *terminator != '\0'))
|
---|
58 | ok = false;
|
---|
59 | else
|
---|
60 | {
|
---|
61 | /* Allow underflow (in which case CONVERT returns zero),
|
---|
62 | but flag overflow as an error. */
|
---|
63 | if (val != 0 && errno == ERANGE)
|
---|
64 | ok = false;
|
---|
65 | }
|
---|
66 |
|
---|
67 | if (ptr != NULL)
|
---|
68 | *ptr = terminator;
|
---|
69 |
|
---|
70 | *result = val;
|
---|
71 | return ok;
|
---|
72 | }
|
---|