Fix a typo in ChangeLog
[glibc.git] / stdio-common / printf_fp.c
blob6e2b57c0396c157e3a699298fc681b1034c9f838
1 /* Floating point output for `printf'.
2 Copyright (C) 1995-2012 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
5 Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; if not, see
19 <http://www.gnu.org/licenses/>. */
21 /* The gmp headers need some configuration frobs. */
22 #define HAVE_ALLOCA 1
24 #include <libioP.h>
25 #include <alloca.h>
26 #include <ctype.h>
27 #include <float.h>
28 #include <gmp-mparam.h>
29 #include <gmp.h>
30 #include <ieee754.h>
31 #include <stdlib/gmp-impl.h>
32 #include <stdlib/longlong.h>
33 #include <stdlib/fpioconst.h>
34 #include <locale/localeinfo.h>
35 #include <limits.h>
36 #include <math.h>
37 #include <printf.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <wchar.h>
42 #include <stdbool.h>
43 #include <rounding-mode.h>
45 #ifdef COMPILE_WPRINTF
46 # define CHAR_T wchar_t
47 #else
48 # define CHAR_T char
49 #endif
51 #include "_i18n_number.h"
53 #ifndef NDEBUG
54 # define NDEBUG /* Undefine this for debugging assertions. */
55 #endif
56 #include <assert.h>
58 /* This defines make it possible to use the same code for GNU C library and
59 the GNU I/O library. */
60 #define PUT(f, s, n) _IO_sputn (f, s, n)
61 #define PAD(f, c, n) (wide ? _IO_wpadn (f, c, n) : _IO_padn (f, c, n))
62 /* We use this file GNU C library and GNU I/O library. So make
63 names equal. */
64 #undef putc
65 #define putc(c, f) (wide \
66 ? (int)_IO_putwc_unlocked (c, f) : _IO_putc_unlocked (c, f))
67 #define size_t _IO_size_t
68 #define FILE _IO_FILE
70 /* Macros for doing the actual output. */
72 #define outchar(ch) \
73 do \
74 { \
75 register const int outc = (ch); \
76 if (putc (outc, fp) == EOF) \
77 { \
78 if (buffer_malloced) \
79 free (wbuffer); \
80 return -1; \
81 } \
82 ++done; \
83 } while (0)
85 #define PRINT(ptr, wptr, len) \
86 do \
87 { \
88 register size_t outlen = (len); \
89 if (len > 20) \
90 { \
91 if (PUT (fp, wide ? (const char *) wptr : ptr, outlen) != outlen) \
92 { \
93 if (buffer_malloced) \
94 free (wbuffer); \
95 return -1; \
96 } \
97 ptr += outlen; \
98 done += outlen; \
99 } \
100 else \
102 if (wide) \
103 while (outlen-- > 0) \
104 outchar (*wptr++); \
105 else \
106 while (outlen-- > 0) \
107 outchar (*ptr++); \
109 } while (0)
111 #define PADN(ch, len) \
112 do \
114 if (PAD (fp, ch, len) != len) \
116 if (buffer_malloced) \
117 free (wbuffer); \
118 return -1; \
120 done += len; \
122 while (0)
124 /* We use the GNU MP library to handle large numbers.
126 An MP variable occupies a varying number of entries in its array. We keep
127 track of this number for efficiency reasons. Otherwise we would always
128 have to process the whole array. */
129 #define MPN_VAR(name) mp_limb_t *name; mp_size_t name##size
131 #define MPN_ASSIGN(dst,src) \
132 memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
133 #define MPN_GE(u,v) \
134 (u##size > v##size || (u##size == v##size && __mpn_cmp (u, v, u##size) >= 0))
136 extern int __isinfl_internal (long double) attribute_hidden;
137 extern int __isnanl_internal (long double) attribute_hidden;
139 extern mp_size_t __mpn_extract_double (mp_ptr res_ptr, mp_size_t size,
140 int *expt, int *is_neg,
141 double value);
142 extern mp_size_t __mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size,
143 int *expt, int *is_neg,
144 long double value);
145 extern unsigned int __guess_grouping (unsigned int intdig_max,
146 const char *grouping);
149 static wchar_t *group_number (wchar_t *buf, wchar_t *bufend,
150 unsigned int intdig_no, const char *grouping,
151 wchar_t thousands_sep, int ngroups)
152 internal_function;
156 ___printf_fp (FILE *fp,
157 const struct printf_info *info,
158 const void *const *args)
160 /* The floating-point value to output. */
161 union
163 double dbl;
164 __long_double_t ldbl;
166 fpnum;
168 /* Locale-dependent representation of decimal point. */
169 const char *decimal;
170 wchar_t decimalwc;
172 /* Locale-dependent thousands separator and grouping specification. */
173 const char *thousands_sep = NULL;
174 wchar_t thousands_sepwc = 0;
175 const char *grouping;
177 /* "NaN" or "Inf" for the special cases. */
178 const char *special = NULL;
179 const wchar_t *wspecial = NULL;
181 /* We need just a few limbs for the input before shifting to the right
182 position. */
183 mp_limb_t fp_input[(LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB];
184 /* We need to shift the contents of fp_input by this amount of bits. */
185 int to_shift = 0;
187 /* The fraction of the floting-point value in question */
188 MPN_VAR(frac);
189 /* and the exponent. */
190 int exponent;
191 /* Sign of the exponent. */
192 int expsign = 0;
193 /* Sign of float number. */
194 int is_neg = 0;
196 /* Scaling factor. */
197 MPN_VAR(scale);
199 /* Temporary bignum value. */
200 MPN_VAR(tmp);
202 /* The type of output format that will be used: 'e'/'E' or 'f'. */
203 int type;
205 /* Counter for number of written characters. */
206 int done = 0;
208 /* General helper (carry limb). */
209 mp_limb_t cy;
211 /* Nonzero if this is output on a wide character stream. */
212 int wide = info->wide;
214 /* Buffer in which we produce the output. */
215 wchar_t *wbuffer = NULL;
216 /* Flag whether wbuffer is malloc'ed or not. */
217 int buffer_malloced = 0;
219 auto wchar_t hack_digit (void);
221 wchar_t hack_digit (void)
223 mp_limb_t hi;
225 if (expsign != 0 && type == 'f' && exponent-- > 0)
226 hi = 0;
227 else if (scalesize == 0)
229 hi = frac[fracsize - 1];
230 frac[fracsize - 1] = __mpn_mul_1 (frac, frac, fracsize - 1, 10);
232 else
234 if (fracsize < scalesize)
235 hi = 0;
236 else
238 hi = mpn_divmod (tmp, frac, fracsize, scale, scalesize);
239 tmp[fracsize - scalesize] = hi;
240 hi = tmp[0];
242 fracsize = scalesize;
243 while (fracsize != 0 && frac[fracsize - 1] == 0)
244 --fracsize;
245 if (fracsize == 0)
247 /* We're not prepared for an mpn variable with zero
248 limbs. */
249 fracsize = 1;
250 return L'0' + hi;
254 mp_limb_t _cy = __mpn_mul_1 (frac, frac, fracsize, 10);
255 if (_cy != 0)
256 frac[fracsize++] = _cy;
259 return L'0' + hi;
263 /* Figure out the decimal point character. */
264 if (info->extra == 0)
266 decimal = _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
267 decimalwc = _NL_CURRENT_WORD (LC_NUMERIC, _NL_NUMERIC_DECIMAL_POINT_WC);
269 else
271 decimal = _NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT);
272 if (*decimal == '\0')
273 decimal = _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
274 decimalwc = _NL_CURRENT_WORD (LC_MONETARY,
275 _NL_MONETARY_DECIMAL_POINT_WC);
276 if (decimalwc == L'\0')
277 decimalwc = _NL_CURRENT_WORD (LC_NUMERIC,
278 _NL_NUMERIC_DECIMAL_POINT_WC);
280 /* The decimal point character must not be zero. */
281 assert (*decimal != '\0');
282 assert (decimalwc != L'\0');
284 if (info->group)
286 if (info->extra == 0)
287 grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
288 else
289 grouping = _NL_CURRENT (LC_MONETARY, MON_GROUPING);
291 if (*grouping <= 0 || *grouping == CHAR_MAX)
292 grouping = NULL;
293 else
295 /* Figure out the thousands separator character. */
296 if (wide)
298 if (info->extra == 0)
299 thousands_sepwc =
300 _NL_CURRENT_WORD (LC_NUMERIC, _NL_NUMERIC_THOUSANDS_SEP_WC);
301 else
302 thousands_sepwc =
303 _NL_CURRENT_WORD (LC_MONETARY,
304 _NL_MONETARY_THOUSANDS_SEP_WC);
306 else
308 if (info->extra == 0)
309 thousands_sep = _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
310 else
311 thousands_sep = _NL_CURRENT (LC_MONETARY, MON_THOUSANDS_SEP);
314 if ((wide && thousands_sepwc == L'\0')
315 || (! wide && *thousands_sep == '\0'))
316 grouping = NULL;
317 else if (thousands_sepwc == L'\0')
318 /* If we are printing multibyte characters and there is a
319 multibyte representation for the thousands separator,
320 we must ensure the wide character thousands separator
321 is available, even if it is fake. */
322 thousands_sepwc = 0xfffffffe;
325 else
326 grouping = NULL;
328 /* Fetch the argument value. */
329 #ifndef __NO_LONG_DOUBLE_MATH
330 if (info->is_long_double && sizeof (long double) > sizeof (double))
332 fpnum.ldbl = *(const long double *) args[0];
334 /* Check for special values: not a number or infinity. */
335 int res;
336 if (__isnanl (fpnum.ldbl))
338 union ieee854_long_double u = { .d = fpnum.ldbl };
339 is_neg = u.ieee.negative != 0;
340 if (isupper (info->spec))
342 special = "NAN";
343 wspecial = L"NAN";
345 else
347 special = "nan";
348 wspecial = L"nan";
351 else if ((res = __isinfl (fpnum.ldbl)))
353 is_neg = res < 0;
354 if (isupper (info->spec))
356 special = "INF";
357 wspecial = L"INF";
359 else
361 special = "inf";
362 wspecial = L"inf";
365 else
367 fracsize = __mpn_extract_long_double (fp_input,
368 (sizeof (fp_input) /
369 sizeof (fp_input[0])),
370 &exponent, &is_neg,
371 fpnum.ldbl);
372 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
375 else
376 #endif /* no long double */
378 fpnum.dbl = *(const double *) args[0];
380 /* Check for special values: not a number or infinity. */
381 int res;
382 if (__isnan (fpnum.dbl))
384 union ieee754_double u = { .d = fpnum.dbl };
385 is_neg = u.ieee.negative != 0;
386 if (isupper (info->spec))
388 special = "NAN";
389 wspecial = L"NAN";
391 else
393 special = "nan";
394 wspecial = L"nan";
397 else if ((res = __isinf (fpnum.dbl)))
399 is_neg = res < 0;
400 if (isupper (info->spec))
402 special = "INF";
403 wspecial = L"INF";
405 else
407 special = "inf";
408 wspecial = L"inf";
411 else
413 fracsize = __mpn_extract_double (fp_input,
414 (sizeof (fp_input)
415 / sizeof (fp_input[0])),
416 &exponent, &is_neg, fpnum.dbl);
417 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - DBL_MANT_DIG;
421 if (special)
423 int width = info->width;
425 if (is_neg || info->showsign || info->space)
426 --width;
427 width -= 3;
429 if (!info->left && width > 0)
430 PADN (' ', width);
432 if (is_neg)
433 outchar ('-');
434 else if (info->showsign)
435 outchar ('+');
436 else if (info->space)
437 outchar (' ');
439 PRINT (special, wspecial, 3);
441 if (info->left && width > 0)
442 PADN (' ', width);
444 return done;
448 /* We need three multiprecision variables. Now that we have the exponent
449 of the number we can allocate the needed memory. It would be more
450 efficient to use variables of the fixed maximum size but because this
451 would be really big it could lead to memory problems. */
453 mp_size_t bignum_size = ((ABS (exponent) + BITS_PER_MP_LIMB - 1)
454 / BITS_PER_MP_LIMB
455 + (LDBL_MANT_DIG / BITS_PER_MP_LIMB > 2 ? 8 : 4))
456 * sizeof (mp_limb_t);
457 frac = (mp_limb_t *) alloca (bignum_size);
458 tmp = (mp_limb_t *) alloca (bignum_size);
459 scale = (mp_limb_t *) alloca (bignum_size);
462 /* We now have to distinguish between numbers with positive and negative
463 exponents because the method used for the one is not applicable/efficient
464 for the other. */
465 scalesize = 0;
466 if (exponent > 2)
468 /* |FP| >= 8.0. */
469 int scaleexpo = 0;
470 int explog = LDBL_MAX_10_EXP_LOG;
471 int exp10 = 0;
472 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
473 int cnt_h, cnt_l, i;
475 if ((exponent + to_shift) % BITS_PER_MP_LIMB == 0)
477 MPN_COPY_DECR (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
478 fp_input, fracsize);
479 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
481 else
483 cy = __mpn_lshift (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
484 fp_input, fracsize,
485 (exponent + to_shift) % BITS_PER_MP_LIMB);
486 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
487 if (cy)
488 frac[fracsize++] = cy;
490 MPN_ZERO (frac, (exponent + to_shift) / BITS_PER_MP_LIMB);
492 assert (powers > &_fpioconst_pow10[0]);
495 --powers;
497 /* The number of the product of two binary numbers with n and m
498 bits respectively has m+n or m+n-1 bits. */
499 if (exponent >= scaleexpo + powers->p_expo - 1)
501 if (scalesize == 0)
503 #ifndef __NO_LONG_DOUBLE_MATH
504 if (LDBL_MANT_DIG > _FPIO_CONST_OFFSET * BITS_PER_MP_LIMB
505 && info->is_long_double)
507 #define _FPIO_CONST_SHIFT \
508 (((LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB) \
509 - _FPIO_CONST_OFFSET)
510 /* 64bit const offset is not enough for
511 IEEE quad long double. */
512 tmpsize = powers->arraysize + _FPIO_CONST_SHIFT;
513 memcpy (tmp + _FPIO_CONST_SHIFT,
514 &__tens[powers->arrayoff],
515 tmpsize * sizeof (mp_limb_t));
516 MPN_ZERO (tmp, _FPIO_CONST_SHIFT);
517 /* Adjust exponent, as scaleexpo will be this much
518 bigger too. */
519 exponent += _FPIO_CONST_SHIFT * BITS_PER_MP_LIMB;
521 else
522 #endif
524 tmpsize = powers->arraysize;
525 memcpy (tmp, &__tens[powers->arrayoff],
526 tmpsize * sizeof (mp_limb_t));
529 else
531 cy = __mpn_mul (tmp, scale, scalesize,
532 &__tens[powers->arrayoff
533 + _FPIO_CONST_OFFSET],
534 powers->arraysize - _FPIO_CONST_OFFSET);
535 tmpsize = scalesize + powers->arraysize - _FPIO_CONST_OFFSET;
536 if (cy == 0)
537 --tmpsize;
540 if (MPN_GE (frac, tmp))
542 int cnt;
543 MPN_ASSIGN (scale, tmp);
544 count_leading_zeros (cnt, scale[scalesize - 1]);
545 scaleexpo = (scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
546 exp10 |= 1 << explog;
549 --explog;
551 while (powers > &_fpioconst_pow10[0]);
552 exponent = exp10;
554 /* Optimize number representations. We want to represent the numbers
555 with the lowest number of bytes possible without losing any
556 bytes. Also the highest bit in the scaling factor has to be set
557 (this is a requirement of the MPN division routines). */
558 if (scalesize > 0)
560 /* Determine minimum number of zero bits at the end of
561 both numbers. */
562 for (i = 0; scale[i] == 0 && frac[i] == 0; i++)
565 /* Determine number of bits the scaling factor is misplaced. */
566 count_leading_zeros (cnt_h, scale[scalesize - 1]);
568 if (cnt_h == 0)
570 /* The highest bit of the scaling factor is already set. So
571 we only have to remove the trailing empty limbs. */
572 if (i > 0)
574 MPN_COPY_INCR (scale, scale + i, scalesize - i);
575 scalesize -= i;
576 MPN_COPY_INCR (frac, frac + i, fracsize - i);
577 fracsize -= i;
580 else
582 if (scale[i] != 0)
584 count_trailing_zeros (cnt_l, scale[i]);
585 if (frac[i] != 0)
587 int cnt_l2;
588 count_trailing_zeros (cnt_l2, frac[i]);
589 if (cnt_l2 < cnt_l)
590 cnt_l = cnt_l2;
593 else
594 count_trailing_zeros (cnt_l, frac[i]);
596 /* Now shift the numbers to their optimal position. */
597 if (i == 0 && BITS_PER_MP_LIMB - cnt_h > cnt_l)
599 /* We cannot save any memory. So just roll both numbers
600 so that the scaling factor has its highest bit set. */
602 (void) __mpn_lshift (scale, scale, scalesize, cnt_h);
603 cy = __mpn_lshift (frac, frac, fracsize, cnt_h);
604 if (cy != 0)
605 frac[fracsize++] = cy;
607 else if (BITS_PER_MP_LIMB - cnt_h <= cnt_l)
609 /* We can save memory by removing the trailing zero limbs
610 and by packing the non-zero limbs which gain another
611 free one. */
613 (void) __mpn_rshift (scale, scale + i, scalesize - i,
614 BITS_PER_MP_LIMB - cnt_h);
615 scalesize -= i + 1;
616 (void) __mpn_rshift (frac, frac + i, fracsize - i,
617 BITS_PER_MP_LIMB - cnt_h);
618 fracsize -= frac[fracsize - i - 1] == 0 ? i + 1 : i;
620 else
622 /* We can only save the memory of the limbs which are zero.
623 The non-zero parts occupy the same number of limbs. */
625 (void) __mpn_rshift (scale, scale + (i - 1),
626 scalesize - (i - 1),
627 BITS_PER_MP_LIMB - cnt_h);
628 scalesize -= i;
629 (void) __mpn_rshift (frac, frac + (i - 1),
630 fracsize - (i - 1),
631 BITS_PER_MP_LIMB - cnt_h);
632 fracsize -= frac[fracsize - (i - 1) - 1] == 0 ? i : i - 1;
637 else if (exponent < 0)
639 /* |FP| < 1.0. */
640 int exp10 = 0;
641 int explog = LDBL_MAX_10_EXP_LOG;
642 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
644 /* Now shift the input value to its right place. */
645 cy = __mpn_lshift (frac, fp_input, fracsize, to_shift);
646 frac[fracsize++] = cy;
647 assert (cy == 1 || (frac[fracsize - 2] == 0 && frac[0] == 0));
649 expsign = 1;
650 exponent = -exponent;
652 assert (powers != &_fpioconst_pow10[0]);
655 --powers;
657 if (exponent >= powers->m_expo)
659 int i, incr, cnt_h, cnt_l;
660 mp_limb_t topval[2];
662 /* The __mpn_mul function expects the first argument to be
663 bigger than the second. */
664 if (fracsize < powers->arraysize - _FPIO_CONST_OFFSET)
665 cy = __mpn_mul (tmp, &__tens[powers->arrayoff
666 + _FPIO_CONST_OFFSET],
667 powers->arraysize - _FPIO_CONST_OFFSET,
668 frac, fracsize);
669 else
670 cy = __mpn_mul (tmp, frac, fracsize,
671 &__tens[powers->arrayoff + _FPIO_CONST_OFFSET],
672 powers->arraysize - _FPIO_CONST_OFFSET);
673 tmpsize = fracsize + powers->arraysize - _FPIO_CONST_OFFSET;
674 if (cy == 0)
675 --tmpsize;
677 count_leading_zeros (cnt_h, tmp[tmpsize - 1]);
678 incr = (tmpsize - fracsize) * BITS_PER_MP_LIMB
679 + BITS_PER_MP_LIMB - 1 - cnt_h;
681 assert (incr <= powers->p_expo);
683 /* If we increased the exponent by exactly 3 we have to test
684 for overflow. This is done by comparing with 10 shifted
685 to the right position. */
686 if (incr == exponent + 3)
688 if (cnt_h <= BITS_PER_MP_LIMB - 4)
690 topval[0] = 0;
691 topval[1]
692 = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4 - cnt_h);
694 else
696 topval[0] = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4);
697 topval[1] = 0;
698 (void) __mpn_lshift (topval, topval, 2,
699 BITS_PER_MP_LIMB - cnt_h);
703 /* We have to be careful when multiplying the last factor.
704 If the result is greater than 1.0 be have to test it
705 against 10.0. If it is greater or equal to 10.0 the
706 multiplication was not valid. This is because we cannot
707 determine the number of bits in the result in advance. */
708 if (incr < exponent + 3
709 || (incr == exponent + 3 &&
710 (tmp[tmpsize - 1] < topval[1]
711 || (tmp[tmpsize - 1] == topval[1]
712 && tmp[tmpsize - 2] < topval[0]))))
714 /* The factor is right. Adapt binary and decimal
715 exponents. */
716 exponent -= incr;
717 exp10 |= 1 << explog;
719 /* If this factor yields a number greater or equal to
720 1.0, we must not shift the non-fractional digits down. */
721 if (exponent < 0)
722 cnt_h += -exponent;
724 /* Now we optimize the number representation. */
725 for (i = 0; tmp[i] == 0; ++i);
726 if (cnt_h == BITS_PER_MP_LIMB - 1)
728 MPN_COPY (frac, tmp + i, tmpsize - i);
729 fracsize = tmpsize - i;
731 else
733 count_trailing_zeros (cnt_l, tmp[i]);
735 /* Now shift the numbers to their optimal position. */
736 if (i == 0 && BITS_PER_MP_LIMB - 1 - cnt_h > cnt_l)
738 /* We cannot save any memory. Just roll the
739 number so that the leading digit is in a
740 separate limb. */
742 cy = __mpn_lshift (frac, tmp, tmpsize, cnt_h + 1);
743 fracsize = tmpsize + 1;
744 frac[fracsize - 1] = cy;
746 else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
748 (void) __mpn_rshift (frac, tmp + i, tmpsize - i,
749 BITS_PER_MP_LIMB - 1 - cnt_h);
750 fracsize = tmpsize - i;
752 else
754 /* We can only save the memory of the limbs which
755 are zero. The non-zero parts occupy the same
756 number of limbs. */
758 (void) __mpn_rshift (frac, tmp + (i - 1),
759 tmpsize - (i - 1),
760 BITS_PER_MP_LIMB - 1 - cnt_h);
761 fracsize = tmpsize - (i - 1);
766 --explog;
768 while (powers != &_fpioconst_pow10[1] && exponent > 0);
769 /* All factors but 10^-1 are tested now. */
770 if (exponent > 0)
772 int cnt_l;
774 cy = __mpn_mul_1 (tmp, frac, fracsize, 10);
775 tmpsize = fracsize;
776 assert (cy == 0 || tmp[tmpsize - 1] < 20);
778 count_trailing_zeros (cnt_l, tmp[0]);
779 if (cnt_l < MIN (4, exponent))
781 cy = __mpn_lshift (frac, tmp, tmpsize,
782 BITS_PER_MP_LIMB - MIN (4, exponent));
783 if (cy != 0)
784 frac[tmpsize++] = cy;
786 else
787 (void) __mpn_rshift (frac, tmp, tmpsize, MIN (4, exponent));
788 fracsize = tmpsize;
789 exp10 |= 1;
790 assert (frac[fracsize - 1] < 10);
792 exponent = exp10;
794 else
796 /* This is a special case. We don't need a factor because the
797 numbers are in the range of 1.0 <= |fp| < 8.0. We simply
798 shift it to the right place and divide it by 1.0 to get the
799 leading digit. (Of course this division is not really made.) */
800 assert (0 <= exponent && exponent < 3 &&
801 exponent + to_shift < BITS_PER_MP_LIMB);
803 /* Now shift the input value to its right place. */
804 cy = __mpn_lshift (frac, fp_input, fracsize, (exponent + to_shift));
805 frac[fracsize++] = cy;
806 exponent = 0;
810 int width = info->width;
811 wchar_t *wstartp, *wcp;
812 size_t chars_needed;
813 int expscale;
814 int intdig_max, intdig_no = 0;
815 int fracdig_min;
816 int fracdig_max;
817 int dig_max;
818 int significant;
819 int ngroups = 0;
820 char spec = _tolower (info->spec);
822 if (spec == 'e')
824 type = info->spec;
825 intdig_max = 1;
826 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
827 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
828 /* d . ddd e +- ddd */
829 dig_max = INT_MAX; /* Unlimited. */
830 significant = 1; /* Does not matter here. */
832 else if (spec == 'f')
834 type = 'f';
835 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
836 dig_max = INT_MAX; /* Unlimited. */
837 significant = 1; /* Does not matter here. */
838 if (expsign == 0)
840 intdig_max = exponent + 1;
841 /* This can be really big! */ /* XXX Maybe malloc if too big? */
842 chars_needed = (size_t) exponent + 1 + 1 + (size_t) fracdig_max;
844 else
846 intdig_max = 1;
847 chars_needed = 1 + 1 + (size_t) fracdig_max;
850 else
852 dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
853 if ((expsign == 0 && exponent >= dig_max)
854 || (expsign != 0 && exponent > 4))
856 if ('g' - 'G' == 'e' - 'E')
857 type = 'E' + (info->spec - 'G');
858 else
859 type = isupper (info->spec) ? 'E' : 'e';
860 fracdig_max = dig_max - 1;
861 intdig_max = 1;
862 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
864 else
866 type = 'f';
867 intdig_max = expsign == 0 ? exponent + 1 : 0;
868 fracdig_max = dig_max - intdig_max;
869 /* We need space for the significant digits and perhaps
870 for leading zeros when < 1.0. The number of leading
871 zeros can be as many as would be required for
872 exponential notation with a negative two-digit
873 exponent, which is 4. */
874 chars_needed = (size_t) dig_max + 1 + 4;
876 fracdig_min = info->alt ? fracdig_max : 0;
877 significant = 0; /* We count significant digits. */
880 if (grouping)
882 /* Guess the number of groups we will make, and thus how
883 many spaces we need for separator characters. */
884 ngroups = __guess_grouping (intdig_max, grouping);
885 /* Allocate one more character in case rounding increases the
886 number of groups. */
887 chars_needed += ngroups + 1;
890 /* Allocate buffer for output. We need two more because while rounding
891 it is possible that we need two more characters in front of all the
892 other output. If the amount of memory we have to allocate is too
893 large use `malloc' instead of `alloca'. */
894 if (__builtin_expect (chars_needed >= (size_t) -1 / sizeof (wchar_t) - 2
895 || chars_needed < fracdig_max, 0))
897 /* Some overflow occurred. */
898 __set_errno (ERANGE);
899 return -1;
901 size_t wbuffer_to_alloc = (2 + chars_needed) * sizeof (wchar_t);
902 buffer_malloced = ! __libc_use_alloca (wbuffer_to_alloc);
903 if (__builtin_expect (buffer_malloced, 0))
905 wbuffer = (wchar_t *) malloc (wbuffer_to_alloc);
906 if (wbuffer == NULL)
907 /* Signal an error to the caller. */
908 return -1;
910 else
911 wbuffer = (wchar_t *) alloca (wbuffer_to_alloc);
912 wcp = wstartp = wbuffer + 2; /* Let room for rounding. */
914 /* Do the real work: put digits in allocated buffer. */
915 if (expsign == 0 || type != 'f')
917 assert (expsign == 0 || intdig_max == 1);
918 while (intdig_no < intdig_max)
920 ++intdig_no;
921 *wcp++ = hack_digit ();
923 significant = 1;
924 if (info->alt
925 || fracdig_min > 0
926 || (fracdig_max > 0 && (fracsize > 1 || frac[0] != 0)))
927 *wcp++ = decimalwc;
929 else
931 /* |fp| < 1.0 and the selected type is 'f', so put "0."
932 in the buffer. */
933 *wcp++ = L'0';
934 --exponent;
935 *wcp++ = decimalwc;
938 /* Generate the needed number of fractional digits. */
939 int fracdig_no = 0;
940 int added_zeros = 0;
941 while (fracdig_no < fracdig_min + added_zeros
942 || (fracdig_no < fracdig_max && (fracsize > 1 || frac[0] != 0)))
944 ++fracdig_no;
945 *wcp = hack_digit ();
946 if (*wcp++ != L'0')
947 significant = 1;
948 else if (significant == 0)
950 ++fracdig_max;
951 if (fracdig_min > 0)
952 ++added_zeros;
956 /* Do rounding. */
957 wchar_t last_digit = wcp[-1] != decimalwc ? wcp[-1] : wcp[-2];
958 wchar_t next_digit = hack_digit ();
959 bool more_bits;
960 if (next_digit != L'0' && next_digit != L'5')
961 more_bits = true;
962 else if (fracsize == 1 && frac[0] == 0)
963 /* Rest of the number is zero. */
964 more_bits = false;
965 else if (scalesize == 0)
967 /* Here we have to see whether all limbs are zero since no
968 normalization happened. */
969 size_t lcnt = fracsize;
970 while (lcnt >= 1 && frac[lcnt - 1] == 0)
971 --lcnt;
972 more_bits = lcnt > 0;
974 else
975 more_bits = true;
976 int rounding_mode = get_rounding_mode ();
977 if (round_away (is_neg, (last_digit - L'0') & 1, next_digit >= L'5',
978 more_bits, rounding_mode))
980 wchar_t *wtp = wcp;
982 if (fracdig_no > 0)
984 /* Process fractional digits. Terminate if not rounded or
985 radix character is reached. */
986 int removed = 0;
987 while (*--wtp != decimalwc && *wtp == L'9')
989 *wtp = L'0';
990 ++removed;
992 if (removed == fracdig_min && added_zeros > 0)
993 --added_zeros;
994 if (*wtp != decimalwc)
995 /* Round up. */
996 (*wtp)++;
997 else if (__builtin_expect (spec == 'g' && type == 'f' && info->alt
998 && wtp == wstartp + 1
999 && wstartp[0] == L'0',
1001 /* This is a special case: the rounded number is 1.0,
1002 the format is 'g' or 'G', and the alternative format
1003 is selected. This means the result must be "1.". */
1004 --added_zeros;
1007 if (fracdig_no == 0 || *wtp == decimalwc)
1009 /* Round the integer digits. */
1010 if (*(wtp - 1) == decimalwc)
1011 --wtp;
1013 while (--wtp >= wstartp && *wtp == L'9')
1014 *wtp = L'0';
1016 if (wtp >= wstartp)
1017 /* Round up. */
1018 (*wtp)++;
1019 else
1020 /* It is more critical. All digits were 9's. */
1022 if (type != 'f')
1024 *wstartp = '1';
1025 exponent += expsign == 0 ? 1 : -1;
1027 /* The above exponent adjustment could lead to 1.0e-00,
1028 e.g. for 0.999999999. Make sure exponent 0 always
1029 uses + sign. */
1030 if (exponent == 0)
1031 expsign = 0;
1033 else if (intdig_no == dig_max)
1035 /* This is the case where for type %g the number fits
1036 really in the range for %f output but after rounding
1037 the number of digits is too big. */
1038 *--wstartp = decimalwc;
1039 *--wstartp = L'1';
1041 if (info->alt || fracdig_no > 0)
1043 /* Overwrite the old radix character. */
1044 wstartp[intdig_no + 2] = L'0';
1045 ++fracdig_no;
1048 fracdig_no += intdig_no;
1049 intdig_no = 1;
1050 fracdig_max = intdig_max - intdig_no;
1051 ++exponent;
1052 /* Now we must print the exponent. */
1053 type = isupper (info->spec) ? 'E' : 'e';
1055 else
1057 /* We can simply add another another digit before the
1058 radix. */
1059 *--wstartp = L'1';
1060 ++intdig_no;
1063 /* While rounding the number of digits can change.
1064 If the number now exceeds the limits remove some
1065 fractional digits. */
1066 if (intdig_no + fracdig_no > dig_max)
1068 wcp -= intdig_no + fracdig_no - dig_max;
1069 fracdig_no -= intdig_no + fracdig_no - dig_max;
1075 /* Now remove unnecessary '0' at the end of the string. */
1076 while (fracdig_no > fracdig_min + added_zeros && *(wcp - 1) == L'0')
1078 --wcp;
1079 --fracdig_no;
1081 /* If we eliminate all fractional digits we perhaps also can remove
1082 the radix character. */
1083 if (fracdig_no == 0 && !info->alt && *(wcp - 1) == decimalwc)
1084 --wcp;
1086 if (grouping)
1088 /* Rounding might have changed the number of groups. We allocated
1089 enough memory but we need here the correct number of groups. */
1090 if (intdig_no != intdig_max)
1091 ngroups = __guess_grouping (intdig_no, grouping);
1093 /* Add in separator characters, overwriting the same buffer. */
1094 wcp = group_number (wstartp, wcp, intdig_no, grouping, thousands_sepwc,
1095 ngroups);
1098 /* Write the exponent if it is needed. */
1099 if (type != 'f')
1101 if (__builtin_expect (expsign != 0 && exponent == 4 && spec == 'g', 0))
1103 /* This is another special case. The exponent of the number is
1104 really smaller than -4, which requires the 'e'/'E' format.
1105 But after rounding the number has an exponent of -4. */
1106 assert (wcp >= wstartp + 1);
1107 assert (wstartp[0] == L'1');
1108 __wmemcpy (wstartp, L"0.0001", 6);
1109 wstartp[1] = decimalwc;
1110 if (wcp >= wstartp + 2)
1112 wmemset (wstartp + 6, L'0', wcp - (wstartp + 2));
1113 wcp += 4;
1115 else
1116 wcp += 5;
1118 else
1120 *wcp++ = (wchar_t) type;
1121 *wcp++ = expsign ? L'-' : L'+';
1123 /* Find the magnitude of the exponent. */
1124 expscale = 10;
1125 while (expscale <= exponent)
1126 expscale *= 10;
1128 if (exponent < 10)
1129 /* Exponent always has at least two digits. */
1130 *wcp++ = L'0';
1131 else
1134 expscale /= 10;
1135 *wcp++ = L'0' + (exponent / expscale);
1136 exponent %= expscale;
1138 while (expscale > 10);
1139 *wcp++ = L'0' + exponent;
1143 /* Compute number of characters which must be filled with the padding
1144 character. */
1145 if (is_neg || info->showsign || info->space)
1146 --width;
1147 width -= wcp - wstartp;
1149 if (!info->left && info->pad != '0' && width > 0)
1150 PADN (info->pad, width);
1152 if (is_neg)
1153 outchar ('-');
1154 else if (info->showsign)
1155 outchar ('+');
1156 else if (info->space)
1157 outchar (' ');
1159 if (!info->left && info->pad == '0' && width > 0)
1160 PADN ('0', width);
1163 char *buffer = NULL;
1164 char *buffer_end = NULL;
1165 char *cp = NULL;
1166 char *tmpptr;
1168 if (! wide)
1170 /* Create the single byte string. */
1171 size_t decimal_len;
1172 size_t thousands_sep_len;
1173 wchar_t *copywc;
1174 size_t factor = (info->i18n
1175 ? _NL_CURRENT_WORD (LC_CTYPE, _NL_CTYPE_MB_CUR_MAX)
1176 : 1);
1178 decimal_len = strlen (decimal);
1180 if (thousands_sep == NULL)
1181 thousands_sep_len = 0;
1182 else
1183 thousands_sep_len = strlen (thousands_sep);
1185 size_t nbuffer = (2 + chars_needed * factor + decimal_len
1186 + ngroups * thousands_sep_len);
1187 if (__builtin_expect (buffer_malloced, 0))
1189 buffer = (char *) malloc (nbuffer);
1190 if (buffer == NULL)
1192 /* Signal an error to the caller. */
1193 free (wbuffer);
1194 return -1;
1197 else
1198 buffer = (char *) alloca (nbuffer);
1199 buffer_end = buffer + nbuffer;
1201 /* Now copy the wide character string. Since the character
1202 (except for the decimal point and thousands separator) must
1203 be coming from the ASCII range we can esily convert the
1204 string without mapping tables. */
1205 for (cp = buffer, copywc = wstartp; copywc < wcp; ++copywc)
1206 if (*copywc == decimalwc)
1207 cp = (char *) __mempcpy (cp, decimal, decimal_len);
1208 else if (*copywc == thousands_sepwc)
1209 cp = (char *) __mempcpy (cp, thousands_sep, thousands_sep_len);
1210 else
1211 *cp++ = (char) *copywc;
1214 tmpptr = buffer;
1215 if (__builtin_expect (info->i18n, 0))
1217 #ifdef COMPILE_WPRINTF
1218 wstartp = _i18n_number_rewrite (wstartp, wcp,
1219 wbuffer + wbuffer_to_alloc);
1220 wcp = wbuffer + wbuffer_to_alloc;
1221 assert ((uintptr_t) wbuffer <= (uintptr_t) wstartp);
1222 assert ((uintptr_t) wstartp
1223 < (uintptr_t) wbuffer + wbuffer_to_alloc);
1224 #else
1225 tmpptr = _i18n_number_rewrite (tmpptr, cp, buffer_end);
1226 cp = buffer_end;
1227 assert ((uintptr_t) buffer <= (uintptr_t) tmpptr);
1228 assert ((uintptr_t) tmpptr < (uintptr_t) buffer_end);
1229 #endif
1232 PRINT (tmpptr, wstartp, wide ? wcp - wstartp : cp - tmpptr);
1234 /* Free the memory if necessary. */
1235 if (__builtin_expect (buffer_malloced, 0))
1237 free (buffer);
1238 free (wbuffer);
1242 if (info->left && width > 0)
1243 PADN (info->pad, width);
1245 return done;
1247 ldbl_hidden_def (___printf_fp, __printf_fp)
1248 ldbl_strong_alias (___printf_fp, __printf_fp)
1250 /* Return the number of extra grouping characters that will be inserted
1251 into a number with INTDIG_MAX integer digits. */
1253 unsigned int
1254 __guess_grouping (unsigned int intdig_max, const char *grouping)
1256 unsigned int groups;
1258 /* We treat all negative values like CHAR_MAX. */
1260 if (*grouping == CHAR_MAX || *grouping <= 0)
1261 /* No grouping should be done. */
1262 return 0;
1264 groups = 0;
1265 while (intdig_max > (unsigned int) *grouping)
1267 ++groups;
1268 intdig_max -= *grouping++;
1270 if (*grouping == CHAR_MAX
1271 #if CHAR_MIN < 0
1272 || *grouping < 0
1273 #endif
1275 /* No more grouping should be done. */
1276 break;
1277 else if (*grouping == 0)
1279 /* Same grouping repeats. */
1280 groups += (intdig_max - 1) / grouping[-1];
1281 break;
1285 return groups;
1288 /* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
1289 There is guaranteed enough space past BUFEND to extend it.
1290 Return the new end of buffer. */
1292 static wchar_t *
1293 internal_function
1294 group_number (wchar_t *buf, wchar_t *bufend, unsigned int intdig_no,
1295 const char *grouping, wchar_t thousands_sep, int ngroups)
1297 wchar_t *p;
1299 if (ngroups == 0)
1300 return bufend;
1302 /* Move the fractional part down. */
1303 __wmemmove (buf + intdig_no + ngroups, buf + intdig_no,
1304 bufend - (buf + intdig_no));
1306 p = buf + intdig_no + ngroups - 1;
1309 unsigned int len = *grouping++;
1311 *p-- = buf[--intdig_no];
1312 while (--len > 0);
1313 *p-- = thousands_sep;
1315 if (*grouping == CHAR_MAX
1316 #if CHAR_MIN < 0
1317 || *grouping < 0
1318 #endif
1320 /* No more grouping should be done. */
1321 break;
1322 else if (*grouping == 0)
1323 /* Same grouping repeats. */
1324 --grouping;
1325 } while (intdig_no > (unsigned int) *grouping);
1327 /* Copy the remaining ungrouped digits. */
1329 *p-- = buf[--intdig_no];
1330 while (p > buf);
1332 return bufend + ngroups;