2.5-18.1
[glibc.git] / stdio-common / printf_fp.c
blobc7a381a69d22cd77fba256d56aed9920dcafdb16
1 /* Floating point output for `printf'.
2 Copyright (C) 1995-2003, 2006, 2007 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Written 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 Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the 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 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA. */
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 <stdlib/gmp-impl.h>
31 #include <stdlib/longlong.h>
32 #include <stdlib/fpioconst.h>
33 #include <locale/localeinfo.h>
34 #include <limits.h>
35 #include <math.h>
36 #include <printf.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <stdlib.h>
40 #include <wchar.h>
42 #ifdef COMPILE_WPRINTF
43 # define CHAR_T wchar_t
44 #else
45 # define CHAR_T char
46 #endif
48 #include "_i18n_number.h"
50 #ifndef NDEBUG
51 # define NDEBUG /* Undefine this for debugging assertions. */
52 #endif
53 #include <assert.h>
55 /* This defines make it possible to use the same code for GNU C library and
56 the GNU I/O library. */
57 #define PUT(f, s, n) _IO_sputn (f, s, n)
58 #define PAD(f, c, n) (wide ? _IO_wpadn (f, c, n) : INTUSE(_IO_padn) (f, c, n))
59 /* We use this file GNU C library and GNU I/O library. So make
60 names equal. */
61 #undef putc
62 #define putc(c, f) (wide \
63 ? (int)_IO_putwc_unlocked (c, f) : _IO_putc_unlocked (c, f))
64 #define size_t _IO_size_t
65 #define FILE _IO_FILE
67 /* Macros for doing the actual output. */
69 #define outchar(ch) \
70 do \
71 { \
72 register const int outc = (ch); \
73 if (putc (outc, fp) == EOF) \
74 { \
75 if (buffer_malloced) \
76 free (wbuffer); \
77 return -1; \
78 } \
79 ++done; \
80 } while (0)
82 #define PRINT(ptr, wptr, len) \
83 do \
84 { \
85 register size_t outlen = (len); \
86 if (len > 20) \
87 { \
88 if (PUT (fp, wide ? (const char *) wptr : ptr, outlen) != outlen) \
89 { \
90 if (buffer_malloced) \
91 free (wbuffer); \
92 return -1; \
93 } \
94 ptr += outlen; \
95 done += outlen; \
96 } \
97 else \
98 { \
99 if (wide) \
100 while (outlen-- > 0) \
101 outchar (*wptr++); \
102 else \
103 while (outlen-- > 0) \
104 outchar (*ptr++); \
106 } while (0)
108 #define PADN(ch, len) \
109 do \
111 if (PAD (fp, ch, len) != len) \
113 if (buffer_malloced) \
114 free (wbuffer); \
115 return -1; \
117 done += len; \
119 while (0)
121 /* We use the GNU MP library to handle large numbers.
123 An MP variable occupies a varying number of entries in its array. We keep
124 track of this number for efficiency reasons. Otherwise we would always
125 have to process the whole array. */
126 #define MPN_VAR(name) mp_limb_t *name; mp_size_t name##size
128 #define MPN_ASSIGN(dst,src) \
129 memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
130 #define MPN_GE(u,v) \
131 (u##size > v##size || (u##size == v##size && __mpn_cmp (u, v, u##size) >= 0))
133 extern int __isinfl_internal (long double) attribute_hidden;
134 extern int __isnanl_internal (long double) attribute_hidden;
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 /* Digit which is result of last hack_digit() call. */
200 wchar_t digit;
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 if (__isnanl (fpnum.ldbl))
337 if (isupper (info->spec))
339 special = "NAN";
340 wspecial = L"NAN";
342 else
344 special = "nan";
345 wspecial = L"nan";
347 is_neg = 0;
349 else if (__isinfl (fpnum.ldbl))
351 if (isupper (info->spec))
353 special = "INF";
354 wspecial = L"INF";
356 else
358 special = "inf";
359 wspecial = L"inf";
361 is_neg = fpnum.ldbl < 0;
363 else
365 fracsize = __mpn_extract_long_double (fp_input,
366 (sizeof (fp_input) /
367 sizeof (fp_input[0])),
368 &exponent, &is_neg,
369 fpnum.ldbl);
370 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
373 else
374 #endif /* no long double */
376 fpnum.dbl = *(const double *) args[0];
378 /* Check for special values: not a number or infinity. */
379 if (__isnan (fpnum.dbl))
381 is_neg = 0;
382 if (isupper (info->spec))
384 special = "NAN";
385 wspecial = L"NAN";
387 else
389 special = "nan";
390 wspecial = L"nan";
393 else if (__isinf (fpnum.dbl))
395 is_neg = fpnum.dbl < 0;
396 if (isupper (info->spec))
398 special = "INF";
399 wspecial = L"INF";
401 else
403 special = "inf";
404 wspecial = L"inf";
407 else
409 fracsize = __mpn_extract_double (fp_input,
410 (sizeof (fp_input)
411 / sizeof (fp_input[0])),
412 &exponent, &is_neg, fpnum.dbl);
413 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - DBL_MANT_DIG;
417 if (special)
419 int width = info->width;
421 if (is_neg || info->showsign || info->space)
422 --width;
423 width -= 3;
425 if (!info->left && width > 0)
426 PADN (' ', width);
428 if (is_neg)
429 outchar ('-');
430 else if (info->showsign)
431 outchar ('+');
432 else if (info->space)
433 outchar (' ');
435 PRINT (special, wspecial, 3);
437 if (info->left && width > 0)
438 PADN (' ', width);
440 return done;
444 /* We need three multiprecision variables. Now that we have the exponent
445 of the number we can allocate the needed memory. It would be more
446 efficient to use variables of the fixed maximum size but because this
447 would be really big it could lead to memory problems. */
449 mp_size_t bignum_size = ((ABS (exponent) + BITS_PER_MP_LIMB - 1)
450 / BITS_PER_MP_LIMB
451 + (LDBL_MANT_DIG / BITS_PER_MP_LIMB > 2 ? 8 : 4))
452 * sizeof (mp_limb_t);
453 frac = (mp_limb_t *) alloca (bignum_size);
454 tmp = (mp_limb_t *) alloca (bignum_size);
455 scale = (mp_limb_t *) alloca (bignum_size);
458 /* We now have to distinguish between numbers with positive and negative
459 exponents because the method used for the one is not applicable/efficient
460 for the other. */
461 scalesize = 0;
462 if (exponent > 2)
464 /* |FP| >= 8.0. */
465 int scaleexpo = 0;
466 int explog = LDBL_MAX_10_EXP_LOG;
467 int exp10 = 0;
468 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
469 int cnt_h, cnt_l, i;
471 if ((exponent + to_shift) % BITS_PER_MP_LIMB == 0)
473 MPN_COPY_DECR (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
474 fp_input, fracsize);
475 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
477 else
479 cy = __mpn_lshift (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
480 fp_input, fracsize,
481 (exponent + to_shift) % BITS_PER_MP_LIMB);
482 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
483 if (cy)
484 frac[fracsize++] = cy;
486 MPN_ZERO (frac, (exponent + to_shift) / BITS_PER_MP_LIMB);
488 assert (powers > &_fpioconst_pow10[0]);
491 --powers;
493 /* The number of the product of two binary numbers with n and m
494 bits respectively has m+n or m+n-1 bits. */
495 if (exponent >= scaleexpo + powers->p_expo - 1)
497 if (scalesize == 0)
499 #ifndef __NO_LONG_DOUBLE_MATH
500 if (LDBL_MANT_DIG > _FPIO_CONST_OFFSET * BITS_PER_MP_LIMB
501 && info->is_long_double)
503 #define _FPIO_CONST_SHIFT \
504 (((LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB) \
505 - _FPIO_CONST_OFFSET)
506 /* 64bit const offset is not enough for
507 IEEE quad long double. */
508 tmpsize = powers->arraysize + _FPIO_CONST_SHIFT;
509 memcpy (tmp + _FPIO_CONST_SHIFT,
510 &__tens[powers->arrayoff],
511 tmpsize * sizeof (mp_limb_t));
512 MPN_ZERO (tmp, _FPIO_CONST_SHIFT);
513 /* Adjust exponent, as scaleexpo will be this much
514 bigger too. */
515 exponent += _FPIO_CONST_SHIFT * BITS_PER_MP_LIMB;
517 else
518 #endif
520 tmpsize = powers->arraysize;
521 memcpy (tmp, &__tens[powers->arrayoff],
522 tmpsize * sizeof (mp_limb_t));
525 else
527 cy = __mpn_mul (tmp, scale, scalesize,
528 &__tens[powers->arrayoff
529 + _FPIO_CONST_OFFSET],
530 powers->arraysize - _FPIO_CONST_OFFSET);
531 tmpsize = scalesize + powers->arraysize - _FPIO_CONST_OFFSET;
532 if (cy == 0)
533 --tmpsize;
536 if (MPN_GE (frac, tmp))
538 int cnt;
539 MPN_ASSIGN (scale, tmp);
540 count_leading_zeros (cnt, scale[scalesize - 1]);
541 scaleexpo = (scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
542 exp10 |= 1 << explog;
545 --explog;
547 while (powers > &_fpioconst_pow10[0]);
548 exponent = exp10;
550 /* Optimize number representations. We want to represent the numbers
551 with the lowest number of bytes possible without losing any
552 bytes. Also the highest bit in the scaling factor has to be set
553 (this is a requirement of the MPN division routines). */
554 if (scalesize > 0)
556 /* Determine minimum number of zero bits at the end of
557 both numbers. */
558 for (i = 0; scale[i] == 0 && frac[i] == 0; i++)
561 /* Determine number of bits the scaling factor is misplaced. */
562 count_leading_zeros (cnt_h, scale[scalesize - 1]);
564 if (cnt_h == 0)
566 /* The highest bit of the scaling factor is already set. So
567 we only have to remove the trailing empty limbs. */
568 if (i > 0)
570 MPN_COPY_INCR (scale, scale + i, scalesize - i);
571 scalesize -= i;
572 MPN_COPY_INCR (frac, frac + i, fracsize - i);
573 fracsize -= i;
576 else
578 if (scale[i] != 0)
580 count_trailing_zeros (cnt_l, scale[i]);
581 if (frac[i] != 0)
583 int cnt_l2;
584 count_trailing_zeros (cnt_l2, frac[i]);
585 if (cnt_l2 < cnt_l)
586 cnt_l = cnt_l2;
589 else
590 count_trailing_zeros (cnt_l, frac[i]);
592 /* Now shift the numbers to their optimal position. */
593 if (i == 0 && BITS_PER_MP_LIMB - cnt_h > cnt_l)
595 /* We cannot save any memory. So just roll both numbers
596 so that the scaling factor has its highest bit set. */
598 (void) __mpn_lshift (scale, scale, scalesize, cnt_h);
599 cy = __mpn_lshift (frac, frac, fracsize, cnt_h);
600 if (cy != 0)
601 frac[fracsize++] = cy;
603 else if (BITS_PER_MP_LIMB - cnt_h <= cnt_l)
605 /* We can save memory by removing the trailing zero limbs
606 and by packing the non-zero limbs which gain another
607 free one. */
609 (void) __mpn_rshift (scale, scale + i, scalesize - i,
610 BITS_PER_MP_LIMB - cnt_h);
611 scalesize -= i + 1;
612 (void) __mpn_rshift (frac, frac + i, fracsize - i,
613 BITS_PER_MP_LIMB - cnt_h);
614 fracsize -= frac[fracsize - i - 1] == 0 ? i + 1 : i;
616 else
618 /* We can only save the memory of the limbs which are zero.
619 The non-zero parts occupy the same number of limbs. */
621 (void) __mpn_rshift (scale, scale + (i - 1),
622 scalesize - (i - 1),
623 BITS_PER_MP_LIMB - cnt_h);
624 scalesize -= i;
625 (void) __mpn_rshift (frac, frac + (i - 1),
626 fracsize - (i - 1),
627 BITS_PER_MP_LIMB - cnt_h);
628 fracsize -= frac[fracsize - (i - 1) - 1] == 0 ? i : i - 1;
633 else if (exponent < 0)
635 /* |FP| < 1.0. */
636 int exp10 = 0;
637 int explog = LDBL_MAX_10_EXP_LOG;
638 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
639 mp_size_t used_limbs = fracsize - 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);
761 used_limbs = fracsize - 1;
764 --explog;
766 while (powers != &_fpioconst_pow10[1] && exponent > 0);
767 /* All factors but 10^-1 are tested now. */
768 if (exponent > 0)
770 int cnt_l;
772 cy = __mpn_mul_1 (tmp, frac, fracsize, 10);
773 tmpsize = fracsize;
774 assert (cy == 0 || tmp[tmpsize - 1] < 20);
776 count_trailing_zeros (cnt_l, tmp[0]);
777 if (cnt_l < MIN (4, exponent))
779 cy = __mpn_lshift (frac, tmp, tmpsize,
780 BITS_PER_MP_LIMB - MIN (4, exponent));
781 if (cy != 0)
782 frac[tmpsize++] = cy;
784 else
785 (void) __mpn_rshift (frac, tmp, tmpsize, MIN (4, exponent));
786 fracsize = tmpsize;
787 exp10 |= 1;
788 assert (frac[fracsize - 1] < 10);
790 exponent = exp10;
792 else
794 /* This is a special case. We don't need a factor because the
795 numbers are in the range of 1.0 <= |fp| < 8.0. We simply
796 shift it to the right place and divide it by 1.0 to get the
797 leading digit. (Of course this division is not really made.) */
798 assert (0 <= exponent && exponent < 3 &&
799 exponent + to_shift < BITS_PER_MP_LIMB);
801 /* Now shift the input value to its right place. */
802 cy = __mpn_lshift (frac, fp_input, fracsize, (exponent + to_shift));
803 frac[fracsize++] = cy;
804 exponent = 0;
808 int width = info->width;
809 wchar_t *wstartp, *wcp;
810 int chars_needed;
811 int expscale;
812 int intdig_max, intdig_no = 0;
813 int fracdig_min;
814 int fracdig_max;
815 int dig_max;
816 int significant;
817 int ngroups = 0;
818 char spec = _tolower (info->spec);
820 if (spec == 'e')
822 type = info->spec;
823 intdig_max = 1;
824 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
825 chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
826 /* d . ddd e +- ddd */
827 dig_max = INT_MAX; /* Unlimited. */
828 significant = 1; /* Does not matter here. */
830 else if (spec == 'f')
832 type = 'f';
833 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
834 dig_max = INT_MAX; /* Unlimited. */
835 significant = 1; /* Does not matter here. */
836 if (expsign == 0)
838 intdig_max = exponent + 1;
839 /* This can be really big! */ /* XXX Maybe malloc if too big? */
840 chars_needed = exponent + 1 + 1 + fracdig_max;
842 else
844 intdig_max = 1;
845 chars_needed = 1 + 1 + fracdig_max;
848 else
850 dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
851 if ((expsign == 0 && exponent >= dig_max)
852 || (expsign != 0 && exponent > 4))
854 if ('g' - 'G' == 'e' - 'E')
855 type = 'E' + (info->spec - 'G');
856 else
857 type = isupper (info->spec) ? 'E' : 'e';
858 fracdig_max = dig_max - 1;
859 intdig_max = 1;
860 chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
862 else
864 type = 'f';
865 intdig_max = expsign == 0 ? exponent + 1 : 0;
866 fracdig_max = dig_max - intdig_max;
867 /* We need space for the significant digits and perhaps
868 for leading zeros when < 1.0. The number of leading
869 zeros can be as many as would be required for
870 exponential notation with a negative two-digit
871 exponent, which is 4. */
872 chars_needed = dig_max + 1 + 4;
874 fracdig_min = info->alt ? fracdig_max : 0;
875 significant = 0; /* We count significant digits. */
878 if (grouping)
880 /* Guess the number of groups we will make, and thus how
881 many spaces we need for separator characters. */
882 ngroups = __guess_grouping (intdig_max, grouping);
883 chars_needed += ngroups;
886 /* Allocate buffer for output. We need two more because while rounding
887 it is possible that we need two more characters in front of all the
888 other output. If the amount of memory we have to allocate is too
889 large use `malloc' instead of `alloca'. */
890 buffer_malloced = ! __libc_use_alloca (chars_needed * 2 * sizeof (wchar_t));
891 if (buffer_malloced)
893 wbuffer = (wchar_t *) malloc ((2 + chars_needed) * sizeof (wchar_t));
894 if (wbuffer == NULL)
895 /* Signal an error to the caller. */
896 return -1;
898 else
899 wbuffer = (wchar_t *) alloca ((2 + chars_needed) * sizeof (wchar_t));
900 wcp = wstartp = wbuffer + 2; /* Let room for rounding. */
902 /* Do the real work: put digits in allocated buffer. */
903 if (expsign == 0 || type != 'f')
905 assert (expsign == 0 || intdig_max == 1);
906 while (intdig_no < intdig_max)
908 ++intdig_no;
909 *wcp++ = hack_digit ();
911 significant = 1;
912 if (info->alt
913 || fracdig_min > 0
914 || (fracdig_max > 0 && (fracsize > 1 || frac[0] != 0)))
915 *wcp++ = decimalwc;
917 else
919 /* |fp| < 1.0 and the selected type is 'f', so put "0."
920 in the buffer. */
921 *wcp++ = L'0';
922 --exponent;
923 *wcp++ = decimalwc;
926 /* Generate the needed number of fractional digits. */
927 int fracdig_no = 0;
928 int added_zeros = 0;
929 while (fracdig_no < fracdig_min + added_zeros
930 || (fracdig_no < fracdig_max && (fracsize > 1 || frac[0] != 0)))
932 ++fracdig_no;
933 *wcp = hack_digit ();
934 if (*wcp++ != L'0')
935 significant = 1;
936 else if (significant == 0)
938 ++fracdig_max;
939 if (fracdig_min > 0)
940 ++added_zeros;
944 /* Do rounding. */
945 digit = hack_digit ();
946 if (digit > L'4')
948 wchar_t *wtp = wcp;
950 if (digit == L'5'
951 && ((*(wcp - 1) != decimalwc && (*(wcp - 1) & 1) == 0)
952 || ((*(wcp - 1) == decimalwc && (*(wcp - 2) & 1) == 0))))
954 /* This is the critical case. */
955 if (fracsize == 1 && frac[0] == 0)
956 /* Rest of the number is zero -> round to even.
957 (IEEE 754-1985 4.1 says this is the default rounding.) */
958 goto do_expo;
959 else if (scalesize == 0)
961 /* Here we have to see whether all limbs are zero since no
962 normalization happened. */
963 size_t lcnt = fracsize;
964 while (lcnt >= 1 && frac[lcnt - 1] == 0)
965 --lcnt;
966 if (lcnt == 0)
967 /* Rest of the number is zero -> round to even.
968 (IEEE 754-1985 4.1 says this is the default rounding.) */
969 goto do_expo;
973 if (fracdig_no > 0)
975 /* Process fractional digits. Terminate if not rounded or
976 radix character is reached. */
977 int removed = 0;
978 while (*--wtp != decimalwc && *wtp == L'9')
980 *wtp = L'0';
981 ++removed;
983 if (removed == fracdig_min && added_zeros > 0)
984 --added_zeros;
985 if (*wtp != decimalwc)
986 /* Round up. */
987 (*wtp)++;
988 else if (__builtin_expect (spec == 'g' && type == 'f' && info->alt,
990 /* This is a special case: the rounded number is 1.0,
991 the format is 'g' or 'G', and the alternative format
992 is selected. This means the result must be "1.". */
993 --added_zeros;
996 if (fracdig_no == 0 || *wtp == decimalwc)
998 /* Round the integer digits. */
999 if (*(wtp - 1) == decimalwc)
1000 --wtp;
1002 while (--wtp >= wstartp && *wtp == L'9')
1003 *wtp = L'0';
1005 if (wtp >= wstartp)
1006 /* Round up. */
1007 (*wtp)++;
1008 else
1009 /* It is more critical. All digits were 9's. */
1011 if (type != 'f')
1013 *wstartp = '1';
1014 exponent += expsign == 0 ? 1 : -1;
1016 /* The above exponent adjustment could lead to 1.0e-00,
1017 e.g. for 0.999999999. Make sure exponent 0 always
1018 uses + sign. */
1019 if (exponent == 0)
1020 expsign = 0;
1022 else if (intdig_no == dig_max)
1024 /* This is the case where for type %g the number fits
1025 really in the range for %f output but after rounding
1026 the number of digits is too big. */
1027 *--wstartp = decimalwc;
1028 *--wstartp = L'1';
1030 if (info->alt || fracdig_no > 0)
1032 /* Overwrite the old radix character. */
1033 wstartp[intdig_no + 2] = L'0';
1034 ++fracdig_no;
1037 fracdig_no += intdig_no;
1038 intdig_no = 1;
1039 fracdig_max = intdig_max - intdig_no;
1040 ++exponent;
1041 /* Now we must print the exponent. */
1042 type = isupper (info->spec) ? 'E' : 'e';
1044 else
1046 /* We can simply add another another digit before the
1047 radix. */
1048 *--wstartp = L'1';
1049 ++intdig_no;
1052 /* While rounding the number of digits can change.
1053 If the number now exceeds the limits remove some
1054 fractional digits. */
1055 if (intdig_no + fracdig_no > dig_max)
1057 wcp -= intdig_no + fracdig_no - dig_max;
1058 fracdig_no -= intdig_no + fracdig_no - dig_max;
1064 do_expo:
1065 /* Now remove unnecessary '0' at the end of the string. */
1066 while (fracdig_no > fracdig_min + added_zeros && *(wcp - 1) == L'0')
1068 --wcp;
1069 --fracdig_no;
1071 /* If we eliminate all fractional digits we perhaps also can remove
1072 the radix character. */
1073 if (fracdig_no == 0 && !info->alt && *(wcp - 1) == decimalwc)
1074 --wcp;
1076 if (grouping)
1077 /* Add in separator characters, overwriting the same buffer. */
1078 wcp = group_number (wstartp, wcp, intdig_no, grouping, thousands_sepwc,
1079 ngroups);
1081 /* Write the exponent if it is needed. */
1082 if (type != 'f')
1084 if (__builtin_expect (expsign != 0 && exponent == 4 && spec == 'g', 0))
1086 /* This is another special case. The exponent of the number is
1087 really smaller than -4, which requires the 'e'/'E' format.
1088 But after rounding the number has an exponent of -4. */
1089 assert (wcp >= wstartp + 1);
1090 assert (wstartp[0] == L'1');
1091 __wmemcpy (wstartp, L"0.0001", 6);
1092 wstartp[1] = decimalwc;
1093 if (wcp >= wstartp + 2)
1095 wmemset (wstartp + 6, L'0', wcp - (wstartp + 2));
1096 wcp += 4;
1098 else
1099 wcp += 5;
1101 else
1103 *wcp++ = (wchar_t) type;
1104 *wcp++ = expsign ? L'-' : L'+';
1106 /* Find the magnitude of the exponent. */
1107 expscale = 10;
1108 while (expscale <= exponent)
1109 expscale *= 10;
1111 if (exponent < 10)
1112 /* Exponent always has at least two digits. */
1113 *wcp++ = L'0';
1114 else
1117 expscale /= 10;
1118 *wcp++ = L'0' + (exponent / expscale);
1119 exponent %= expscale;
1121 while (expscale > 10);
1122 *wcp++ = L'0' + exponent;
1126 /* Compute number of characters which must be filled with the padding
1127 character. */
1128 if (is_neg || info->showsign || info->space)
1129 --width;
1130 width -= wcp - wstartp;
1132 if (!info->left && info->pad != '0' && width > 0)
1133 PADN (info->pad, width);
1135 if (is_neg)
1136 outchar ('-');
1137 else if (info->showsign)
1138 outchar ('+');
1139 else if (info->space)
1140 outchar (' ');
1142 if (!info->left && info->pad == '0' && width > 0)
1143 PADN ('0', width);
1146 char *buffer = NULL;
1147 char *cp = NULL;
1148 char *tmpptr;
1150 if (! wide)
1152 /* Create the single byte string. */
1153 size_t decimal_len;
1154 size_t thousands_sep_len;
1155 wchar_t *copywc;
1157 decimal_len = strlen (decimal);
1159 if (thousands_sep == NULL)
1160 thousands_sep_len = 0;
1161 else
1162 thousands_sep_len = strlen (thousands_sep);
1164 if (buffer_malloced)
1166 buffer = (char *) malloc (2 + chars_needed + decimal_len
1167 + ngroups * thousands_sep_len);
1168 if (buffer == NULL)
1170 /* Signal an error to the caller. */
1171 if (buffer_malloced)
1172 free (wbuffer);
1173 return -1;
1176 else
1177 buffer = (char *) alloca (2 + chars_needed + decimal_len
1178 + ngroups * thousands_sep_len);
1180 /* Now copy the wide character string. Since the character
1181 (except for the decimal point and thousands separator) must
1182 be coming from the ASCII range we can esily convert the
1183 string without mapping tables. */
1184 for (cp = buffer, copywc = wstartp; copywc < wcp; ++copywc)
1185 if (*copywc == decimalwc)
1186 cp = (char *) __mempcpy (cp, decimal, decimal_len);
1187 else if (*copywc == thousands_sepwc)
1188 cp = (char *) __mempcpy (cp, thousands_sep, thousands_sep_len);
1189 else
1190 *cp++ = (char) *copywc;
1193 tmpptr = buffer;
1194 if (__builtin_expect (info->i18n, 0))
1196 #ifdef COMPILE_WPRINTF
1197 wstartp = _i18n_number_rewrite (wstartp, wcp);
1198 #else
1199 tmpptr = _i18n_number_rewrite (tmpptr, cp);
1200 #endif
1203 PRINT (tmpptr, wstartp, wide ? wcp - wstartp : cp - tmpptr);
1205 /* Free the memory if necessary. */
1206 if (buffer_malloced)
1208 free (buffer);
1209 free (wbuffer);
1213 if (info->left && width > 0)
1214 PADN (info->pad, width);
1216 return done;
1218 ldbl_hidden_def (___printf_fp, __printf_fp)
1219 ldbl_strong_alias (___printf_fp, __printf_fp)
1221 /* Return the number of extra grouping characters that will be inserted
1222 into a number with INTDIG_MAX integer digits. */
1224 unsigned int
1225 __guess_grouping (unsigned int intdig_max, const char *grouping)
1227 unsigned int groups;
1229 /* We treat all negative values like CHAR_MAX. */
1231 if (*grouping == CHAR_MAX || *grouping <= 0)
1232 /* No grouping should be done. */
1233 return 0;
1235 groups = 0;
1236 while (intdig_max > (unsigned int) *grouping)
1238 ++groups;
1239 intdig_max -= *grouping++;
1241 if (*grouping == CHAR_MAX
1242 #if CHAR_MIN < 0
1243 || *grouping < 0
1244 #endif
1246 /* No more grouping should be done. */
1247 break;
1248 else if (*grouping == 0)
1250 /* Same grouping repeats. */
1251 groups += (intdig_max - 1) / grouping[-1];
1252 break;
1256 return groups;
1259 /* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
1260 There is guaranteed enough space past BUFEND to extend it.
1261 Return the new end of buffer. */
1263 static wchar_t *
1264 internal_function
1265 group_number (wchar_t *buf, wchar_t *bufend, unsigned int intdig_no,
1266 const char *grouping, wchar_t thousands_sep, int ngroups)
1268 wchar_t *p;
1270 if (ngroups == 0)
1271 return bufend;
1273 /* Move the fractional part down. */
1274 __wmemmove (buf + intdig_no + ngroups, buf + intdig_no,
1275 bufend - (buf + intdig_no));
1277 p = buf + intdig_no + ngroups - 1;
1280 unsigned int len = *grouping++;
1282 *p-- = buf[--intdig_no];
1283 while (--len > 0);
1284 *p-- = thousands_sep;
1286 if (*grouping == CHAR_MAX
1287 #if CHAR_MIN < 0
1288 || *grouping < 0
1289 #endif
1291 /* No more grouping should be done. */
1292 break;
1293 else if (*grouping == 0)
1294 /* Same grouping repeats. */
1295 --grouping;
1296 } while (intdig_no > (unsigned int) *grouping);
1298 /* Copy the remaining ungrouped digits. */
1300 *p-- = buf[--intdig_no];
1301 while (p > buf);
1303 return bufend + ngroups;