malloc: Add realloc test.
[glibc.git] / stdio-common / printf_fp.c
blobe20eab6a345c8a2202140c78d207a92f137b8b6f
1 /* Floating point output for `printf'.
2 Copyright (C) 1995-2013 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 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 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 mp_size_t __mpn_extract_double (mp_ptr res_ptr, mp_size_t size,
137 int *expt, int *is_neg,
138 double value);
139 extern mp_size_t __mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size,
140 int *expt, int *is_neg,
141 long double value);
142 extern unsigned int __guess_grouping (unsigned int intdig_max,
143 const char *grouping);
146 static wchar_t *group_number (wchar_t *buf, wchar_t *bufend,
147 unsigned int intdig_no, const char *grouping,
148 wchar_t thousands_sep, int ngroups)
149 internal_function;
153 ___printf_fp (FILE *fp,
154 const struct printf_info *info,
155 const void *const *args)
157 /* The floating-point value to output. */
158 union
160 double dbl;
161 __long_double_t ldbl;
163 fpnum;
165 /* Locale-dependent representation of decimal point. */
166 const char *decimal;
167 wchar_t decimalwc;
169 /* Locale-dependent thousands separator and grouping specification. */
170 const char *thousands_sep = NULL;
171 wchar_t thousands_sepwc = 0;
172 const char *grouping;
174 /* "NaN" or "Inf" for the special cases. */
175 const char *special = NULL;
176 const wchar_t *wspecial = NULL;
178 /* We need just a few limbs for the input before shifting to the right
179 position. */
180 mp_limb_t fp_input[(LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB];
181 /* We need to shift the contents of fp_input by this amount of bits. */
182 int to_shift = 0;
184 /* The fraction of the floting-point value in question */
185 MPN_VAR(frac);
186 /* and the exponent. */
187 int exponent;
188 /* Sign of the exponent. */
189 int expsign = 0;
190 /* Sign of float number. */
191 int is_neg = 0;
193 /* Scaling factor. */
194 MPN_VAR(scale);
196 /* Temporary bignum value. */
197 MPN_VAR(tmp);
199 /* The type of output format that will be used: 'e'/'E' or 'f'. */
200 int type;
202 /* Counter for number of written characters. */
203 int done = 0;
205 /* General helper (carry limb). */
206 mp_limb_t cy;
208 /* Nonzero if this is output on a wide character stream. */
209 int wide = info->wide;
211 /* Buffer in which we produce the output. */
212 wchar_t *wbuffer = NULL;
213 /* Flag whether wbuffer is malloc'ed or not. */
214 int buffer_malloced = 0;
216 auto wchar_t hack_digit (void);
218 wchar_t hack_digit (void)
220 mp_limb_t hi;
222 if (expsign != 0 && type == 'f' && exponent-- > 0)
223 hi = 0;
224 else if (scalesize == 0)
226 hi = frac[fracsize - 1];
227 frac[fracsize - 1] = __mpn_mul_1 (frac, frac, fracsize - 1, 10);
229 else
231 if (fracsize < scalesize)
232 hi = 0;
233 else
235 hi = mpn_divmod (tmp, frac, fracsize, scale, scalesize);
236 tmp[fracsize - scalesize] = hi;
237 hi = tmp[0];
239 fracsize = scalesize;
240 while (fracsize != 0 && frac[fracsize - 1] == 0)
241 --fracsize;
242 if (fracsize == 0)
244 /* We're not prepared for an mpn variable with zero
245 limbs. */
246 fracsize = 1;
247 return L'0' + hi;
251 mp_limb_t _cy = __mpn_mul_1 (frac, frac, fracsize, 10);
252 if (_cy != 0)
253 frac[fracsize++] = _cy;
256 return L'0' + hi;
260 /* Figure out the decimal point character. */
261 if (info->extra == 0)
263 decimal = _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
264 decimalwc = _NL_CURRENT_WORD (LC_NUMERIC, _NL_NUMERIC_DECIMAL_POINT_WC);
266 else
268 decimal = _NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT);
269 if (*decimal == '\0')
270 decimal = _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
271 decimalwc = _NL_CURRENT_WORD (LC_MONETARY,
272 _NL_MONETARY_DECIMAL_POINT_WC);
273 if (decimalwc == L'\0')
274 decimalwc = _NL_CURRENT_WORD (LC_NUMERIC,
275 _NL_NUMERIC_DECIMAL_POINT_WC);
277 /* The decimal point character must not be zero. */
278 assert (*decimal != '\0');
279 assert (decimalwc != L'\0');
281 if (info->group)
283 if (info->extra == 0)
284 grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
285 else
286 grouping = _NL_CURRENT (LC_MONETARY, MON_GROUPING);
288 if (*grouping <= 0 || *grouping == CHAR_MAX)
289 grouping = NULL;
290 else
292 /* Figure out the thousands separator character. */
293 if (wide)
295 if (info->extra == 0)
296 thousands_sepwc =
297 _NL_CURRENT_WORD (LC_NUMERIC, _NL_NUMERIC_THOUSANDS_SEP_WC);
298 else
299 thousands_sepwc =
300 _NL_CURRENT_WORD (LC_MONETARY,
301 _NL_MONETARY_THOUSANDS_SEP_WC);
303 else
305 if (info->extra == 0)
306 thousands_sep = _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
307 else
308 thousands_sep = _NL_CURRENT (LC_MONETARY, MON_THOUSANDS_SEP);
311 if ((wide && thousands_sepwc == L'\0')
312 || (! wide && *thousands_sep == '\0'))
313 grouping = NULL;
314 else if (thousands_sepwc == L'\0')
315 /* If we are printing multibyte characters and there is a
316 multibyte representation for the thousands separator,
317 we must ensure the wide character thousands separator
318 is available, even if it is fake. */
319 thousands_sepwc = 0xfffffffe;
322 else
323 grouping = NULL;
325 /* Fetch the argument value. */
326 #ifndef __NO_LONG_DOUBLE_MATH
327 if (info->is_long_double && sizeof (long double) > sizeof (double))
329 fpnum.ldbl = *(const long double *) args[0];
331 /* Check for special values: not a number or infinity. */
332 int res;
333 if (__isnanl (fpnum.ldbl))
335 union ieee854_long_double u = { .d = fpnum.ldbl };
336 is_neg = u.ieee.negative != 0;
337 if (isupper (info->spec))
339 special = "NAN";
340 wspecial = L"NAN";
342 else
344 special = "nan";
345 wspecial = L"nan";
348 else if ((res = __isinfl (fpnum.ldbl)))
350 is_neg = res < 0;
351 if (isupper (info->spec))
353 special = "INF";
354 wspecial = L"INF";
356 else
358 special = "inf";
359 wspecial = L"inf";
362 else
364 fracsize = __mpn_extract_long_double (fp_input,
365 (sizeof (fp_input) /
366 sizeof (fp_input[0])),
367 &exponent, &is_neg,
368 fpnum.ldbl);
369 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
372 else
373 #endif /* no long double */
375 fpnum.dbl = *(const double *) args[0];
377 /* Check for special values: not a number or infinity. */
378 int res;
379 if (__isnan (fpnum.dbl))
381 union ieee754_double u = { .d = fpnum.dbl };
382 is_neg = u.ieee.negative != 0;
383 if (isupper (info->spec))
385 special = "NAN";
386 wspecial = L"NAN";
388 else
390 special = "nan";
391 wspecial = L"nan";
394 else if ((res = __isinf (fpnum.dbl)))
396 is_neg = res < 0;
397 if (isupper (info->spec))
399 special = "INF";
400 wspecial = L"INF";
402 else
404 special = "inf";
405 wspecial = L"inf";
408 else
410 fracsize = __mpn_extract_double (fp_input,
411 (sizeof (fp_input)
412 / sizeof (fp_input[0])),
413 &exponent, &is_neg, fpnum.dbl);
414 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - DBL_MANT_DIG;
418 if (special)
420 int width = info->width;
422 if (is_neg || info->showsign || info->space)
423 --width;
424 width -= 3;
426 if (!info->left && width > 0)
427 PADN (' ', width);
429 if (is_neg)
430 outchar ('-');
431 else if (info->showsign)
432 outchar ('+');
433 else if (info->space)
434 outchar (' ');
436 PRINT (special, wspecial, 3);
438 if (info->left && width > 0)
439 PADN (' ', width);
441 return done;
445 /* We need three multiprecision variables. Now that we have the exponent
446 of the number we can allocate the needed memory. It would be more
447 efficient to use variables of the fixed maximum size but because this
448 would be really big it could lead to memory problems. */
450 mp_size_t bignum_size = ((ABS (exponent) + BITS_PER_MP_LIMB - 1)
451 / BITS_PER_MP_LIMB
452 + (LDBL_MANT_DIG / BITS_PER_MP_LIMB > 2 ? 8 : 4))
453 * sizeof (mp_limb_t);
454 frac = (mp_limb_t *) alloca (bignum_size);
455 tmp = (mp_limb_t *) alloca (bignum_size);
456 scale = (mp_limb_t *) alloca (bignum_size);
459 /* We now have to distinguish between numbers with positive and negative
460 exponents because the method used for the one is not applicable/efficient
461 for the other. */
462 scalesize = 0;
463 if (exponent > 2)
465 /* |FP| >= 8.0. */
466 int scaleexpo = 0;
467 int explog = LDBL_MAX_10_EXP_LOG;
468 int exp10 = 0;
469 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
470 int cnt_h, cnt_l, i;
472 if ((exponent + to_shift) % BITS_PER_MP_LIMB == 0)
474 MPN_COPY_DECR (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
475 fp_input, fracsize);
476 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
478 else
480 cy = __mpn_lshift (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
481 fp_input, fracsize,
482 (exponent + to_shift) % BITS_PER_MP_LIMB);
483 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
484 if (cy)
485 frac[fracsize++] = cy;
487 MPN_ZERO (frac, (exponent + to_shift) / BITS_PER_MP_LIMB);
489 assert (powers > &_fpioconst_pow10[0]);
492 --powers;
494 /* The number of the product of two binary numbers with n and m
495 bits respectively has m+n or m+n-1 bits. */
496 if (exponent >= scaleexpo + powers->p_expo - 1)
498 if (scalesize == 0)
500 #ifndef __NO_LONG_DOUBLE_MATH
501 if (LDBL_MANT_DIG > _FPIO_CONST_OFFSET * BITS_PER_MP_LIMB
502 && info->is_long_double)
504 #define _FPIO_CONST_SHIFT \
505 (((LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB) \
506 - _FPIO_CONST_OFFSET)
507 /* 64bit const offset is not enough for
508 IEEE quad long double. */
509 tmpsize = powers->arraysize + _FPIO_CONST_SHIFT;
510 memcpy (tmp + _FPIO_CONST_SHIFT,
511 &__tens[powers->arrayoff],
512 tmpsize * sizeof (mp_limb_t));
513 MPN_ZERO (tmp, _FPIO_CONST_SHIFT);
514 /* Adjust exponent, as scaleexpo will be this much
515 bigger too. */
516 exponent += _FPIO_CONST_SHIFT * BITS_PER_MP_LIMB;
518 else
519 #endif
521 tmpsize = powers->arraysize;
522 memcpy (tmp, &__tens[powers->arrayoff],
523 tmpsize * sizeof (mp_limb_t));
526 else
528 cy = __mpn_mul (tmp, scale, scalesize,
529 &__tens[powers->arrayoff
530 + _FPIO_CONST_OFFSET],
531 powers->arraysize - _FPIO_CONST_OFFSET);
532 tmpsize = scalesize + powers->arraysize - _FPIO_CONST_OFFSET;
533 if (cy == 0)
534 --tmpsize;
537 if (MPN_GE (frac, tmp))
539 int cnt;
540 MPN_ASSIGN (scale, tmp);
541 count_leading_zeros (cnt, scale[scalesize - 1]);
542 scaleexpo = (scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
543 exp10 |= 1 << explog;
546 --explog;
548 while (powers > &_fpioconst_pow10[0]);
549 exponent = exp10;
551 /* Optimize number representations. We want to represent the numbers
552 with the lowest number of bytes possible without losing any
553 bytes. Also the highest bit in the scaling factor has to be set
554 (this is a requirement of the MPN division routines). */
555 if (scalesize > 0)
557 /* Determine minimum number of zero bits at the end of
558 both numbers. */
559 for (i = 0; scale[i] == 0 && frac[i] == 0; i++)
562 /* Determine number of bits the scaling factor is misplaced. */
563 count_leading_zeros (cnt_h, scale[scalesize - 1]);
565 if (cnt_h == 0)
567 /* The highest bit of the scaling factor is already set. So
568 we only have to remove the trailing empty limbs. */
569 if (i > 0)
571 MPN_COPY_INCR (scale, scale + i, scalesize - i);
572 scalesize -= i;
573 MPN_COPY_INCR (frac, frac + i, fracsize - i);
574 fracsize -= i;
577 else
579 if (scale[i] != 0)
581 count_trailing_zeros (cnt_l, scale[i]);
582 if (frac[i] != 0)
584 int cnt_l2;
585 count_trailing_zeros (cnt_l2, frac[i]);
586 if (cnt_l2 < cnt_l)
587 cnt_l = cnt_l2;
590 else
591 count_trailing_zeros (cnt_l, frac[i]);
593 /* Now shift the numbers to their optimal position. */
594 if (i == 0 && BITS_PER_MP_LIMB - cnt_h > cnt_l)
596 /* We cannot save any memory. So just roll both numbers
597 so that the scaling factor has its highest bit set. */
599 (void) __mpn_lshift (scale, scale, scalesize, cnt_h);
600 cy = __mpn_lshift (frac, frac, fracsize, cnt_h);
601 if (cy != 0)
602 frac[fracsize++] = cy;
604 else if (BITS_PER_MP_LIMB - cnt_h <= cnt_l)
606 /* We can save memory by removing the trailing zero limbs
607 and by packing the non-zero limbs which gain another
608 free one. */
610 (void) __mpn_rshift (scale, scale + i, scalesize - i,
611 BITS_PER_MP_LIMB - cnt_h);
612 scalesize -= i + 1;
613 (void) __mpn_rshift (frac, frac + i, fracsize - i,
614 BITS_PER_MP_LIMB - cnt_h);
615 fracsize -= frac[fracsize - i - 1] == 0 ? i + 1 : i;
617 else
619 /* We can only save the memory of the limbs which are zero.
620 The non-zero parts occupy the same number of limbs. */
622 (void) __mpn_rshift (scale, scale + (i - 1),
623 scalesize - (i - 1),
624 BITS_PER_MP_LIMB - cnt_h);
625 scalesize -= i;
626 (void) __mpn_rshift (frac, frac + (i - 1),
627 fracsize - (i - 1),
628 BITS_PER_MP_LIMB - cnt_h);
629 fracsize -= frac[fracsize - (i - 1) - 1] == 0 ? i : i - 1;
634 else if (exponent < 0)
636 /* |FP| < 1.0. */
637 int exp10 = 0;
638 int explog = LDBL_MAX_10_EXP_LOG;
639 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
641 /* Now shift the input value to its right place. */
642 cy = __mpn_lshift (frac, fp_input, fracsize, to_shift);
643 frac[fracsize++] = cy;
644 assert (cy == 1 || (frac[fracsize - 2] == 0 && frac[0] == 0));
646 expsign = 1;
647 exponent = -exponent;
649 assert (powers != &_fpioconst_pow10[0]);
652 --powers;
654 if (exponent >= powers->m_expo)
656 int i, incr, cnt_h, cnt_l;
657 mp_limb_t topval[2];
659 /* The __mpn_mul function expects the first argument to be
660 bigger than the second. */
661 if (fracsize < powers->arraysize - _FPIO_CONST_OFFSET)
662 cy = __mpn_mul (tmp, &__tens[powers->arrayoff
663 + _FPIO_CONST_OFFSET],
664 powers->arraysize - _FPIO_CONST_OFFSET,
665 frac, fracsize);
666 else
667 cy = __mpn_mul (tmp, frac, fracsize,
668 &__tens[powers->arrayoff + _FPIO_CONST_OFFSET],
669 powers->arraysize - _FPIO_CONST_OFFSET);
670 tmpsize = fracsize + powers->arraysize - _FPIO_CONST_OFFSET;
671 if (cy == 0)
672 --tmpsize;
674 count_leading_zeros (cnt_h, tmp[tmpsize - 1]);
675 incr = (tmpsize - fracsize) * BITS_PER_MP_LIMB
676 + BITS_PER_MP_LIMB - 1 - cnt_h;
678 assert (incr <= powers->p_expo);
680 /* If we increased the exponent by exactly 3 we have to test
681 for overflow. This is done by comparing with 10 shifted
682 to the right position. */
683 if (incr == exponent + 3)
685 if (cnt_h <= BITS_PER_MP_LIMB - 4)
687 topval[0] = 0;
688 topval[1]
689 = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4 - cnt_h);
691 else
693 topval[0] = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4);
694 topval[1] = 0;
695 (void) __mpn_lshift (topval, topval, 2,
696 BITS_PER_MP_LIMB - cnt_h);
700 /* We have to be careful when multiplying the last factor.
701 If the result is greater than 1.0 be have to test it
702 against 10.0. If it is greater or equal to 10.0 the
703 multiplication was not valid. This is because we cannot
704 determine the number of bits in the result in advance. */
705 if (incr < exponent + 3
706 || (incr == exponent + 3 &&
707 (tmp[tmpsize - 1] < topval[1]
708 || (tmp[tmpsize - 1] == topval[1]
709 && tmp[tmpsize - 2] < topval[0]))))
711 /* The factor is right. Adapt binary and decimal
712 exponents. */
713 exponent -= incr;
714 exp10 |= 1 << explog;
716 /* If this factor yields a number greater or equal to
717 1.0, we must not shift the non-fractional digits down. */
718 if (exponent < 0)
719 cnt_h += -exponent;
721 /* Now we optimize the number representation. */
722 for (i = 0; tmp[i] == 0; ++i);
723 if (cnt_h == BITS_PER_MP_LIMB - 1)
725 MPN_COPY (frac, tmp + i, tmpsize - i);
726 fracsize = tmpsize - i;
728 else
730 count_trailing_zeros (cnt_l, tmp[i]);
732 /* Now shift the numbers to their optimal position. */
733 if (i == 0 && BITS_PER_MP_LIMB - 1 - cnt_h > cnt_l)
735 /* We cannot save any memory. Just roll the
736 number so that the leading digit is in a
737 separate limb. */
739 cy = __mpn_lshift (frac, tmp, tmpsize, cnt_h + 1);
740 fracsize = tmpsize + 1;
741 frac[fracsize - 1] = cy;
743 else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
745 (void) __mpn_rshift (frac, tmp + i, tmpsize - i,
746 BITS_PER_MP_LIMB - 1 - cnt_h);
747 fracsize = tmpsize - i;
749 else
751 /* We can only save the memory of the limbs which
752 are zero. The non-zero parts occupy the same
753 number of limbs. */
755 (void) __mpn_rshift (frac, tmp + (i - 1),
756 tmpsize - (i - 1),
757 BITS_PER_MP_LIMB - 1 - cnt_h);
758 fracsize = tmpsize - (i - 1);
763 --explog;
765 while (powers != &_fpioconst_pow10[1] && exponent > 0);
766 /* All factors but 10^-1 are tested now. */
767 if (exponent > 0)
769 int cnt_l;
771 cy = __mpn_mul_1 (tmp, frac, fracsize, 10);
772 tmpsize = fracsize;
773 assert (cy == 0 || tmp[tmpsize - 1] < 20);
775 count_trailing_zeros (cnt_l, tmp[0]);
776 if (cnt_l < MIN (4, exponent))
778 cy = __mpn_lshift (frac, tmp, tmpsize,
779 BITS_PER_MP_LIMB - MIN (4, exponent));
780 if (cy != 0)
781 frac[tmpsize++] = cy;
783 else
784 (void) __mpn_rshift (frac, tmp, tmpsize, MIN (4, exponent));
785 fracsize = tmpsize;
786 exp10 |= 1;
787 assert (frac[fracsize - 1] < 10);
789 exponent = exp10;
791 else
793 /* This is a special case. We don't need a factor because the
794 numbers are in the range of 1.0 <= |fp| < 8.0. We simply
795 shift it to the right place and divide it by 1.0 to get the
796 leading digit. (Of course this division is not really made.) */
797 assert (0 <= exponent && exponent < 3 &&
798 exponent + to_shift < BITS_PER_MP_LIMB);
800 /* Now shift the input value to its right place. */
801 cy = __mpn_lshift (frac, fp_input, fracsize, (exponent + to_shift));
802 frac[fracsize++] = cy;
803 exponent = 0;
807 int width = info->width;
808 wchar_t *wstartp, *wcp;
809 size_t chars_needed;
810 int expscale;
811 int intdig_max, intdig_no = 0;
812 int fracdig_min;
813 int fracdig_max;
814 int dig_max;
815 int significant;
816 int ngroups = 0;
817 char spec = _tolower (info->spec);
819 if (spec == 'e')
821 type = info->spec;
822 intdig_max = 1;
823 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
824 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
825 /* d . ddd e +- ddd */
826 dig_max = INT_MAX; /* Unlimited. */
827 significant = 1; /* Does not matter here. */
829 else if (spec == 'f')
831 type = 'f';
832 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
833 dig_max = INT_MAX; /* Unlimited. */
834 significant = 1; /* Does not matter here. */
835 if (expsign == 0)
837 intdig_max = exponent + 1;
838 /* This can be really big! */ /* XXX Maybe malloc if too big? */
839 chars_needed = (size_t) exponent + 1 + 1 + (size_t) fracdig_max;
841 else
843 intdig_max = 1;
844 chars_needed = 1 + 1 + (size_t) fracdig_max;
847 else
849 dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
850 if ((expsign == 0 && exponent >= dig_max)
851 || (expsign != 0 && exponent > 4))
853 if ('g' - 'G' == 'e' - 'E')
854 type = 'E' + (info->spec - 'G');
855 else
856 type = isupper (info->spec) ? 'E' : 'e';
857 fracdig_max = dig_max - 1;
858 intdig_max = 1;
859 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
861 else
863 type = 'f';
864 intdig_max = expsign == 0 ? exponent + 1 : 0;
865 fracdig_max = dig_max - intdig_max;
866 /* We need space for the significant digits and perhaps
867 for leading zeros when < 1.0. The number of leading
868 zeros can be as many as would be required for
869 exponential notation with a negative two-digit
870 exponent, which is 4. */
871 chars_needed = (size_t) dig_max + 1 + 4;
873 fracdig_min = info->alt ? fracdig_max : 0;
874 significant = 0; /* We count significant digits. */
877 if (grouping)
879 /* Guess the number of groups we will make, and thus how
880 many spaces we need for separator characters. */
881 ngroups = __guess_grouping (intdig_max, grouping);
882 /* Allocate one more character in case rounding increases the
883 number of groups. */
884 chars_needed += ngroups + 1;
887 /* Allocate buffer for output. We need two more because while rounding
888 it is possible that we need two more characters in front of all the
889 other output. If the amount of memory we have to allocate is too
890 large use `malloc' instead of `alloca'. */
891 if (__builtin_expect (chars_needed >= (size_t) -1 / sizeof (wchar_t) - 2
892 || chars_needed < fracdig_max, 0))
894 /* Some overflow occurred. */
895 __set_errno (ERANGE);
896 return -1;
898 size_t wbuffer_to_alloc = (2 + chars_needed) * sizeof (wchar_t);
899 buffer_malloced = ! __libc_use_alloca (wbuffer_to_alloc);
900 if (__builtin_expect (buffer_malloced, 0))
902 wbuffer = (wchar_t *) malloc (wbuffer_to_alloc);
903 if (wbuffer == NULL)
904 /* Signal an error to the caller. */
905 return -1;
907 else
908 wbuffer = (wchar_t *) alloca (wbuffer_to_alloc);
909 wcp = wstartp = wbuffer + 2; /* Let room for rounding. */
911 /* Do the real work: put digits in allocated buffer. */
912 if (expsign == 0 || type != 'f')
914 assert (expsign == 0 || intdig_max == 1);
915 while (intdig_no < intdig_max)
917 ++intdig_no;
918 *wcp++ = hack_digit ();
920 significant = 1;
921 if (info->alt
922 || fracdig_min > 0
923 || (fracdig_max > 0 && (fracsize > 1 || frac[0] != 0)))
924 *wcp++ = decimalwc;
926 else
928 /* |fp| < 1.0 and the selected type is 'f', so put "0."
929 in the buffer. */
930 *wcp++ = L'0';
931 --exponent;
932 *wcp++ = decimalwc;
935 /* Generate the needed number of fractional digits. */
936 int fracdig_no = 0;
937 int added_zeros = 0;
938 while (fracdig_no < fracdig_min + added_zeros
939 || (fracdig_no < fracdig_max && (fracsize > 1 || frac[0] != 0)))
941 ++fracdig_no;
942 *wcp = hack_digit ();
943 if (*wcp++ != L'0')
944 significant = 1;
945 else if (significant == 0)
947 ++fracdig_max;
948 if (fracdig_min > 0)
949 ++added_zeros;
953 /* Do rounding. */
954 wchar_t last_digit = wcp[-1] != decimalwc ? wcp[-1] : wcp[-2];
955 wchar_t next_digit = hack_digit ();
956 bool more_bits;
957 if (next_digit != L'0' && next_digit != L'5')
958 more_bits = true;
959 else if (fracsize == 1 && frac[0] == 0)
960 /* Rest of the number is zero. */
961 more_bits = false;
962 else if (scalesize == 0)
964 /* Here we have to see whether all limbs are zero since no
965 normalization happened. */
966 size_t lcnt = fracsize;
967 while (lcnt >= 1 && frac[lcnt - 1] == 0)
968 --lcnt;
969 more_bits = lcnt > 0;
971 else
972 more_bits = true;
973 int rounding_mode = get_rounding_mode ();
974 if (round_away (is_neg, (last_digit - L'0') & 1, next_digit >= L'5',
975 more_bits, rounding_mode))
977 wchar_t *wtp = wcp;
979 if (fracdig_no > 0)
981 /* Process fractional digits. Terminate if not rounded or
982 radix character is reached. */
983 int removed = 0;
984 while (*--wtp != decimalwc && *wtp == L'9')
986 *wtp = L'0';
987 ++removed;
989 if (removed == fracdig_min && added_zeros > 0)
990 --added_zeros;
991 if (*wtp != decimalwc)
992 /* Round up. */
993 (*wtp)++;
994 else if (__builtin_expect (spec == 'g' && type == 'f' && info->alt
995 && wtp == wstartp + 1
996 && wstartp[0] == L'0',
998 /* This is a special case: the rounded number is 1.0,
999 the format is 'g' or 'G', and the alternative format
1000 is selected. This means the result must be "1.". */
1001 --added_zeros;
1004 if (fracdig_no == 0 || *wtp == decimalwc)
1006 /* Round the integer digits. */
1007 if (*(wtp - 1) == decimalwc)
1008 --wtp;
1010 while (--wtp >= wstartp && *wtp == L'9')
1011 *wtp = L'0';
1013 if (wtp >= wstartp)
1014 /* Round up. */
1015 (*wtp)++;
1016 else
1017 /* It is more critical. All digits were 9's. */
1019 if (type != 'f')
1021 *wstartp = '1';
1022 exponent += expsign == 0 ? 1 : -1;
1024 /* The above exponent adjustment could lead to 1.0e-00,
1025 e.g. for 0.999999999. Make sure exponent 0 always
1026 uses + sign. */
1027 if (exponent == 0)
1028 expsign = 0;
1030 else if (intdig_no == dig_max)
1032 /* This is the case where for type %g the number fits
1033 really in the range for %f output but after rounding
1034 the number of digits is too big. */
1035 *--wstartp = decimalwc;
1036 *--wstartp = L'1';
1038 if (info->alt || fracdig_no > 0)
1040 /* Overwrite the old radix character. */
1041 wstartp[intdig_no + 2] = L'0';
1042 ++fracdig_no;
1045 fracdig_no += intdig_no;
1046 intdig_no = 1;
1047 fracdig_max = intdig_max - intdig_no;
1048 ++exponent;
1049 /* Now we must print the exponent. */
1050 type = isupper (info->spec) ? 'E' : 'e';
1052 else
1054 /* We can simply add another another digit before the
1055 radix. */
1056 *--wstartp = L'1';
1057 ++intdig_no;
1060 /* While rounding the number of digits can change.
1061 If the number now exceeds the limits remove some
1062 fractional digits. */
1063 if (intdig_no + fracdig_no > dig_max)
1065 wcp -= intdig_no + fracdig_no - dig_max;
1066 fracdig_no -= intdig_no + fracdig_no - dig_max;
1072 /* Now remove unnecessary '0' at the end of the string. */
1073 while (fracdig_no > fracdig_min + added_zeros && *(wcp - 1) == L'0')
1075 --wcp;
1076 --fracdig_no;
1078 /* If we eliminate all fractional digits we perhaps also can remove
1079 the radix character. */
1080 if (fracdig_no == 0 && !info->alt && *(wcp - 1) == decimalwc)
1081 --wcp;
1083 if (grouping)
1085 /* Rounding might have changed the number of groups. We allocated
1086 enough memory but we need here the correct number of groups. */
1087 if (intdig_no != intdig_max)
1088 ngroups = __guess_grouping (intdig_no, grouping);
1090 /* Add in separator characters, overwriting the same buffer. */
1091 wcp = group_number (wstartp, wcp, intdig_no, grouping, thousands_sepwc,
1092 ngroups);
1095 /* Write the exponent if it is needed. */
1096 if (type != 'f')
1098 if (__builtin_expect (expsign != 0 && exponent == 4 && spec == 'g', 0))
1100 /* This is another special case. The exponent of the number is
1101 really smaller than -4, which requires the 'e'/'E' format.
1102 But after rounding the number has an exponent of -4. */
1103 assert (wcp >= wstartp + 1);
1104 assert (wstartp[0] == L'1');
1105 __wmemcpy (wstartp, L"0.0001", 6);
1106 wstartp[1] = decimalwc;
1107 if (wcp >= wstartp + 2)
1109 wmemset (wstartp + 6, L'0', wcp - (wstartp + 2));
1110 wcp += 4;
1112 else
1113 wcp += 5;
1115 else
1117 *wcp++ = (wchar_t) type;
1118 *wcp++ = expsign ? L'-' : L'+';
1120 /* Find the magnitude of the exponent. */
1121 expscale = 10;
1122 while (expscale <= exponent)
1123 expscale *= 10;
1125 if (exponent < 10)
1126 /* Exponent always has at least two digits. */
1127 *wcp++ = L'0';
1128 else
1131 expscale /= 10;
1132 *wcp++ = L'0' + (exponent / expscale);
1133 exponent %= expscale;
1135 while (expscale > 10);
1136 *wcp++ = L'0' + exponent;
1140 /* Compute number of characters which must be filled with the padding
1141 character. */
1142 if (is_neg || info->showsign || info->space)
1143 --width;
1144 width -= wcp - wstartp;
1146 if (!info->left && info->pad != '0' && width > 0)
1147 PADN (info->pad, width);
1149 if (is_neg)
1150 outchar ('-');
1151 else if (info->showsign)
1152 outchar ('+');
1153 else if (info->space)
1154 outchar (' ');
1156 if (!info->left && info->pad == '0' && width > 0)
1157 PADN ('0', width);
1160 char *buffer = NULL;
1161 char *buffer_end = NULL;
1162 char *cp = NULL;
1163 char *tmpptr;
1165 if (! wide)
1167 /* Create the single byte string. */
1168 size_t decimal_len;
1169 size_t thousands_sep_len;
1170 wchar_t *copywc;
1171 size_t factor = (info->i18n
1172 ? _NL_CURRENT_WORD (LC_CTYPE, _NL_CTYPE_MB_CUR_MAX)
1173 : 1);
1175 decimal_len = strlen (decimal);
1177 if (thousands_sep == NULL)
1178 thousands_sep_len = 0;
1179 else
1180 thousands_sep_len = strlen (thousands_sep);
1182 size_t nbuffer = (2 + chars_needed * factor + decimal_len
1183 + ngroups * thousands_sep_len);
1184 if (__builtin_expect (buffer_malloced, 0))
1186 buffer = (char *) malloc (nbuffer);
1187 if (buffer == NULL)
1189 /* Signal an error to the caller. */
1190 free (wbuffer);
1191 return -1;
1194 else
1195 buffer = (char *) alloca (nbuffer);
1196 buffer_end = buffer + nbuffer;
1198 /* Now copy the wide character string. Since the character
1199 (except for the decimal point and thousands separator) must
1200 be coming from the ASCII range we can esily convert the
1201 string without mapping tables. */
1202 for (cp = buffer, copywc = wstartp; copywc < wcp; ++copywc)
1203 if (*copywc == decimalwc)
1204 cp = (char *) __mempcpy (cp, decimal, decimal_len);
1205 else if (*copywc == thousands_sepwc)
1206 cp = (char *) __mempcpy (cp, thousands_sep, thousands_sep_len);
1207 else
1208 *cp++ = (char) *copywc;
1211 tmpptr = buffer;
1212 if (__builtin_expect (info->i18n, 0))
1214 #ifdef COMPILE_WPRINTF
1215 wstartp = _i18n_number_rewrite (wstartp, wcp,
1216 wbuffer + wbuffer_to_alloc);
1217 wcp = wbuffer + wbuffer_to_alloc;
1218 assert ((uintptr_t) wbuffer <= (uintptr_t) wstartp);
1219 assert ((uintptr_t) wstartp
1220 < (uintptr_t) wbuffer + wbuffer_to_alloc);
1221 #else
1222 tmpptr = _i18n_number_rewrite (tmpptr, cp, buffer_end);
1223 cp = buffer_end;
1224 assert ((uintptr_t) buffer <= (uintptr_t) tmpptr);
1225 assert ((uintptr_t) tmpptr < (uintptr_t) buffer_end);
1226 #endif
1229 PRINT (tmpptr, wstartp, wide ? wcp - wstartp : cp - tmpptr);
1231 /* Free the memory if necessary. */
1232 if (__builtin_expect (buffer_malloced, 0))
1234 free (buffer);
1235 free (wbuffer);
1239 if (info->left && width > 0)
1240 PADN (info->pad, width);
1242 return done;
1244 ldbl_hidden_def (___printf_fp, __printf_fp)
1245 ldbl_strong_alias (___printf_fp, __printf_fp)
1247 /* Return the number of extra grouping characters that will be inserted
1248 into a number with INTDIG_MAX integer digits. */
1250 unsigned int
1251 __guess_grouping (unsigned int intdig_max, const char *grouping)
1253 unsigned int groups;
1255 /* We treat all negative values like CHAR_MAX. */
1257 if (*grouping == CHAR_MAX || *grouping <= 0)
1258 /* No grouping should be done. */
1259 return 0;
1261 groups = 0;
1262 while (intdig_max > (unsigned int) *grouping)
1264 ++groups;
1265 intdig_max -= *grouping++;
1267 if (*grouping == CHAR_MAX
1268 #if CHAR_MIN < 0
1269 || *grouping < 0
1270 #endif
1272 /* No more grouping should be done. */
1273 break;
1274 else if (*grouping == 0)
1276 /* Same grouping repeats. */
1277 groups += (intdig_max - 1) / grouping[-1];
1278 break;
1282 return groups;
1285 /* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
1286 There is guaranteed enough space past BUFEND to extend it.
1287 Return the new end of buffer. */
1289 static wchar_t *
1290 internal_function
1291 group_number (wchar_t *buf, wchar_t *bufend, unsigned int intdig_no,
1292 const char *grouping, wchar_t thousands_sep, int ngroups)
1294 wchar_t *p;
1296 if (ngroups == 0)
1297 return bufend;
1299 /* Move the fractional part down. */
1300 __wmemmove (buf + intdig_no + ngroups, buf + intdig_no,
1301 bufend - (buf + intdig_no));
1303 p = buf + intdig_no + ngroups - 1;
1306 unsigned int len = *grouping++;
1308 *p-- = buf[--intdig_no];
1309 while (--len > 0);
1310 *p-- = thousands_sep;
1312 if (*grouping == CHAR_MAX
1313 #if CHAR_MIN < 0
1314 || *grouping < 0
1315 #endif
1317 /* No more grouping should be done. */
1318 break;
1319 else if (*grouping == 0)
1320 /* Same grouping repeats. */
1321 --grouping;
1322 } while (intdig_no > (unsigned int) *grouping);
1324 /* Copy the remaining ungrouped digits. */
1326 *p-- = buf[--intdig_no];
1327 while (p > buf);
1329 return bufend + ngroups;