Wrapper around strtod.c to compile as strtof_l.
[glibc/history.git] / stdlib / strtod.c
blob5ddb956081805392891edb90ceef34da2921e70a
1 /* Read decimal floating point numbers.
2 This file is part of the GNU C Library.
3 Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc.
4 Contributed by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public License as
8 published by the Free Software Foundation; either version 2 of the
9 License, or (at your option) any later version.
11 The GNU C Library 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 GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 /* Configuration part. These macros are defined by `strtold.c',
22 `strtof.c', `wcstod.c', `wcstold.c', and `wcstof.c' to produce the
23 `long double' and `float' versions of the reader. */
24 #ifndef FLOAT
25 # define FLOAT double
26 # define FLT DBL
27 # ifdef USE_WIDE_CHAR
28 # ifdef USE_IN_EXTENDED_LOCALE_MODEL
29 # define STRTOF __wcstod_l
30 # else
31 # define STRTOF wcstod
32 # endif
33 # else
34 # ifdef USE_IN_EXTENDED_LOCALE_MODEL
35 # define STRTOF __strtod_l
36 # else
37 # define STRTOF strtod
38 # endif
39 # endif
40 # define MPN2FLOAT __mpn_construct_double
41 # define FLOAT_HUGE_VAL HUGE_VAL
42 # define SET_MANTISSA(flt, mant) \
43 do { union ieee754_double u; \
44 u.d = (flt); \
45 if ((mant & 0xfffffffffffffULL) == 0) \
46 mant = 0x8000000000000ULL; \
47 u.ieee.mantissa0 = ((mant) >> 32) & 0xfffff; \
48 u.ieee.mantissa1 = (mant) & 0xffffffff; \
49 } while (0)
50 #endif
51 /* End of configuration part. */
53 #include <ctype.h>
54 #include <errno.h>
55 #include <float.h>
56 #include <ieee754.h>
57 #include "../locale/localeinfo.h"
58 #include <math.h>
59 #include <stdlib.h>
60 #include <string.h>
62 /* The gmp headers need some configuration frobs. */
63 #define HAVE_ALLOCA 1
65 #include "gmp.h"
66 #include "gmp-impl.h"
67 #include <gmp-mparam.h>
68 #include "longlong.h"
69 #include "fpioconst.h"
71 #define NDEBUG 1
72 #include <assert.h>
75 /* We use this code also for the extended locale handling where the
76 function gets as an additional argument the locale which has to be
77 used. To access the values we have to redefine the _NL_CURRENT
78 macro. */
79 #ifdef USE_IN_EXTENDED_LOCALE_MODEL
80 # undef _NL_CURRENT
81 # define _NL_CURRENT(category, item) \
82 (current->values[_NL_ITEM_INDEX (item)].string)
83 # define LOCALE_PARAM , loc
84 # define LOCALE_PARAM_DECL __locale_t loc;
85 #else
86 # define LOCALE_PARAM
87 # define LOCALE_PARAM_DECL
88 #endif
91 #ifdef USE_WIDE_CHAR
92 # include <wctype.h>
93 # include <wchar.h>
94 # define STRING_TYPE wchar_t
95 # define CHAR_TYPE wint_t
96 # define L_(Ch) L##Ch
97 # ifdef USE_IN_EXTENDED_LOCALE_MODEL
98 # define ISSPACE(Ch) __iswspace_l ((Ch), loc)
99 # define ISDIGIT(Ch) __iswdigit_l ((Ch), loc)
100 # define ISXDIGIT(Ch) __iswxdigit_l ((Ch), loc)
101 # define TOLOWER(Ch) __towlower_l ((Ch), loc)
102 # define STRNCASECMP(S1, S2, N) __wcsncasecmp_l ((S1), (S2), (N), loc)
103 # define STRTOULL(S, E, B) __wcstoull_l ((S), (E), (B), loc)
104 # else
105 # define ISSPACE(Ch) iswspace (Ch)
106 # define ISDIGIT(Ch) iswdigit (Ch)
107 # define ISXDIGIT(Ch) iswxdigit (Ch)
108 # define TOLOWER(Ch) towlower (Ch)
109 # define STRNCASECMP(S1, S2, N) __wcsncasecmp ((S1), (S2), (N))
110 # define STRTOULL(S, E, B) wcstoull ((S), (E), (B))
111 # endif
112 #else
113 # define STRING_TYPE char
114 # define CHAR_TYPE char
115 # define L_(Ch) Ch
116 # ifdef USE_IN_EXTENDED_LOCALE_MODEL
117 # define ISSPACE(Ch) __isspace_l ((Ch), loc)
118 # define ISDIGIT(Ch) __isdigit_l ((Ch), loc)
119 # define ISXDIGIT(Ch) __isxdigit_l ((Ch), loc)
120 # define TOLOWER(Ch) __tolower_l ((Ch), loc)
121 # define STRNCASECMP(S1, S2, N) __strncasecmp_l ((S1), (S2), (N), loc)
122 # define STRTOULL(S, E, B) __strtoull_l ((S), (E), (B), loc)
123 # else
124 # define ISSPACE(Ch) isspace (Ch)
125 # define ISDIGIT(Ch) isdigit (Ch)
126 # define ISXDIGIT(Ch) isxdigit (Ch)
127 # define TOLOWER(Ch) tolower (Ch)
128 # define STRNCASECMP(S1, S2, N) __strncasecmp ((S1), (S2), (N))
129 # define STRTOULL(S, E, B) strtoull ((S), (E), (B))
130 # endif
131 #endif
134 /* Constants we need from float.h; select the set for the FLOAT precision. */
135 #define MANT_DIG PASTE(FLT,_MANT_DIG)
136 #define DIG PASTE(FLT,_DIG)
137 #define MAX_EXP PASTE(FLT,_MAX_EXP)
138 #define MIN_EXP PASTE(FLT,_MIN_EXP)
139 #define MAX_10_EXP PASTE(FLT,_MAX_10_EXP)
140 #define MIN_10_EXP PASTE(FLT,_MIN_10_EXP)
142 /* Extra macros required to get FLT expanded before the pasting. */
143 #define PASTE(a,b) PASTE1(a,b)
144 #define PASTE1(a,b) a##b
146 /* Function to construct a floating point number from an MP integer
147 containing the fraction bits, a base 2 exponent, and a sign flag. */
148 extern FLOAT MPN2FLOAT (mp_srcptr mpn, int exponent, int negative);
150 /* Definitions according to limb size used. */
151 #if BITS_PER_MP_LIMB == 32
152 # define MAX_DIG_PER_LIMB 9
153 # define MAX_FAC_PER_LIMB 1000000000UL
154 #elif BITS_PER_MP_LIMB == 64
155 # define MAX_DIG_PER_LIMB 19
156 # define MAX_FAC_PER_LIMB 10000000000000000000UL
157 #else
158 # error "mp_limb_t size " BITS_PER_MP_LIMB "not accounted for"
159 #endif
162 /* Local data structure. */
163 static const mp_limb_t _tens_in_limb[MAX_DIG_PER_LIMB + 1] =
164 { 0, 10, 100,
165 1000, 10000, 100000,
166 1000000, 10000000, 100000000,
167 1000000000
168 #if BITS_PER_MP_LIMB > 32
169 , 10000000000U, 100000000000U,
170 1000000000000U, 10000000000000U, 100000000000000U,
171 1000000000000000U, 10000000000000000U, 100000000000000000U,
172 1000000000000000000U, 10000000000000000000U
173 #endif
174 #if BITS_PER_MP_LIMB > 64
175 #error "Need to expand tens_in_limb table to" MAX_DIG_PER_LIMB
176 #endif
179 #ifndef howmany
180 #define howmany(x,y) (((x)+((y)-1))/(y))
181 #endif
182 #define SWAP(x, y) ({ typeof(x) _tmp = x; x = y; y = _tmp; })
184 #define NDIG (MAX_10_EXP - MIN_10_EXP + 2 * MANT_DIG)
185 #define HEXNDIG ((MAX_EXP - MIN_EXP + 7) / 8 + 2 * MANT_DIG)
186 #define RETURN_LIMB_SIZE howmany (MANT_DIG, BITS_PER_MP_LIMB)
188 #define RETURN(val,end) \
189 do { if (endptr != NULL) *endptr = (STRING_TYPE *) (end); \
190 return val; } while (0)
192 /* Maximum size necessary for mpn integers to hold floating point numbers. */
193 #define MPNSIZE (howmany (MAX_EXP + 2 * MANT_DIG, BITS_PER_MP_LIMB) \
194 + 2)
195 /* Declare an mpn integer variable that big. */
196 #define MPN_VAR(name) mp_limb_t name[MPNSIZE]; mp_size_t name##size
197 /* Copy an mpn integer value. */
198 #define MPN_ASSIGN(dst, src) \
199 memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
202 /* Return a floating point number of the needed type according to the given
203 multi-precision number after possible rounding. */
204 static inline FLOAT
205 round_and_return (mp_limb_t *retval, int exponent, int negative,
206 mp_limb_t round_limb, mp_size_t round_bit, int more_bits)
208 if (exponent < MIN_EXP - 1)
210 mp_size_t shift = MIN_EXP - 1 - exponent;
212 if (shift > MANT_DIG)
214 __set_errno (EDOM);
215 return 0.0;
218 more_bits |= (round_limb & ((((mp_limb_t) 1) << round_bit) - 1)) != 0;
219 if (shift == MANT_DIG)
220 /* This is a special case to handle the very seldom case where
221 the mantissa will be empty after the shift. */
223 int i;
225 round_limb = retval[RETURN_LIMB_SIZE - 1];
226 round_bit = BITS_PER_MP_LIMB - 1;
227 for (i = 0; i < RETURN_LIMB_SIZE; ++i)
228 more_bits |= retval[i] != 0;
229 MPN_ZERO (retval, RETURN_LIMB_SIZE);
231 else if (shift >= BITS_PER_MP_LIMB)
233 int i;
235 round_limb = retval[(shift - 1) / BITS_PER_MP_LIMB];
236 round_bit = (shift - 1) % BITS_PER_MP_LIMB;
237 for (i = 0; i < (shift - 1) / BITS_PER_MP_LIMB; ++i)
238 more_bits |= retval[i] != 0;
239 more_bits |= ((round_limb & ((((mp_limb_t) 1) << round_bit) - 1))
240 != 0);
242 (void) __mpn_rshift (retval, &retval[shift / BITS_PER_MP_LIMB],
243 RETURN_LIMB_SIZE - (shift / BITS_PER_MP_LIMB),
244 shift % BITS_PER_MP_LIMB);
245 MPN_ZERO (&retval[RETURN_LIMB_SIZE - (shift / BITS_PER_MP_LIMB)],
246 shift / BITS_PER_MP_LIMB);
248 else if (shift > 0)
250 round_limb = retval[0];
251 round_bit = shift - 1;
252 (void) __mpn_rshift (retval, retval, RETURN_LIMB_SIZE, shift);
254 exponent = MIN_EXP - 2;
257 if ((round_limb & (((mp_limb_t) 1) << round_bit)) != 0
258 && (more_bits || (retval[0] & 1) != 0
259 || (round_limb & ((((mp_limb_t) 1) << round_bit) - 1)) != 0))
261 mp_limb_t cy = __mpn_add_1 (retval, retval, RETURN_LIMB_SIZE, 1);
263 if (((MANT_DIG % BITS_PER_MP_LIMB) == 0 && cy) ||
264 ((MANT_DIG % BITS_PER_MP_LIMB) != 0 &&
265 (retval[RETURN_LIMB_SIZE - 1]
266 & (((mp_limb_t) 1) << (MANT_DIG % BITS_PER_MP_LIMB))) != 0))
268 ++exponent;
269 (void) __mpn_rshift (retval, retval, RETURN_LIMB_SIZE, 1);
270 retval[RETURN_LIMB_SIZE - 1]
271 |= ((mp_limb_t) 1) << ((MANT_DIG - 1) % BITS_PER_MP_LIMB);
273 else if (exponent == MIN_EXP - 2
274 && (retval[RETURN_LIMB_SIZE - 1]
275 & (((mp_limb_t) 1) << ((MANT_DIG - 1) % BITS_PER_MP_LIMB)))
276 != 0)
277 /* The number was denormalized but now normalized. */
278 exponent = MIN_EXP - 1;
281 if (exponent > MAX_EXP)
282 return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
284 return MPN2FLOAT (retval, exponent, negative);
288 /* Read a multi-precision integer starting at STR with exactly DIGCNT digits
289 into N. Return the size of the number limbs in NSIZE at the first
290 character od the string that is not part of the integer as the function
291 value. If the EXPONENT is small enough to be taken as an additional
292 factor for the resulting number (see code) multiply by it. */
293 static inline const STRING_TYPE *
294 str_to_mpn (const STRING_TYPE *str, int digcnt, mp_limb_t *n, mp_size_t *nsize,
295 int *exponent)
297 /* Number of digits for actual limb. */
298 int cnt = 0;
299 mp_limb_t low = 0;
300 mp_limb_t start;
302 *nsize = 0;
303 assert (digcnt > 0);
306 if (cnt == MAX_DIG_PER_LIMB)
308 if (*nsize == 0)
309 n[0] = low;
310 else
312 mp_limb_t cy;
313 cy = __mpn_mul_1 (n, n, *nsize, MAX_FAC_PER_LIMB);
314 cy += __mpn_add_1 (n, n, *nsize, low);
315 if (cy != 0)
316 n[*nsize] = cy;
318 ++(*nsize);
319 cnt = 0;
320 low = 0;
323 /* There might be thousands separators or radix characters in
324 the string. But these all can be ignored because we know the
325 format of the number is correct and we have an exact number
326 of characters to read. */
327 while (*str < L_('0') || *str > L_('9'))
328 ++str;
329 low = low * 10 + *str++ - L_('0');
330 ++cnt;
332 while (--digcnt > 0);
334 if (*exponent > 0 && cnt + *exponent <= MAX_DIG_PER_LIMB)
336 low *= _tens_in_limb[*exponent];
337 start = _tens_in_limb[cnt + *exponent];
338 *exponent = 0;
340 else
341 start = _tens_in_limb[cnt];
343 if (*nsize == 0)
345 n[0] = low;
346 *nsize = 1;
348 else
350 mp_limb_t cy;
351 cy = __mpn_mul_1 (n, n, *nsize, start);
352 cy += __mpn_add_1 (n, n, *nsize, low);
353 if (cy != 0)
354 n[(*nsize)++] = cy;
357 return str;
361 /* Shift {PTR, SIZE} COUNT bits to the left, and fill the vacated bits
362 with the COUNT most significant bits of LIMB.
364 Tege doesn't like this function so I have to write it here myself. :)
365 --drepper */
366 static inline void
367 __mpn_lshift_1 (mp_limb_t *ptr, mp_size_t size, unsigned int count,
368 mp_limb_t limb)
370 if (count == BITS_PER_MP_LIMB)
372 /* Optimize the case of shifting by exactly a word:
373 just copy words, with no actual bit-shifting. */
374 mp_size_t i;
375 for (i = size - 1; i > 0; --i)
376 ptr[i] = ptr[i - 1];
377 ptr[0] = limb;
379 else
381 (void) __mpn_lshift (ptr, ptr, size, count);
382 ptr[0] |= limb >> (BITS_PER_MP_LIMB - count);
387 #define INTERNAL(x) INTERNAL1(x)
388 #define INTERNAL1(x) __##x##_internal
390 /* This file defines a function to check for correct grouping. */
391 #include "grouping.h"
394 /* Return a floating point number with the value of the given string NPTR.
395 Set *ENDPTR to the character after the last used one. If the number is
396 smaller than the smallest representable number, set `errno' to ERANGE and
397 return 0.0. If the number is too big to be represented, set `errno' to
398 ERANGE and return HUGE_VAL with the appropriate sign. */
399 FLOAT
400 INTERNAL (STRTOF) (nptr, endptr, group LOCALE_PARAM)
401 const STRING_TYPE *nptr;
402 STRING_TYPE **endptr;
403 int group;
404 LOCALE_PARAM_DECL
406 int negative; /* The sign of the number. */
407 MPN_VAR (num); /* MP representation of the number. */
408 int exponent; /* Exponent of the number. */
410 /* Numbers starting `0X' or `0x' have to be processed with base 16. */
411 int base = 10;
413 /* When we have to compute fractional digits we form a fraction with a
414 second multi-precision number (and we sometimes need a second for
415 temporary results). */
416 MPN_VAR (den);
418 /* Representation for the return value. */
419 mp_limb_t retval[RETURN_LIMB_SIZE];
420 /* Number of bits currently in result value. */
421 int bits;
423 /* Running pointer after the last character processed in the string. */
424 const STRING_TYPE *cp, *tp;
425 /* Start of significant part of the number. */
426 const STRING_TYPE *startp, *start_of_digits;
427 /* Points at the character following the integer and fractional digits. */
428 const STRING_TYPE *expp;
429 /* Total number of digit and number of digits in integer part. */
430 int dig_no, int_no, lead_zero;
431 /* Contains the last character read. */
432 CHAR_TYPE c;
434 /* We should get wint_t from <stddef.h>, but not all GCC versions define it
435 there. So define it ourselves if it remains undefined. */
436 #ifndef _WINT_T
437 typedef unsigned int wint_t;
438 #endif
439 /* The radix character of the current locale. */
440 wchar_t decimal;
441 /* The thousands character of the current locale. */
442 wchar_t thousands;
443 /* The numeric grouping specification of the current locale,
444 in the format described in <locale.h>. */
445 const char *grouping;
447 #ifdef USE_IN_EXTENDED_LOCALE_MODEL
448 struct locale_data *current = loc->__locales[LC_NUMERIC];
449 #endif
451 if (group)
453 grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
454 if (*grouping <= 0 || *grouping == CHAR_MAX)
455 grouping = NULL;
456 else
458 /* Figure out the thousands separator character. */
459 if (mbtowc (&thousands, _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP),
460 strlen (_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP))) <= 0)
461 thousands = (wchar_t) *_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
462 if (thousands == L'\0')
463 grouping = NULL;
466 else
468 grouping = NULL;
469 thousands = L'\0';
472 /* Find the locale's decimal point character. */
473 if (mbtowc ((wchar_t *) &decimal, _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT),
474 strlen (_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT))) <= 0)
475 decimal = (wchar_t) *_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
476 assert (decimal != L'\0');
478 /* Prepare number representation. */
479 exponent = 0;
480 negative = 0;
481 bits = 0;
483 /* Parse string to get maximal legal prefix. We need the number of
484 characters of the integer part, the fractional part and the exponent. */
485 cp = nptr - 1;
486 /* Ignore leading white space. */
488 c = *++cp;
489 while (ISSPACE (c));
491 /* Get sign of the result. */
492 if (c == L_('-'))
494 negative = 1;
495 c = *++cp;
497 else if (c == L_('+'))
498 c = *++cp;
500 /* Return 0.0 if no legal string is found.
501 No character is used even if a sign was found. */
502 if ((c < L_('0') || c > L_('9'))
503 && ((wchar_t) c != decimal || cp[1] < L_('0') || cp[1] > L_('9')))
505 int matched = 0;
506 /* Check for `INF' or `INFINITY'. */
507 if (TOLOWER (c) == L_('i') && ((STRNCASECMP (cp, L_("nf"), 2) == 0
508 && (matched = 2))
509 || (STRNCASECMP (cp, L_("nfinity"), 7)
510 == 0
511 && (matched = 7))))
513 /* Return +/- inifity. */
514 if (endptr != NULL)
515 *endptr = (STRING_TYPE *) (cp + matched);
517 return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
520 if (TOLOWER (c) == L_('n') && STRNCASECMP (cp, L_("an"), 2) == 0)
522 FLOAT retval = NAN;
524 /* Return NaN. */
525 if (endptr != NULL)
527 cp += 2;
529 /* Match `(n-char-sequence-digit)'. */
530 if (*cp == L_('('))
532 const STRING_TYPE *startp = cp;
534 ++cp;
535 while ((*cp >= '0' && *cp <= '9')
536 || (TOLOWER (*cp) >= 'a' && TOLOWER (*cp) <= 'z')
537 || *cp == L_('_'));
539 if (*cp != L_(')'))
540 /* The closing brace is missing. Only match the NAN
541 part. */
542 cp = startp;
543 else
545 /* This is a system-dependent way to specify the
546 bitmask used for the NaN. We expect it to be
547 a number which is put in the mantissa of the
548 number. */
549 STRING_TYPE *endp;
550 unsigned long long int mant;
552 mant = STRTOULL (startp, &endp, 0);
553 if (endp == cp)
554 SET_MANTISSA (retval, mant);
558 *endptr = (STRING_TYPE *) cp;
561 return retval;
564 /* It is really a text we do not recognize. */
565 RETURN (0.0, nptr);
568 /* First look whether we are faced with a hexadecimal number. */
569 if (c == L_('0') && TOLOWER (cp[1]) == L_('x'))
571 /* Okay, it is a hexa-decimal number. Remember this and skip
572 the characters. BTW: hexadecimal numbers must not be
573 grouped. */
574 base = 16;
575 cp += 2;
576 c = *cp;
577 grouping = NULL;
580 /* Record the start of the digits, in case we will check their grouping. */
581 start_of_digits = startp = cp;
583 /* Ignore leading zeroes. This helps us to avoid useless computations. */
584 while (c == L_('0') || (thousands != L'\0' && (wchar_t) c == thousands))
585 c = *++cp;
587 /* If no other digit but a '0' is found the result is 0.0.
588 Return current read pointer. */
589 if ((c < L_('0') || c > L_('9')) &&
590 (base == 16 && (c < TOLOWER (L_('a')) || c > TOLOWER (L_('f')))) &&
591 (wchar_t) c != decimal &&
592 (base == 16 && (cp == start_of_digits || TOLOWER (c) != L_('p'))) &&
593 (base != 16 && TOLOWER (c) != L_('e')))
595 tp = correctly_grouped_prefix (start_of_digits, cp, thousands, grouping);
596 /* If TP is at the start of the digits, there was no correctly
597 grouped prefix of the string; so no number found. */
598 RETURN (0.0, tp == start_of_digits ? (base == 16 ? cp - 1 : nptr) : tp);
601 /* Remember first significant digit and read following characters until the
602 decimal point, exponent character or any non-FP number character. */
603 startp = cp;
604 dig_no = 0;
605 while (dig_no < (base == 16 ? HEXNDIG : NDIG) ||
606 /* If parsing grouping info, keep going past useful digits
607 so we can check all the grouping separators. */
608 grouping)
610 if ((c >= L_('0') && c <= L_('9'))
611 || (base == 16 && TOLOWER (c) >= L_('a') && TOLOWER (c) <= L_('f')))
612 ++dig_no;
613 else if (thousands == L'\0' || (wchar_t) c != thousands)
614 /* Not a digit or separator: end of the integer part. */
615 break;
616 c = *++cp;
619 if (grouping && dig_no > 0)
621 /* Check the grouping of the digits. */
622 tp = correctly_grouped_prefix (start_of_digits, cp, thousands, grouping);
623 if (cp != tp)
625 /* Less than the entire string was correctly grouped. */
627 if (tp == start_of_digits)
628 /* No valid group of numbers at all: no valid number. */
629 RETURN (0.0, nptr);
631 if (tp < startp)
632 /* The number is validly grouped, but consists
633 only of zeroes. The whole value is zero. */
634 RETURN (0.0, tp);
636 /* Recompute DIG_NO so we won't read more digits than
637 are properly grouped. */
638 cp = tp;
639 dig_no = 0;
640 for (tp = startp; tp < cp; ++tp)
641 if (*tp >= L_('0') && *tp <= L_('9'))
642 ++dig_no;
644 int_no = dig_no;
645 lead_zero = 0;
647 goto number_parsed;
651 if (dig_no >= (base == 16 ? HEXNDIG : NDIG))
652 /* Too many digits to be representable. Assigning this to EXPONENT
653 allows us to read the full number but return HUGE_VAL after parsing. */
654 exponent = MAX_10_EXP;
656 /* We have the number digits in the integer part. Whether these are all or
657 any is really a fractional digit will be decided later. */
658 int_no = dig_no;
659 lead_zero = int_no == 0 ? -1 : 0;
661 /* Read the fractional digits. A special case are the 'american style'
662 numbers like `16.' i.e. with decimal but without trailing digits. */
663 if ((wchar_t) c == decimal)
665 c = *++cp;
666 while (c >= L_('0') && c <= L_('9') ||
667 (base == 16 && TOLOWER (c) >= L_('a') && TOLOWER (c) <= L_('f')))
669 if (c != L_('0') && lead_zero == -1)
670 lead_zero = dig_no - int_no;
671 ++dig_no;
672 c = *++cp;
676 /* Remember start of exponent (if any). */
677 expp = cp;
679 /* Read exponent. */
680 if ((base == 16 && TOLOWER (c) == L_('p'))
681 || (base != 16 && TOLOWER (c) == L_('e')))
683 int exp_negative = 0;
685 c = *++cp;
686 if (c == L_('-'))
688 exp_negative = 1;
689 c = *++cp;
691 else if (c == L_('+'))
692 c = *++cp;
694 if (c >= L_('0') && c <= L_('9'))
696 int exp_limit;
698 /* Get the exponent limit. */
699 if (base == 16)
700 exp_limit = (exp_negative ?
701 -MIN_EXP + MANT_DIG - 4 * int_no :
702 MAX_EXP - 4 * int_no + lead_zero);
703 else
704 exp_limit = (exp_negative ?
705 -MIN_10_EXP + MANT_DIG - int_no :
706 MAX_10_EXP - int_no + lead_zero);
710 exponent *= 10;
712 if (exponent > exp_limit)
713 /* The exponent is too large/small to represent a valid
714 number. */
716 FLOAT result;
718 /* Overflow or underflow. */
719 __set_errno (ERANGE);
720 result = (exp_negative ? 0.0 :
721 negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL);
723 /* Accept all following digits as part of the exponent. */
725 ++cp;
726 while (*cp >= L_('0') && *cp <= L_('9'));
728 RETURN (result, cp);
729 /* NOTREACHED */
732 exponent += c - L_('0');
733 c = *++cp;
735 while (c >= L_('0') && c <= L_('9'));
737 if (exp_negative)
738 exponent = -exponent;
740 else
741 cp = expp;
744 /* We don't want to have to work with trailing zeroes after the radix. */
745 if (dig_no > int_no)
747 while (expp[-1] == L_('0'))
749 --expp;
750 --dig_no;
752 assert (dig_no >= int_no);
755 number_parsed:
757 /* The whole string is parsed. Store the address of the next character. */
758 if (endptr)
759 *endptr = (STRING_TYPE *) cp;
761 if (dig_no == 0)
762 return 0.0;
764 if (lead_zero)
766 /* Find the decimal point */
767 while ((wchar_t) *startp != decimal)
768 ++startp;
769 startp += lead_zero + 1;
770 exponent -= base == 16 ? 4 * lead_zero : lead_zero;
771 dig_no -= lead_zero;
774 /* If the BASE is 16 we can use a simpler algorithm. */
775 if (base == 16)
777 static const int nbits[16] = { 0, 1, 2, 2, 3, 3, 3, 3,
778 4, 4, 4, 4, 4, 4, 4, 4 };
779 int idx = (MANT_DIG - 1) / BITS_PER_MP_LIMB;
780 int pos = (MANT_DIG - 1) % BITS_PER_MP_LIMB;
781 mp_limb_t val;
783 while (!ISXDIGIT (*startp))
784 ++startp;
785 if (ISDIGIT (*startp))
786 val = *startp++ - L_('0');
787 else
788 val = 10 + TOLOWER (*startp++) - L_('a');
789 bits = nbits[val];
791 if (pos + 1 >= 4)
793 /* We don't have to care for wrapping. This is the normal
794 case so we add this optimization. */
795 retval[idx] = val << (pos - bits + 1);
796 pos -= bits;
798 else
800 if (pos + 1 >= bits)
802 retval[idx] = val << (pos - bits + 1);
803 pos -= bits;
805 else
807 retval[idx--] = val >> (bits - pos - 1);
808 retval[idx] = val << (BITS_PER_MP_LIMB - (bits - pos - 1));
809 pos = BITS_PER_MP_LIMB - 1 - (bits - pos - 1);
813 while (--dig_no > 0 && idx >= 0)
815 while (!ISXDIGIT (*startp))
816 ++startp;
817 if (ISDIGIT (*startp))
818 val = *startp++ - L_('0');
819 else
820 val = 10 + TOLOWER (*startp++) - L_('a');
822 if (pos + 1 >= 4)
824 retval[idx] |= val << (pos - 4 + 1);
825 pos -= 4;
827 else
829 retval[idx--] |= val >> (4 - pos - 1);
830 val <<= BITS_PER_MP_LIMB - (4 - pos - 1);
831 if (idx < 0)
832 return round_and_return (retval, exponent, negative, val,
833 BITS_PER_MP_LIMB - 1, dig_no > 0);
835 retval[idx] = val;
836 pos = BITS_PER_MP_LIMB - 1 - (4 - pos - 1);
840 /* We ran out of digits. */
841 MPN_ZERO (retval, idx);
843 return round_and_return (retval, exponent, negative, 0, 0, 0);
846 /* Now we have the number of digits in total and the integer digits as well
847 as the exponent and its sign. We can decide whether the read digits are
848 really integer digits or belong to the fractional part; i.e. we normalize
849 123e-2 to 1.23. */
851 register int incr = (exponent < 0 ? MAX (-int_no, exponent)
852 : MIN (dig_no - int_no, exponent));
853 int_no += incr;
854 exponent -= incr;
857 if (int_no + exponent > MAX_10_EXP + 1)
859 __set_errno (ERANGE);
860 return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
863 if (exponent < MIN_10_EXP - (DIG + 1))
865 __set_errno (ERANGE);
866 return 0.0;
869 if (int_no > 0)
871 /* Read the integer part as a multi-precision number to NUM. */
872 startp = str_to_mpn (startp, int_no, num, &numsize, &exponent);
874 if (exponent > 0)
876 /* We now multiply the gained number by the given power of ten. */
877 mp_limb_t *psrc = num;
878 mp_limb_t *pdest = den;
879 int expbit = 1;
880 const struct mp_power *ttab = &_fpioconst_pow10[0];
884 if ((exponent & expbit) != 0)
886 mp_limb_t cy;
887 exponent ^= expbit;
889 /* FIXME: not the whole multiplication has to be
890 done. If we have the needed number of bits we
891 only need the information whether more non-zero
892 bits follow. */
893 if (numsize >= ttab->arraysize - _FPIO_CONST_OFFSET)
894 cy = __mpn_mul (pdest, psrc, numsize,
895 &ttab->array[_FPIO_CONST_OFFSET],
896 ttab->arraysize - _FPIO_CONST_OFFSET);
897 else
898 cy = __mpn_mul (pdest, &ttab->array[_FPIO_CONST_OFFSET],
899 ttab->arraysize - _FPIO_CONST_OFFSET,
900 psrc, numsize);
901 numsize += ttab->arraysize - _FPIO_CONST_OFFSET;
902 if (cy == 0)
903 --numsize;
904 SWAP (psrc, pdest);
906 expbit <<= 1;
907 ++ttab;
909 while (exponent != 0);
911 if (psrc == den)
912 memcpy (num, den, numsize * sizeof (mp_limb_t));
915 /* Determine how many bits of the result we already have. */
916 count_leading_zeros (bits, num[numsize - 1]);
917 bits = numsize * BITS_PER_MP_LIMB - bits;
919 /* Now we know the exponent of the number in base two.
920 Check it against the maximum possible exponent. */
921 if (bits > MAX_EXP)
923 __set_errno (ERANGE);
924 return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
927 /* We have already the first BITS bits of the result. Together with
928 the information whether more non-zero bits follow this is enough
929 to determine the result. */
930 if (bits > MANT_DIG)
932 int i;
933 const mp_size_t least_idx = (bits - MANT_DIG) / BITS_PER_MP_LIMB;
934 const mp_size_t least_bit = (bits - MANT_DIG) % BITS_PER_MP_LIMB;
935 const mp_size_t round_idx = least_bit == 0 ? least_idx - 1
936 : least_idx;
937 const mp_size_t round_bit = least_bit == 0 ? BITS_PER_MP_LIMB - 1
938 : least_bit - 1;
940 if (least_bit == 0)
941 memcpy (retval, &num[least_idx],
942 RETURN_LIMB_SIZE * sizeof (mp_limb_t));
943 else
945 for (i = least_idx; i < numsize - 1; ++i)
946 retval[i - least_idx] = (num[i] >> least_bit)
947 | (num[i + 1]
948 << (BITS_PER_MP_LIMB - least_bit));
949 if (i - least_idx < RETURN_LIMB_SIZE)
950 retval[RETURN_LIMB_SIZE - 1] = num[i] >> least_bit;
953 /* Check whether any limb beside the ones in RETVAL are non-zero. */
954 for (i = 0; num[i] == 0; ++i)
957 return round_and_return (retval, bits - 1, negative,
958 num[round_idx], round_bit,
959 int_no < dig_no || i < round_idx);
960 /* NOTREACHED */
962 else if (dig_no == int_no)
964 const mp_size_t target_bit = (MANT_DIG - 1) % BITS_PER_MP_LIMB;
965 const mp_size_t is_bit = (bits - 1) % BITS_PER_MP_LIMB;
967 if (target_bit == is_bit)
969 memcpy (&retval[RETURN_LIMB_SIZE - numsize], num,
970 numsize * sizeof (mp_limb_t));
971 /* FIXME: the following loop can be avoided if we assume a
972 maximal MANT_DIG value. */
973 MPN_ZERO (retval, RETURN_LIMB_SIZE - numsize);
975 else if (target_bit > is_bit)
977 (void) __mpn_lshift (&retval[RETURN_LIMB_SIZE - numsize],
978 num, numsize, target_bit - is_bit);
979 /* FIXME: the following loop can be avoided if we assume a
980 maximal MANT_DIG value. */
981 MPN_ZERO (retval, RETURN_LIMB_SIZE - numsize);
983 else
985 mp_limb_t cy;
986 assert (numsize < RETURN_LIMB_SIZE);
988 cy = __mpn_rshift (&retval[RETURN_LIMB_SIZE - numsize],
989 num, numsize, is_bit - target_bit);
990 retval[RETURN_LIMB_SIZE - numsize - 1] = cy;
991 /* FIXME: the following loop can be avoided if we assume a
992 maximal MANT_DIG value. */
993 MPN_ZERO (retval, RETURN_LIMB_SIZE - numsize - 1);
996 return round_and_return (retval, bits - 1, negative, 0, 0, 0);
997 /* NOTREACHED */
1000 /* Store the bits we already have. */
1001 memcpy (retval, num, numsize * sizeof (mp_limb_t));
1002 #if RETURN_LIMB_SIZE > 1
1003 if (numsize < RETURN_LIMB_SIZE)
1004 retval[numsize] = 0;
1005 #endif
1008 /* We have to compute at least some of the fractional digits. */
1010 /* We construct a fraction and the result of the division gives us
1011 the needed digits. The denominator is 1.0 multiplied by the
1012 exponent of the lowest digit; i.e. 0.123 gives 123 / 1000 and
1013 123e-6 gives 123 / 1000000. */
1015 int expbit;
1016 int cnt;
1017 int neg_exp;
1018 int more_bits;
1019 mp_limb_t cy;
1020 mp_limb_t *psrc = den;
1021 mp_limb_t *pdest = num;
1022 const struct mp_power *ttab = &_fpioconst_pow10[0];
1024 assert (dig_no > int_no && exponent <= 0);
1027 /* For the fractional part we need not process too many digits. One
1028 decimal digits gives us log_2(10) ~ 3.32 bits. If we now compute
1029 ceil(BITS / 3) =: N
1030 digits we should have enough bits for the result. The remaining
1031 decimal digits give us the information that more bits are following.
1032 This can be used while rounding. (One added as a safety margin.) */
1033 if (dig_no - int_no > (MANT_DIG - bits + 2) / 3 + 1)
1035 dig_no = int_no + (MANT_DIG - bits + 2) / 3 + 1;
1036 more_bits = 1;
1038 else
1039 more_bits = 0;
1041 neg_exp = dig_no - int_no - exponent;
1043 /* Construct the denominator. */
1044 densize = 0;
1045 expbit = 1;
1048 if ((neg_exp & expbit) != 0)
1050 mp_limb_t cy;
1051 neg_exp ^= expbit;
1053 if (densize == 0)
1055 densize = ttab->arraysize - _FPIO_CONST_OFFSET;
1056 memcpy (psrc, &ttab->array[_FPIO_CONST_OFFSET],
1057 densize * sizeof (mp_limb_t));
1059 else
1061 cy = __mpn_mul (pdest, &ttab->array[_FPIO_CONST_OFFSET],
1062 ttab->arraysize - _FPIO_CONST_OFFSET,
1063 psrc, densize);
1064 densize += ttab->arraysize - _FPIO_CONST_OFFSET;
1065 if (cy == 0)
1066 --densize;
1067 SWAP (psrc, pdest);
1070 expbit <<= 1;
1071 ++ttab;
1073 while (neg_exp != 0);
1075 if (psrc == num)
1076 memcpy (den, num, densize * sizeof (mp_limb_t));
1078 /* Read the fractional digits from the string. */
1079 (void) str_to_mpn (startp, dig_no - int_no, num, &numsize, &exponent);
1082 /* We now have to shift both numbers so that the highest bit in the
1083 denominator is set. In the same process we copy the numerator to
1084 a high place in the array so that the division constructs the wanted
1085 digits. This is done by a "quasi fix point" number representation.
1087 num: ddddddddddd . 0000000000000000000000
1088 |--- m ---|
1089 den: ddddddddddd n >= m
1090 |--- n ---|
1093 count_leading_zeros (cnt, den[densize - 1]);
1095 (void) __mpn_lshift (den, den, densize, cnt);
1096 cy = __mpn_lshift (num, num, numsize, cnt);
1097 if (cy != 0)
1098 num[numsize++] = cy;
1100 /* Now we are ready for the division. But it is not necessary to
1101 do a full multi-precision division because we only need a small
1102 number of bits for the result. So we do not use __mpn_divmod
1103 here but instead do the division here by hand and stop whenever
1104 the needed number of bits is reached. The code itself comes
1105 from the GNU MP Library by Torbj\"orn Granlund. */
1107 exponent = bits;
1109 switch (densize)
1111 case 1:
1113 mp_limb_t d, n, quot;
1114 int used = 0;
1116 n = num[0];
1117 d = den[0];
1118 assert (numsize == 1 && n < d);
1122 udiv_qrnnd (quot, n, n, 0, d);
1124 #define got_limb \
1125 if (bits == 0) \
1127 register int cnt; \
1128 if (quot == 0) \
1129 cnt = BITS_PER_MP_LIMB; \
1130 else \
1131 count_leading_zeros (cnt, quot); \
1132 exponent -= cnt; \
1133 if (BITS_PER_MP_LIMB - cnt > MANT_DIG) \
1135 used = MANT_DIG + cnt; \
1136 retval[0] = quot >> (BITS_PER_MP_LIMB - used); \
1137 bits = MANT_DIG + 1; \
1139 else \
1141 /* Note that we only clear the second element. */ \
1142 /* The conditional is determined at compile time. */ \
1143 if (RETURN_LIMB_SIZE > 1) \
1144 retval[1] = 0; \
1145 retval[0] = quot; \
1146 bits = -cnt; \
1149 else if (bits + BITS_PER_MP_LIMB <= MANT_DIG) \
1150 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, BITS_PER_MP_LIMB, \
1151 quot); \
1152 else \
1154 used = MANT_DIG - bits; \
1155 if (used > 0) \
1156 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, used, quot); \
1158 bits += BITS_PER_MP_LIMB
1160 got_limb;
1162 while (bits <= MANT_DIG);
1164 return round_and_return (retval, exponent - 1, negative,
1165 quot, BITS_PER_MP_LIMB - 1 - used,
1166 more_bits || n != 0);
1168 case 2:
1170 mp_limb_t d0, d1, n0, n1;
1171 mp_limb_t quot = 0;
1172 int used = 0;
1174 d0 = den[0];
1175 d1 = den[1];
1177 if (numsize < densize)
1179 if (num[0] >= d1)
1181 /* The numerator of the number occupies fewer bits than
1182 the denominator but the one limb is bigger than the
1183 high limb of the numerator. */
1184 n1 = 0;
1185 n0 = num[0];
1187 else
1189 if (bits <= 0)
1190 exponent -= BITS_PER_MP_LIMB;
1191 else
1193 if (bits + BITS_PER_MP_LIMB <= MANT_DIG)
1194 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE,
1195 BITS_PER_MP_LIMB, 0);
1196 else
1198 used = MANT_DIG - bits;
1199 if (used > 0)
1200 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, used, 0);
1202 bits += BITS_PER_MP_LIMB;
1204 n1 = num[0];
1205 n0 = 0;
1208 else
1210 n1 = num[1];
1211 n0 = num[0];
1214 while (bits <= MANT_DIG)
1216 mp_limb_t r;
1218 if (n1 == d1)
1220 /* QUOT should be either 111..111 or 111..110. We need
1221 special treatment of this rare case as normal division
1222 would give overflow. */
1223 quot = ~(mp_limb_t) 0;
1225 r = n0 + d1;
1226 if (r < d1) /* Carry in the addition? */
1228 add_ssaaaa (n1, n0, r - d0, 0, 0, d0);
1229 goto have_quot;
1231 n1 = d0 - (d0 != 0);
1232 n0 = -d0;
1234 else
1236 udiv_qrnnd (quot, r, n1, n0, d1);
1237 umul_ppmm (n1, n0, d0, quot);
1240 q_test:
1241 if (n1 > r || (n1 == r && n0 > 0))
1243 /* The estimated QUOT was too large. */
1244 --quot;
1246 sub_ddmmss (n1, n0, n1, n0, 0, d0);
1247 r += d1;
1248 if (r >= d1) /* If not carry, test QUOT again. */
1249 goto q_test;
1251 sub_ddmmss (n1, n0, r, 0, n1, n0);
1253 have_quot:
1254 got_limb;
1257 return round_and_return (retval, exponent - 1, negative,
1258 quot, BITS_PER_MP_LIMB - 1 - used,
1259 more_bits || n1 != 0 || n0 != 0);
1261 default:
1263 int i;
1264 mp_limb_t cy, dX, d1, n0, n1;
1265 mp_limb_t quot = 0;
1266 int used = 0;
1268 dX = den[densize - 1];
1269 d1 = den[densize - 2];
1271 /* The division does not work if the upper limb of the two-limb
1272 numerator is greater than the denominator. */
1273 if (__mpn_cmp (num, &den[densize - numsize], numsize) > 0)
1274 num[numsize++] = 0;
1276 if (numsize < densize)
1278 mp_size_t empty = densize - numsize;
1280 if (bits <= 0)
1282 register int i;
1283 for (i = numsize; i > 0; --i)
1284 num[i + empty] = num[i - 1];
1285 MPN_ZERO (num, empty + 1);
1286 exponent -= empty * BITS_PER_MP_LIMB;
1288 else
1290 if (bits + empty * BITS_PER_MP_LIMB <= MANT_DIG)
1292 /* We make a difference here because the compiler
1293 cannot optimize the `else' case that good and
1294 this reflects all currently used FLOAT types
1295 and GMP implementations. */
1296 register int i;
1297 #if RETURN_LIMB_SIZE <= 2
1298 assert (empty == 1);
1299 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE,
1300 BITS_PER_MP_LIMB, 0);
1301 #else
1302 for (i = RETURN_LIMB_SIZE; i > empty; --i)
1303 retval[i] = retval[i - empty];
1304 #endif
1305 #if RETURN_LIMB_SIZE > 1
1306 retval[1] = 0;
1307 #endif
1308 for (i = numsize; i > 0; --i)
1309 num[i + empty] = num[i - 1];
1310 MPN_ZERO (num, empty + 1);
1312 else
1314 used = MANT_DIG - bits;
1315 if (used >= BITS_PER_MP_LIMB)
1317 register int i;
1318 (void) __mpn_lshift (&retval[used
1319 / BITS_PER_MP_LIMB],
1320 retval, RETURN_LIMB_SIZE,
1321 used % BITS_PER_MP_LIMB);
1322 for (i = used / BITS_PER_MP_LIMB; i >= 0; --i)
1323 retval[i] = 0;
1325 else if (used > 0)
1326 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, used, 0);
1328 bits += empty * BITS_PER_MP_LIMB;
1331 else
1333 int i;
1334 assert (numsize == densize);
1335 for (i = numsize; i > 0; --i)
1336 num[i] = num[i - 1];
1339 den[densize] = 0;
1340 n0 = num[densize];
1342 while (bits <= MANT_DIG)
1344 if (n0 == dX)
1345 /* This might over-estimate QUOT, but it's probably not
1346 worth the extra code here to find out. */
1347 quot = ~(mp_limb_t) 0;
1348 else
1350 mp_limb_t r;
1352 udiv_qrnnd (quot, r, n0, num[densize - 1], dX);
1353 umul_ppmm (n1, n0, d1, quot);
1355 while (n1 > r || (n1 == r && n0 > num[densize - 2]))
1357 --quot;
1358 r += dX;
1359 if (r < dX) /* I.e. "carry in previous addition?" */
1360 break;
1361 n1 -= n0 < d1;
1362 n0 -= d1;
1366 /* Possible optimization: We already have (q * n0) and (1 * n1)
1367 after the calculation of QUOT. Taking advantage of this, we
1368 could make this loop make two iterations less. */
1370 cy = __mpn_submul_1 (num, den, densize + 1, quot);
1372 if (num[densize] != cy)
1374 cy = __mpn_add_n (num, num, den, densize);
1375 assert (cy != 0);
1376 --quot;
1378 n0 = num[densize] = num[densize - 1];
1379 for (i = densize - 1; i > 0; --i)
1380 num[i] = num[i - 1];
1382 got_limb;
1385 for (i = densize; num[i] == 0 && i >= 0; --i)
1387 return round_and_return (retval, exponent - 1, negative,
1388 quot, BITS_PER_MP_LIMB - 1 - used,
1389 more_bits || i >= 0);
1394 /* NOTREACHED */
1397 /* External user entry point. */
1399 FLOAT
1400 #ifdef weak_function
1401 weak_function
1402 #endif
1403 STRTOF (nptr, endptr LOCALE_PARAM)
1404 const STRING_TYPE *nptr;
1405 STRING_TYPE **endptr;
1406 LOCALE_PARAM_DECL
1408 return INTERNAL (STRTOF) (nptr, endptr, 0 LOCALE_PARAM);