Fix spelling in memusagestat.c
[glibc.git] / stdio-common / printf_fp.c
blobb60ddecef080ab6ab8c6bbe635500207545a13e5
1 /* Floating point output for `printf'.
2 Copyright (C) 1995-2003, 2006, 2007, 2008 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, write to the Free
19 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 02111-1307 USA. */
22 /* The gmp headers need some configuration frobs. */
23 #define HAVE_ALLOCA 1
25 #include <libioP.h>
26 #include <alloca.h>
27 #include <ctype.h>
28 #include <float.h>
29 #include <gmp-mparam.h>
30 #include <gmp.h>
31 #include <ieee754.h>
32 #include <stdlib/gmp-impl.h>
33 #include <stdlib/longlong.h>
34 #include <stdlib/fpioconst.h>
35 #include <locale/localeinfo.h>
36 #include <limits.h>
37 #include <math.h>
38 #include <printf.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <stdlib.h>
42 #include <wchar.h>
44 #ifdef COMPILE_WPRINTF
45 # define CHAR_T wchar_t
46 #else
47 # define CHAR_T char
48 #endif
50 #include "_i18n_number.h"
52 #ifndef NDEBUG
53 # define NDEBUG /* Undefine this for debugging assertions. */
54 #endif
55 #include <assert.h>
57 /* This defines make it possible to use the same code for GNU C library and
58 the GNU I/O library. */
59 #define PUT(f, s, n) _IO_sputn (f, s, n)
60 #define PAD(f, c, n) (wide ? _IO_wpadn (f, c, n) : INTUSE(_IO_padn) (f, c, n))
61 /* We use this file GNU C library and GNU I/O library. So make
62 names equal. */
63 #undef putc
64 #define putc(c, f) (wide \
65 ? (int)_IO_putwc_unlocked (c, f) : _IO_putc_unlocked (c, f))
66 #define size_t _IO_size_t
67 #define FILE _IO_FILE
69 /* Macros for doing the actual output. */
71 #define outchar(ch) \
72 do \
73 { \
74 register const int outc = (ch); \
75 if (putc (outc, fp) == EOF) \
76 { \
77 if (buffer_malloced) \
78 free (wbuffer); \
79 return -1; \
80 } \
81 ++done; \
82 } while (0)
84 #define PRINT(ptr, wptr, len) \
85 do \
86 { \
87 register size_t outlen = (len); \
88 if (len > 20) \
89 { \
90 if (PUT (fp, wide ? (const char *) wptr : ptr, outlen) != outlen) \
91 { \
92 if (buffer_malloced) \
93 free (wbuffer); \
94 return -1; \
95 } \
96 ptr += outlen; \
97 done += outlen; \
98 } \
99 else \
101 if (wide) \
102 while (outlen-- > 0) \
103 outchar (*wptr++); \
104 else \
105 while (outlen-- > 0) \
106 outchar (*ptr++); \
108 } while (0)
110 #define PADN(ch, len) \
111 do \
113 if (PAD (fp, ch, len) != len) \
115 if (buffer_malloced) \
116 free (wbuffer); \
117 return -1; \
119 done += len; \
121 while (0)
123 /* We use the GNU MP library to handle large numbers.
125 An MP variable occupies a varying number of entries in its array. We keep
126 track of this number for efficiency reasons. Otherwise we would always
127 have to process the whole array. */
128 #define MPN_VAR(name) mp_limb_t *name; mp_size_t name##size
130 #define MPN_ASSIGN(dst,src) \
131 memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
132 #define MPN_GE(u,v) \
133 (u##size > v##size || (u##size == v##size && __mpn_cmp (u, v, u##size) >= 0))
135 extern int __isinfl_internal (long double) attribute_hidden;
136 extern int __isnanl_internal (long double) attribute_hidden;
138 extern mp_size_t __mpn_extract_double (mp_ptr res_ptr, mp_size_t size,
139 int *expt, int *is_neg,
140 double value);
141 extern mp_size_t __mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size,
142 int *expt, int *is_neg,
143 long double value);
144 extern unsigned int __guess_grouping (unsigned int intdig_max,
145 const char *grouping);
148 static wchar_t *group_number (wchar_t *buf, wchar_t *bufend,
149 unsigned int intdig_no, const char *grouping,
150 wchar_t thousands_sep, int ngroups)
151 internal_function;
155 ___printf_fp (FILE *fp,
156 const struct printf_info *info,
157 const void *const *args)
159 /* The floating-point value to output. */
160 union
162 double dbl;
163 __long_double_t ldbl;
165 fpnum;
167 /* Locale-dependent representation of decimal point. */
168 const char *decimal;
169 wchar_t decimalwc;
171 /* Locale-dependent thousands separator and grouping specification. */
172 const char *thousands_sep = NULL;
173 wchar_t thousands_sepwc = 0;
174 const char *grouping;
176 /* "NaN" or "Inf" for the special cases. */
177 const char *special = NULL;
178 const wchar_t *wspecial = NULL;
180 /* We need just a few limbs for the input before shifting to the right
181 position. */
182 mp_limb_t fp_input[(LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB];
183 /* We need to shift the contents of fp_input by this amount of bits. */
184 int to_shift = 0;
186 /* The fraction of the floting-point value in question */
187 MPN_VAR(frac);
188 /* and the exponent. */
189 int exponent;
190 /* Sign of the exponent. */
191 int expsign = 0;
192 /* Sign of float number. */
193 int is_neg = 0;
195 /* Scaling factor. */
196 MPN_VAR(scale);
198 /* Temporary bignum value. */
199 MPN_VAR(tmp);
201 /* Digit which is result of last hack_digit() call. */
202 wchar_t digit;
204 /* The type of output format that will be used: 'e'/'E' or 'f'. */
205 int type;
207 /* Counter for number of written characters. */
208 int done = 0;
210 /* General helper (carry limb). */
211 mp_limb_t cy;
213 /* Nonzero if this is output on a wide character stream. */
214 int wide = info->wide;
216 /* Buffer in which we produce the output. */
217 wchar_t *wbuffer = NULL;
218 /* Flag whether wbuffer is malloc'ed or not. */
219 int buffer_malloced = 0;
221 auto wchar_t hack_digit (void);
223 wchar_t hack_digit (void)
225 mp_limb_t hi;
227 if (expsign != 0 && type == 'f' && exponent-- > 0)
228 hi = 0;
229 else if (scalesize == 0)
231 hi = frac[fracsize - 1];
232 frac[fracsize - 1] = __mpn_mul_1 (frac, frac, fracsize - 1, 10);
234 else
236 if (fracsize < scalesize)
237 hi = 0;
238 else
240 hi = mpn_divmod (tmp, frac, fracsize, scale, scalesize);
241 tmp[fracsize - scalesize] = hi;
242 hi = tmp[0];
244 fracsize = scalesize;
245 while (fracsize != 0 && frac[fracsize - 1] == 0)
246 --fracsize;
247 if (fracsize == 0)
249 /* We're not prepared for an mpn variable with zero
250 limbs. */
251 fracsize = 1;
252 return L'0' + hi;
256 mp_limb_t _cy = __mpn_mul_1 (frac, frac, fracsize, 10);
257 if (_cy != 0)
258 frac[fracsize++] = _cy;
261 return L'0' + hi;
265 /* Figure out the decimal point character. */
266 if (info->extra == 0)
268 decimal = _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
269 decimalwc = _NL_CURRENT_WORD (LC_NUMERIC, _NL_NUMERIC_DECIMAL_POINT_WC);
271 else
273 decimal = _NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT);
274 if (*decimal == '\0')
275 decimal = _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
276 decimalwc = _NL_CURRENT_WORD (LC_MONETARY,
277 _NL_MONETARY_DECIMAL_POINT_WC);
278 if (decimalwc == L'\0')
279 decimalwc = _NL_CURRENT_WORD (LC_NUMERIC,
280 _NL_NUMERIC_DECIMAL_POINT_WC);
282 /* The decimal point character must not be zero. */
283 assert (*decimal != '\0');
284 assert (decimalwc != L'\0');
286 if (info->group)
288 if (info->extra == 0)
289 grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
290 else
291 grouping = _NL_CURRENT (LC_MONETARY, MON_GROUPING);
293 if (*grouping <= 0 || *grouping == CHAR_MAX)
294 grouping = NULL;
295 else
297 /* Figure out the thousands separator character. */
298 if (wide)
300 if (info->extra == 0)
301 thousands_sepwc =
302 _NL_CURRENT_WORD (LC_NUMERIC, _NL_NUMERIC_THOUSANDS_SEP_WC);
303 else
304 thousands_sepwc =
305 _NL_CURRENT_WORD (LC_MONETARY,
306 _NL_MONETARY_THOUSANDS_SEP_WC);
308 else
310 if (info->extra == 0)
311 thousands_sep = _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
312 else
313 thousands_sep = _NL_CURRENT (LC_MONETARY, MON_THOUSANDS_SEP);
316 if ((wide && thousands_sepwc == L'\0')
317 || (! wide && *thousands_sep == '\0'))
318 grouping = NULL;
319 else if (thousands_sepwc == L'\0')
320 /* If we are printing multibyte characters and there is a
321 multibyte representation for the thousands separator,
322 we must ensure the wide character thousands separator
323 is available, even if it is fake. */
324 thousands_sepwc = 0xfffffffe;
327 else
328 grouping = NULL;
330 /* Fetch the argument value. */
331 #ifndef __NO_LONG_DOUBLE_MATH
332 if (info->is_long_double && sizeof (long double) > sizeof (double))
334 fpnum.ldbl = *(const long double *) args[0];
336 /* Check for special values: not a number or infinity. */
337 if (__isnanl (fpnum.ldbl))
339 union ieee854_long_double u = { .d = fpnum.ldbl };
340 is_neg = u.ieee.negative != 0;
341 if (isupper (info->spec))
343 special = "NAN";
344 wspecial = L"NAN";
346 else
348 special = "nan";
349 wspecial = L"nan";
352 else if (__isinfl (fpnum.ldbl))
354 is_neg = fpnum.ldbl < 0;
355 if (isupper (info->spec))
357 special = "INF";
358 wspecial = L"INF";
360 else
362 special = "inf";
363 wspecial = L"inf";
366 else
368 fracsize = __mpn_extract_long_double (fp_input,
369 (sizeof (fp_input) /
370 sizeof (fp_input[0])),
371 &exponent, &is_neg,
372 fpnum.ldbl);
373 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
376 else
377 #endif /* no long double */
379 fpnum.dbl = *(const double *) args[0];
381 /* Check for special values: not a number or infinity. */
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 (__isinf (fpnum.dbl))
399 is_neg = fpnum.dbl < 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];
643 mp_size_t used_limbs = fracsize - 1;
645 /* Now shift the input value to its right place. */
646 cy = __mpn_lshift (frac, fp_input, fracsize, to_shift);
647 frac[fracsize++] = cy;
648 assert (cy == 1 || (frac[fracsize - 2] == 0 && frac[0] == 0));
650 expsign = 1;
651 exponent = -exponent;
653 assert (powers != &_fpioconst_pow10[0]);
656 --powers;
658 if (exponent >= powers->m_expo)
660 int i, incr, cnt_h, cnt_l;
661 mp_limb_t topval[2];
663 /* The __mpn_mul function expects the first argument to be
664 bigger than the second. */
665 if (fracsize < powers->arraysize - _FPIO_CONST_OFFSET)
666 cy = __mpn_mul (tmp, &__tens[powers->arrayoff
667 + _FPIO_CONST_OFFSET],
668 powers->arraysize - _FPIO_CONST_OFFSET,
669 frac, fracsize);
670 else
671 cy = __mpn_mul (tmp, frac, fracsize,
672 &__tens[powers->arrayoff + _FPIO_CONST_OFFSET],
673 powers->arraysize - _FPIO_CONST_OFFSET);
674 tmpsize = fracsize + powers->arraysize - _FPIO_CONST_OFFSET;
675 if (cy == 0)
676 --tmpsize;
678 count_leading_zeros (cnt_h, tmp[tmpsize - 1]);
679 incr = (tmpsize - fracsize) * BITS_PER_MP_LIMB
680 + BITS_PER_MP_LIMB - 1 - cnt_h;
682 assert (incr <= powers->p_expo);
684 /* If we increased the exponent by exactly 3 we have to test
685 for overflow. This is done by comparing with 10 shifted
686 to the right position. */
687 if (incr == exponent + 3)
689 if (cnt_h <= BITS_PER_MP_LIMB - 4)
691 topval[0] = 0;
692 topval[1]
693 = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4 - cnt_h);
695 else
697 topval[0] = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4);
698 topval[1] = 0;
699 (void) __mpn_lshift (topval, topval, 2,
700 BITS_PER_MP_LIMB - cnt_h);
704 /* We have to be careful when multiplying the last factor.
705 If the result is greater than 1.0 be have to test it
706 against 10.0. If it is greater or equal to 10.0 the
707 multiplication was not valid. This is because we cannot
708 determine the number of bits in the result in advance. */
709 if (incr < exponent + 3
710 || (incr == exponent + 3 &&
711 (tmp[tmpsize - 1] < topval[1]
712 || (tmp[tmpsize - 1] == topval[1]
713 && tmp[tmpsize - 2] < topval[0]))))
715 /* The factor is right. Adapt binary and decimal
716 exponents. */
717 exponent -= incr;
718 exp10 |= 1 << explog;
720 /* If this factor yields a number greater or equal to
721 1.0, we must not shift the non-fractional digits down. */
722 if (exponent < 0)
723 cnt_h += -exponent;
725 /* Now we optimize the number representation. */
726 for (i = 0; tmp[i] == 0; ++i);
727 if (cnt_h == BITS_PER_MP_LIMB - 1)
729 MPN_COPY (frac, tmp + i, tmpsize - i);
730 fracsize = tmpsize - i;
732 else
734 count_trailing_zeros (cnt_l, tmp[i]);
736 /* Now shift the numbers to their optimal position. */
737 if (i == 0 && BITS_PER_MP_LIMB - 1 - cnt_h > cnt_l)
739 /* We cannot save any memory. Just roll the
740 number so that the leading digit is in a
741 separate limb. */
743 cy = __mpn_lshift (frac, tmp, tmpsize, cnt_h + 1);
744 fracsize = tmpsize + 1;
745 frac[fracsize - 1] = cy;
747 else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
749 (void) __mpn_rshift (frac, tmp + i, tmpsize - i,
750 BITS_PER_MP_LIMB - 1 - cnt_h);
751 fracsize = tmpsize - i;
753 else
755 /* We can only save the memory of the limbs which
756 are zero. The non-zero parts occupy the same
757 number of limbs. */
759 (void) __mpn_rshift (frac, tmp + (i - 1),
760 tmpsize - (i - 1),
761 BITS_PER_MP_LIMB - 1 - cnt_h);
762 fracsize = tmpsize - (i - 1);
765 used_limbs = fracsize - 1;
768 --explog;
770 while (powers != &_fpioconst_pow10[1] && exponent > 0);
771 /* All factors but 10^-1 are tested now. */
772 if (exponent > 0)
774 int cnt_l;
776 cy = __mpn_mul_1 (tmp, frac, fracsize, 10);
777 tmpsize = fracsize;
778 assert (cy == 0 || tmp[tmpsize - 1] < 20);
780 count_trailing_zeros (cnt_l, tmp[0]);
781 if (cnt_l < MIN (4, exponent))
783 cy = __mpn_lshift (frac, tmp, tmpsize,
784 BITS_PER_MP_LIMB - MIN (4, exponent));
785 if (cy != 0)
786 frac[tmpsize++] = cy;
788 else
789 (void) __mpn_rshift (frac, tmp, tmpsize, MIN (4, exponent));
790 fracsize = tmpsize;
791 exp10 |= 1;
792 assert (frac[fracsize - 1] < 10);
794 exponent = exp10;
796 else
798 /* This is a special case. We don't need a factor because the
799 numbers are in the range of 1.0 <= |fp| < 8.0. We simply
800 shift it to the right place and divide it by 1.0 to get the
801 leading digit. (Of course this division is not really made.) */
802 assert (0 <= exponent && exponent < 3 &&
803 exponent + to_shift < BITS_PER_MP_LIMB);
805 /* Now shift the input value to its right place. */
806 cy = __mpn_lshift (frac, fp_input, fracsize, (exponent + to_shift));
807 frac[fracsize++] = cy;
808 exponent = 0;
812 int width = info->width;
813 wchar_t *wstartp, *wcp;
814 size_t chars_needed;
815 int expscale;
816 int intdig_max, intdig_no = 0;
817 int fracdig_min;
818 int fracdig_max;
819 int dig_max;
820 int significant;
821 int ngroups = 0;
822 char spec = _tolower (info->spec);
824 if (spec == 'e')
826 type = info->spec;
827 intdig_max = 1;
828 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
829 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
830 /* d . ddd e +- ddd */
831 dig_max = INT_MAX; /* Unlimited. */
832 significant = 1; /* Does not matter here. */
834 else if (spec == 'f')
836 type = 'f';
837 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
838 dig_max = INT_MAX; /* Unlimited. */
839 significant = 1; /* Does not matter here. */
840 if (expsign == 0)
842 intdig_max = exponent + 1;
843 /* This can be really big! */ /* XXX Maybe malloc if too big? */
844 chars_needed = (size_t) exponent + 1 + 1 + (size_t) fracdig_max;
846 else
848 intdig_max = 1;
849 chars_needed = 1 + 1 + (size_t) fracdig_max;
852 else
854 dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
855 if ((expsign == 0 && exponent >= dig_max)
856 || (expsign != 0 && exponent > 4))
858 if ('g' - 'G' == 'e' - 'E')
859 type = 'E' + (info->spec - 'G');
860 else
861 type = isupper (info->spec) ? 'E' : 'e';
862 fracdig_max = dig_max - 1;
863 intdig_max = 1;
864 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
866 else
868 type = 'f';
869 intdig_max = expsign == 0 ? exponent + 1 : 0;
870 fracdig_max = dig_max - intdig_max;
871 /* We need space for the significant digits and perhaps
872 for leading zeros when < 1.0. The number of leading
873 zeros can be as many as would be required for
874 exponential notation with a negative two-digit
875 exponent, which is 4. */
876 chars_needed = (size_t) dig_max + 1 + 4;
878 fracdig_min = info->alt ? fracdig_max : 0;
879 significant = 0; /* We count significant digits. */
882 if (grouping)
884 /* Guess the number of groups we will make, and thus how
885 many spaces we need for separator characters. */
886 ngroups = __guess_grouping (intdig_max, grouping);
887 chars_needed += ngroups;
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 digit = hack_digit ();
958 if (digit > L'4')
960 wchar_t *wtp = wcp;
962 if (digit == L'5'
963 && ((*(wcp - 1) != decimalwc && (*(wcp - 1) & 1) == 0)
964 || ((*(wcp - 1) == decimalwc && (*(wcp - 2) & 1) == 0))))
966 /* This is the critical case. */
967 if (fracsize == 1 && frac[0] == 0)
968 /* Rest of the number is zero -> round to even.
969 (IEEE 754-1985 4.1 says this is the default rounding.) */
970 goto do_expo;
971 else if (scalesize == 0)
973 /* Here we have to see whether all limbs are zero since no
974 normalization happened. */
975 size_t lcnt = fracsize;
976 while (lcnt >= 1 && frac[lcnt - 1] == 0)
977 --lcnt;
978 if (lcnt == 0)
979 /* Rest of the number is zero -> round to even.
980 (IEEE 754-1985 4.1 says this is the default rounding.) */
981 goto do_expo;
985 if (fracdig_no > 0)
987 /* Process fractional digits. Terminate if not rounded or
988 radix character is reached. */
989 int removed = 0;
990 while (*--wtp != decimalwc && *wtp == L'9')
992 *wtp = L'0';
993 ++removed;
995 if (removed == fracdig_min && added_zeros > 0)
996 --added_zeros;
997 if (*wtp != decimalwc)
998 /* Round up. */
999 (*wtp)++;
1000 else if (__builtin_expect (spec == 'g' && type == 'f' && info->alt
1001 && wtp == wstartp + 1
1002 && wstartp[0] == L'0',
1004 /* This is a special case: the rounded number is 1.0,
1005 the format is 'g' or 'G', and the alternative format
1006 is selected. This means the result must be "1.". */
1007 --added_zeros;
1010 if (fracdig_no == 0 || *wtp == decimalwc)
1012 /* Round the integer digits. */
1013 if (*(wtp - 1) == decimalwc)
1014 --wtp;
1016 while (--wtp >= wstartp && *wtp == L'9')
1017 *wtp = L'0';
1019 if (wtp >= wstartp)
1020 /* Round up. */
1021 (*wtp)++;
1022 else
1023 /* It is more critical. All digits were 9's. */
1025 if (type != 'f')
1027 *wstartp = '1';
1028 exponent += expsign == 0 ? 1 : -1;
1030 /* The above exponent adjustment could lead to 1.0e-00,
1031 e.g. for 0.999999999. Make sure exponent 0 always
1032 uses + sign. */
1033 if (exponent == 0)
1034 expsign = 0;
1036 else if (intdig_no == dig_max)
1038 /* This is the case where for type %g the number fits
1039 really in the range for %f output but after rounding
1040 the number of digits is too big. */
1041 *--wstartp = decimalwc;
1042 *--wstartp = L'1';
1044 if (info->alt || fracdig_no > 0)
1046 /* Overwrite the old radix character. */
1047 wstartp[intdig_no + 2] = L'0';
1048 ++fracdig_no;
1051 fracdig_no += intdig_no;
1052 intdig_no = 1;
1053 fracdig_max = intdig_max - intdig_no;
1054 ++exponent;
1055 /* Now we must print the exponent. */
1056 type = isupper (info->spec) ? 'E' : 'e';
1058 else
1060 /* We can simply add another another digit before the
1061 radix. */
1062 *--wstartp = L'1';
1063 ++intdig_no;
1066 /* While rounding the number of digits can change.
1067 If the number now exceeds the limits remove some
1068 fractional digits. */
1069 if (intdig_no + fracdig_no > dig_max)
1071 wcp -= intdig_no + fracdig_no - dig_max;
1072 fracdig_no -= intdig_no + fracdig_no - dig_max;
1078 do_expo:
1079 /* Now remove unnecessary '0' at the end of the string. */
1080 while (fracdig_no > fracdig_min + added_zeros && *(wcp - 1) == L'0')
1082 --wcp;
1083 --fracdig_no;
1085 /* If we eliminate all fractional digits we perhaps also can remove
1086 the radix character. */
1087 if (fracdig_no == 0 && !info->alt && *(wcp - 1) == decimalwc)
1088 --wcp;
1090 if (grouping)
1091 /* Add in separator characters, overwriting the same buffer. */
1092 wcp = group_number (wstartp, wcp, intdig_no, grouping, thousands_sepwc,
1093 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;