| 1 |
/*------------------------------------------------------------------------- |
| 2 |
* |
| 3 |
* strtof.c |
| 4 |
* |
| 5 |
* Portions Copyright (c) 2019-2025, PostgreSQL Global Development Group |
| 6 |
* |
| 7 |
* |
| 8 |
* IDENTIFICATION |
| 9 |
* src/port/strtof.c |
| 10 |
* |
| 11 |
*------------------------------------------------------------------------- |
| 12 |
*/ |
| 13 |
|
| 14 |
#include "c.h" |
| 15 |
|
| 16 |
#include <float.h> |
| 17 |
#include <math.h> |
| 18 |
|
| 19 |
|
| 20 |
/* |
| 21 |
* Cygwin has a strtof() which is literally just (float)strtod(), which means |
| 22 |
* we can't avoid the double-rounding problem; but using this wrapper does get |
| 23 |
* us proper over/underflow checks. (Also, if they fix their strtof(), the |
| 24 |
* wrapper doesn't break anything.) |
| 25 |
* |
| 26 |
* Test results on Mingw suggest that it has the same problem, though looking |
| 27 |
* at the code I can't figure out why. |
| 28 |
*/ |
| 29 |
float |
| 30 |
pg_strtof(const char *nptr, char **endptr) |
| 31 |
{ |
| 32 |
int caller_errno = errno; |
| 33 |
float fresult; |
| 34 |
char *myendptr; |
| 35 |
|
| 36 |
errno = 0; |
| 37 |
fresult = (strtof) (nptr, &myendptr); |
| 38 |
if (endptr) |
| 39 |
*endptr = myendptr; |
| 40 |
if (errno) |
| 41 |
{ |
| 42 |
/* On error, just return the error to the caller. */ |
| 43 |
return fresult; |
| 44 |
} |
| 45 |
else if ((myendptr == nptr) || isnan(fresult) || |
| 46 |
((fresult >= FLT_MIN || fresult <= -FLT_MIN) && !isinf(fresult))) |
| 47 |
{ |
| 48 |
/* |
| 49 |
* If we got nothing parseable, or if we got a non-0 non-subnormal |
| 50 |
* finite value (or NaN) without error, then return that to the caller |
| 51 |
* without error. |
| 52 |
*/ |
| 53 |
errno = caller_errno; |
| 54 |
return fresult; |
| 55 |
} |
| 56 |
else |
| 57 |
{ |
| 58 |
/* |
| 59 |
* Try again. errno is already 0 here, and we assume that the endptr |
| 60 |
* won't be any different. |
| 61 |
*/ |
| 62 |
double dresult = strtod(nptr, NULL); |
| 63 |
|
| 64 |
if (errno) |
| 65 |
{ |
| 66 |
/* On error, just return the error */ |
| 67 |
return fresult; |
| 68 |
} |
| 69 |
else if ((dresult == 0.0 && fresult == 0.0) || |
| 70 |
(isinf(dresult) && isinf(fresult) && (fresult == dresult))) |
| 71 |
{ |
| 72 |
/* both values are 0 or infinities of the same sign */ |
| 73 |
errno = caller_errno; |
| 74 |
return fresult; |
| 75 |
} |
| 76 |
else if ((dresult > 0 && dresult <= FLT_MIN && (float) dresult != 0.0) || |
| 77 |
(dresult < 0 && dresult >= -FLT_MIN && (float) dresult != 0.0)) |
| 78 |
{ |
| 79 |
/* subnormal but nonzero value */ |
| 80 |
errno = caller_errno; |
| 81 |
return (float) dresult; |
| 82 |
} |
| 83 |
else |
| 84 |
{ |
| 85 |
errno = ERANGE; |
| 86 |
return fresult; |
| 87 |
} |
| 88 |
} |
| 89 |
} |