File: c-strtod.c

package info (click to toggle)
coreutils 9.7-3
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 67,780 kB
  • sloc: ansic: 243,477; sh: 29,063; perl: 7,908; yacc: 1,858; makefile: 196; python: 47; sed: 16
file content (342 lines) | stat: -rw-r--r-- 10,674 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/* Convert string to floating-point number, using the C locale.

   Copyright (C) 2003-2004, 2006, 2009-2025 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */

/* Written by Paul Eggert and Bruno Haible.  */

#include <config.h>

#include "c-strtod.h"

#include <errno.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if FLOAT
# define C_STRTOD c_strtof
# define DOUBLE float
# define STRTOD_L strtof_l
# define HAVE_GOOD_STRTOD_L (HAVE_STRTOF_L && !GNULIB_defined_strtof_function)
# define STRTOD strtof
#elif LONG
# define C_STRTOD c_strtold
# define DOUBLE long double
# define STRTOD_L strtold_l
# define HAVE_GOOD_STRTOD_L (HAVE_STRTOLD_L && !GNULIB_defined_strtold_function)
# define STRTOD strtold
#else
# define C_STRTOD c_strtod
# define DOUBLE double
# define STRTOD_L strtod_l
# define HAVE_GOOD_STRTOD_L (HAVE_STRTOD_L && !GNULIB_defined_strtod_function)
# define STRTOD strtod
#endif

/* Here we don't need the newlocale override that supports gl_locale_name().  */
#undef newlocale

#if defined LC_ALL_MASK && (HAVE_GOOD_STRTOD_L || HAVE_WORKING_USELOCALE)

/* Cache for the C locale object.
   Marked volatile so that different threads see the same value
   (avoids locking).  */
static volatile locale_t c_locale_cache;

/* Return the C locale object, or (locale_t) 0 with errno set
   if it cannot be created.  */
static locale_t
c_locale (void)
{
  if (!c_locale_cache)
    c_locale_cache = newlocale (LC_ALL_MASK, "C", (locale_t) 0);
  return c_locale_cache;
}

#else

# if HAVE_NL_LANGINFO
#  include <langinfo.h>
# endif
# include "c-ctype.h"

/* Determine the decimal-point character according to the current locale.  */
static char
decimal_point_char (void)
{
  const char *point;
  /* Determine it in a multithread-safe way.  We know nl_langinfo is
     multithread-safe on glibc systems and Mac OS X systems, but is not required
     to be multithread-safe by POSIX.  sprintf(), however, is multithread-safe.
     localeconv() is rarely multithread-safe.  */
# if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
  point = nl_langinfo (RADIXCHAR);
# elif 1
  char pointbuf[5];
  sprintf (pointbuf, "%#.0f", 1.0);
  point = &pointbuf[1];
# else
  point = localeconv () -> decimal_point;
# endif
  /* The decimal point is always a single byte: either '.' or ','.  */
  return (point[0] != '\0' ? point[0] : '.');
}

#endif

DOUBLE
C_STRTOD (char const *nptr, char **endptr)
{
  DOUBLE r;

#if defined LC_ALL_MASK && (HAVE_GOOD_STRTOD_L || HAVE_WORKING_USELOCALE)

  locale_t locale = c_locale ();
  if (!locale)
    {
      if (endptr)
        *endptr = (char *) nptr;
      return 0; /* errno is set here */
    }

# if HAVE_GOOD_STRTOD_L

  r = STRTOD_L (nptr, endptr, locale);

# else /* HAVE_WORKING_USELOCALE */

  locale_t old_locale = uselocale (locale);
  if (old_locale == (locale_t)0)
    {
      if (endptr)
        *endptr = (char *) nptr;
      return 0; /* errno is set here */
    }

  r = STRTOD (nptr, endptr);

  int saved_errno = errno;
  if (uselocale (old_locale) == (locale_t)0)
    /* We can't switch back to the old locale.  The thread is hosed.  */
    abort ();
  errno = saved_errno;

# endif

#else

  char decimal_point = decimal_point_char ();

  if (decimal_point == '.')
    /* In this locale, C_STRTOD and STRTOD behave the same way.  */
    r = STRTOD (nptr, endptr);
  else
    {
      /* Start and end of the floating-point number.  */
      char const *start;
      char const *end;
      /* Position of the decimal point '.' in the floating-point number.
         Either decimal_point_p == NULL or start <= decimal_point_p < end.  */
      char const *decimal_point_p = NULL;
      /* Set to true if we encountered decimal_point while parsing.  */
      int seen_decimal_point = 0;

      /* Parse
         1. a sequence of white-space characters,
         2. a subject sequence possibly containing a floating-point number,
         as described in POSIX
         <https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtod.html>.
       */
      {
        char const *p;

        p = nptr;

        /* Parse a sequence of white-space characters.  */
        while (*p != '\0' && c_isspace ((unsigned char) *p))
          p++;
        start = p;
        end = p;

        /* Start to parse a subject sequence.  */
        if (*p == '+' || *p == '-')
          p++;
        if (*p == '0')
          {
            end = p + 1;
            if (p[1] == 'x' || p[1] == 'X')
              {
                size_t num_hex_digits = 0;
                p += 2;
                /* Parse a non-empty sequence of hexadecimal digits optionally
                   containing the decimal point character '.'.  */
                while (*p != '\0')
                  {
                    if (c_isxdigit ((unsigned char) *p))
                      {
                        num_hex_digits++;
                        p++;
                      }
                    else if (*p == '.')
                      {
                        if (decimal_point_p == NULL)
                          {
                            decimal_point_p = p;
                            p++;
                          }
                        else
                          break;
                      }
                    else
                      break;
                  }
                seen_decimal_point = (*p == decimal_point);
                if (num_hex_digits > 0)
                  {
                    end = p;
                    /* Parse the character 'p' or the character 'P', optionally
                       followed by a '+' or '-' character, and then followed by
                       one or more decimal digits.  */
                    if (*p == 'p' || *p == 'P')
                      {
                        p++;
                        if (*p == '+' || *p == '-')
                          p++;
                        if (*p != '\0' && c_isdigit ((unsigned char) *p))
                          {
                            p++;
                            while (*p != '\0' && c_isdigit ((unsigned char) *p))
                              p++;
                            end = p;
                          }
                      }
                  }
                else
                  decimal_point_p = NULL;
                goto done_parsing;
              }
          }
        {
          size_t num_digits = 0;
          /* Parse a non-empty sequence of decimal digits optionally containing
             the decimal point character '.'.  */
          while (*p != '\0')
            {
              if (c_isdigit ((unsigned char) *p))
                {
                  num_digits++;
                  p++;
                }
              else if (*p == '.')
                {
                  if (decimal_point_p == NULL)
                    {
                      decimal_point_p = p;
                      p++;
                    }
                  else
                    break;
                }
              else
                break;
            }
          seen_decimal_point = (*p == decimal_point);
          if (num_digits > 0)
            {
              end = p;
              /* Parse the character 'e' or the character 'E', optionally
                 followed by a '+' or '-' character, and then followed by one or
                 more decimal digits.  */
              if (*p == 'e' || *p == 'E')
                {
                  p++;
                  if (*p == '+' || *p == '-')
                    p++;
                  if (*p != '\0' && c_isdigit ((unsigned char) *p))
                    {
                      p++;
                      while (*p != '\0' && c_isdigit ((unsigned char) *p))
                        p++;
                      end = p;
                    }
                }
            }
          else
            decimal_point_p = NULL;
        }
      }
     done_parsing:
      if (end == start || (decimal_point_p == NULL && !seen_decimal_point))
        /* If end == start, we have not parsed anything.  The given string
           might be "INF", "INFINITY", "NAN", "NAN(chars)", or invalid.
           We can pass it to STRTOD.
           If end > start and decimal_point_p == NULL, we have parsed a
           floating-point number, and it does not have a '.' (and not a ','
           either, of course).  If !seen_decimal_point, we did not
           encounter decimal_point while parsing.  In this case, the
           locale-dependent STRTOD function can handle it.  */
        r = STRTOD (nptr, endptr);
      else
        {
          /* Create a modified floating-point number, in which the character '.'
             is replaced with the locale-dependent decimal_point.  */
          size_t len = end - start;
          char *buf;
          char *buf_malloced = NULL;
          char stackbuf[1000];
          char *end_in_buf;

          if (len < sizeof (stackbuf))
            buf = stackbuf;
          else
            {
              buf = malloc (len + 1);
              if (buf == NULL)
                {
                  /* Out of memory.
                     Callers may not be prepared to see errno == ENOMEM.  But
                     they should be prepared to see errno == EINVAL.  */
                  errno = EINVAL;
                  if (endptr != NULL)
                    *endptr = (char *) nptr;
                  return 0;
                }
              buf_malloced = buf;
            }

          memcpy (buf, start, len);
          if (decimal_point_p != NULL)
            buf[decimal_point_p - start] = decimal_point;
          buf[len] = '\0';

          r = STRTOD (buf, &end_in_buf);
          if (endptr != NULL)
            *endptr = (char *) (start + (end_in_buf - buf));

          if (buf_malloced != NULL)
            {
              int saved_errno = errno;
              free (buf_malloced);
              errno = saved_errno;
            }
        }
    }

#endif

  return r;
}