benchtests: Add fmax/fmin benchmarks
[glibc.git] / stdio-common / printf_fp.c
blobfdfe06b0a74ccd789b452b2907cb41abcb5af6fa
1 /* Floating point output for `printf'.
2 Copyright (C) 1995-2016 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;
151 struct hack_digit_param
153 /* Sign of the exponent. */
154 int expsign;
155 /* The type of output format that will be used: 'e'/'E' or 'f'. */
156 int type;
157 /* and the exponent. */
158 int exponent;
159 /* The fraction of the floting-point value in question */
160 MPN_VAR(frac);
161 /* Scaling factor. */
162 MPN_VAR(scale);
163 /* Temporary bignum value. */
164 MPN_VAR(tmp);
167 static wchar_t
168 hack_digit (struct hack_digit_param *p)
170 mp_limb_t hi;
172 if (p->expsign != 0 && p->type == 'f' && p->exponent-- > 0)
173 hi = 0;
174 else if (p->scalesize == 0)
176 hi = p->frac[p->fracsize - 1];
177 p->frac[p->fracsize - 1] = __mpn_mul_1 (p->frac, p->frac,
178 p->fracsize - 1, 10);
180 else
182 if (p->fracsize < p->scalesize)
183 hi = 0;
184 else
186 hi = mpn_divmod (p->tmp, p->frac, p->fracsize,
187 p->scale, p->scalesize);
188 p->tmp[p->fracsize - p->scalesize] = hi;
189 hi = p->tmp[0];
191 p->fracsize = p->scalesize;
192 while (p->fracsize != 0 && p->frac[p->fracsize - 1] == 0)
193 --p->fracsize;
194 if (p->fracsize == 0)
196 /* We're not prepared for an mpn variable with zero
197 limbs. */
198 p->fracsize = 1;
199 return L'0' + hi;
203 mp_limb_t _cy = __mpn_mul_1 (p->frac, p->frac, p->fracsize, 10);
204 if (_cy != 0)
205 p->frac[p->fracsize++] = _cy;
208 return L'0' + hi;
212 __printf_fp_l (FILE *fp, locale_t loc,
213 const struct printf_info *info,
214 const void *const *args)
216 /* The floating-point value to output. */
217 union
219 double dbl;
220 __long_double_t ldbl;
222 fpnum;
224 /* Locale-dependent representation of decimal point. */
225 const char *decimal;
226 wchar_t decimalwc;
228 /* Locale-dependent thousands separator and grouping specification. */
229 const char *thousands_sep = NULL;
230 wchar_t thousands_sepwc = 0;
231 const char *grouping;
233 /* "NaN" or "Inf" for the special cases. */
234 const char *special = NULL;
235 const wchar_t *wspecial = NULL;
237 /* We need just a few limbs for the input before shifting to the right
238 position. */
239 mp_limb_t fp_input[(LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB];
240 /* We need to shift the contents of fp_input by this amount of bits. */
241 int to_shift = 0;
243 struct hack_digit_param p;
244 /* Sign of float number. */
245 int is_neg = 0;
247 /* Counter for number of written characters. */
248 int done = 0;
250 /* General helper (carry limb). */
251 mp_limb_t cy;
253 /* Nonzero if this is output on a wide character stream. */
254 int wide = info->wide;
256 /* Buffer in which we produce the output. */
257 wchar_t *wbuffer = NULL;
258 /* Flag whether wbuffer is malloc'ed or not. */
259 int buffer_malloced = 0;
261 p.expsign = 0;
263 /* Figure out the decimal point character. */
264 if (info->extra == 0)
266 decimal = _nl_lookup (loc, LC_NUMERIC, DECIMAL_POINT);
267 decimalwc = _nl_lookup_word
268 (loc, LC_NUMERIC, _NL_NUMERIC_DECIMAL_POINT_WC);
270 else
272 decimal = _nl_lookup (loc, LC_MONETARY, MON_DECIMAL_POINT);
273 if (*decimal == '\0')
274 decimal = _nl_lookup (loc, LC_NUMERIC, DECIMAL_POINT);
275 decimalwc = _nl_lookup_word (loc, LC_MONETARY,
276 _NL_MONETARY_DECIMAL_POINT_WC);
277 if (decimalwc == L'\0')
278 decimalwc = _nl_lookup_word (loc, LC_NUMERIC,
279 _NL_NUMERIC_DECIMAL_POINT_WC);
281 /* The decimal point character must not be zero. */
282 assert (*decimal != '\0');
283 assert (decimalwc != L'\0');
285 if (info->group)
287 if (info->extra == 0)
288 grouping = _nl_lookup (loc, LC_NUMERIC, GROUPING);
289 else
290 grouping = _nl_lookup (loc, LC_MONETARY, MON_GROUPING);
292 if (*grouping <= 0 || *grouping == CHAR_MAX)
293 grouping = NULL;
294 else
296 /* Figure out the thousands separator character. */
297 if (wide)
299 if (info->extra == 0)
300 thousands_sepwc = _nl_lookup_word
301 (loc, LC_NUMERIC, _NL_NUMERIC_THOUSANDS_SEP_WC);
302 else
303 thousands_sepwc =
304 _nl_lookup_word (loc, LC_MONETARY,
305 _NL_MONETARY_THOUSANDS_SEP_WC);
307 else
309 if (info->extra == 0)
310 thousands_sep = _nl_lookup (loc, LC_NUMERIC, THOUSANDS_SEP);
311 else
312 thousands_sep = _nl_lookup
313 (loc, 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 (isnan (fpnum.ldbl))
339 is_neg = signbit (fpnum.ldbl);
340 if (isupper (info->spec))
342 special = "NAN";
343 wspecial = L"NAN";
345 else
347 special = "nan";
348 wspecial = L"nan";
351 else if (isinf (fpnum.ldbl))
353 is_neg = signbit (fpnum.ldbl);
354 if (isupper (info->spec))
356 special = "INF";
357 wspecial = L"INF";
359 else
361 special = "inf";
362 wspecial = L"inf";
365 else
367 p.fracsize = __mpn_extract_long_double (fp_input,
368 (sizeof (fp_input) /
369 sizeof (fp_input[0])),
370 &p.exponent, &is_neg,
371 fpnum.ldbl);
372 to_shift = 1 + p.fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
375 else
376 #endif /* no long double */
378 fpnum.dbl = *(const double *) args[0];
380 /* Check for special values: not a number or infinity. */
381 if (isnan (fpnum.dbl))
383 is_neg = signbit (fpnum.dbl);
384 if (isupper (info->spec))
386 special = "NAN";
387 wspecial = L"NAN";
389 else
391 special = "nan";
392 wspecial = L"nan";
395 else if (isinf (fpnum.dbl))
397 is_neg = signbit (fpnum.dbl);
398 if (isupper (info->spec))
400 special = "INF";
401 wspecial = L"INF";
403 else
405 special = "inf";
406 wspecial = L"inf";
409 else
411 p.fracsize = __mpn_extract_double (fp_input,
412 (sizeof (fp_input)
413 / sizeof (fp_input[0])),
414 &p.exponent, &is_neg, fpnum.dbl);
415 to_shift = 1 + p.fracsize * BITS_PER_MP_LIMB - DBL_MANT_DIG;
419 if (special)
421 int width = info->width;
423 if (is_neg || info->showsign || info->space)
424 --width;
425 width -= 3;
427 if (!info->left && width > 0)
428 PADN (' ', width);
430 if (is_neg)
431 outchar ('-');
432 else if (info->showsign)
433 outchar ('+');
434 else if (info->space)
435 outchar (' ');
437 PRINT (special, wspecial, 3);
439 if (info->left && width > 0)
440 PADN (' ', width);
442 return done;
446 /* We need three multiprecision variables. Now that we have the p.exponent
447 of the number we can allocate the needed memory. It would be more
448 efficient to use variables of the fixed maximum size but because this
449 would be really big it could lead to memory problems. */
451 mp_size_t bignum_size = ((abs (p.exponent) + BITS_PER_MP_LIMB - 1)
452 / BITS_PER_MP_LIMB
453 + (LDBL_MANT_DIG / BITS_PER_MP_LIMB > 2 ? 8 : 4))
454 * sizeof (mp_limb_t);
455 p.frac = (mp_limb_t *) alloca (bignum_size);
456 p.tmp = (mp_limb_t *) alloca (bignum_size);
457 p.scale = (mp_limb_t *) alloca (bignum_size);
460 /* We now have to distinguish between numbers with positive and negative
461 exponents because the method used for the one is not applicable/efficient
462 for the other. */
463 p.scalesize = 0;
464 if (p.exponent > 2)
466 /* |FP| >= 8.0. */
467 int scaleexpo = 0;
468 int explog = LDBL_MAX_10_EXP_LOG;
469 int exp10 = 0;
470 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
471 int cnt_h, cnt_l, i;
473 if ((p.exponent + to_shift) % BITS_PER_MP_LIMB == 0)
475 MPN_COPY_DECR (p.frac + (p.exponent + to_shift) / BITS_PER_MP_LIMB,
476 fp_input, p.fracsize);
477 p.fracsize += (p.exponent + to_shift) / BITS_PER_MP_LIMB;
479 else
481 cy = __mpn_lshift (p.frac +
482 (p.exponent + to_shift) / BITS_PER_MP_LIMB,
483 fp_input, p.fracsize,
484 (p.exponent + to_shift) % BITS_PER_MP_LIMB);
485 p.fracsize += (p.exponent + to_shift) / BITS_PER_MP_LIMB;
486 if (cy)
487 p.frac[p.fracsize++] = cy;
489 MPN_ZERO (p.frac, (p.exponent + to_shift) / BITS_PER_MP_LIMB);
491 assert (powers > &_fpioconst_pow10[0]);
494 --powers;
496 /* The number of the product of two binary numbers with n and m
497 bits respectively has m+n or m+n-1 bits. */
498 if (p.exponent >= scaleexpo + powers->p_expo - 1)
500 if (p.scalesize == 0)
502 #ifndef __NO_LONG_DOUBLE_MATH
503 if (LDBL_MANT_DIG > _FPIO_CONST_OFFSET * BITS_PER_MP_LIMB
504 && info->is_long_double)
506 #define _FPIO_CONST_SHIFT \
507 (((LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB) \
508 - _FPIO_CONST_OFFSET)
509 /* 64bit const offset is not enough for
510 IEEE quad long double. */
511 p.tmpsize = powers->arraysize + _FPIO_CONST_SHIFT;
512 memcpy (p.tmp + _FPIO_CONST_SHIFT,
513 &__tens[powers->arrayoff],
514 p.tmpsize * sizeof (mp_limb_t));
515 MPN_ZERO (p.tmp, _FPIO_CONST_SHIFT);
516 /* Adjust p.exponent, as scaleexpo will be this much
517 bigger too. */
518 p.exponent += _FPIO_CONST_SHIFT * BITS_PER_MP_LIMB;
520 else
521 #endif
523 p.tmpsize = powers->arraysize;
524 memcpy (p.tmp, &__tens[powers->arrayoff],
525 p.tmpsize * sizeof (mp_limb_t));
528 else
530 cy = __mpn_mul (p.tmp, p.scale, p.scalesize,
531 &__tens[powers->arrayoff
532 + _FPIO_CONST_OFFSET],
533 powers->arraysize - _FPIO_CONST_OFFSET);
534 p.tmpsize = p.scalesize +
535 powers->arraysize - _FPIO_CONST_OFFSET;
536 if (cy == 0)
537 --p.tmpsize;
540 if (MPN_GE (p.frac, p.tmp))
542 int cnt;
543 MPN_ASSIGN (p.scale, p.tmp);
544 count_leading_zeros (cnt, p.scale[p.scalesize - 1]);
545 scaleexpo = (p.scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
546 exp10 |= 1 << explog;
549 --explog;
551 while (powers > &_fpioconst_pow10[0]);
552 p.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 (p.scalesize > 0)
560 /* Determine minimum number of zero bits at the end of
561 both numbers. */
562 for (i = 0; p.scale[i] == 0 && p.frac[i] == 0; i++)
565 /* Determine number of bits the scaling factor is misplaced. */
566 count_leading_zeros (cnt_h, p.scale[p.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 (p.scale, p.scale + i, p.scalesize - i);
575 p.scalesize -= i;
576 MPN_COPY_INCR (p.frac, p.frac + i, p.fracsize - i);
577 p.fracsize -= i;
580 else
582 if (p.scale[i] != 0)
584 count_trailing_zeros (cnt_l, p.scale[i]);
585 if (p.frac[i] != 0)
587 int cnt_l2;
588 count_trailing_zeros (cnt_l2, p.frac[i]);
589 if (cnt_l2 < cnt_l)
590 cnt_l = cnt_l2;
593 else
594 count_trailing_zeros (cnt_l, p.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 (p.scale, p.scale, p.scalesize, cnt_h);
603 cy = __mpn_lshift (p.frac, p.frac, p.fracsize, cnt_h);
604 if (cy != 0)
605 p.frac[p.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 (p.scale, p.scale + i, p.scalesize - i,
614 BITS_PER_MP_LIMB - cnt_h);
615 p.scalesize -= i + 1;
616 (void) __mpn_rshift (p.frac, p.frac + i, p.fracsize - i,
617 BITS_PER_MP_LIMB - cnt_h);
618 p.fracsize -= p.frac[p.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 (p.scale, p.scale + (i - 1),
626 p.scalesize - (i - 1),
627 BITS_PER_MP_LIMB - cnt_h);
628 p.scalesize -= i;
629 (void) __mpn_rshift (p.frac, p.frac + (i - 1),
630 p.fracsize - (i - 1),
631 BITS_PER_MP_LIMB - cnt_h);
632 p.fracsize -=
633 p.frac[p.fracsize - (i - 1) - 1] == 0 ? i : i - 1;
638 else if (p.exponent < 0)
640 /* |FP| < 1.0. */
641 int exp10 = 0;
642 int explog = LDBL_MAX_10_EXP_LOG;
643 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
645 /* Now shift the input value to its right place. */
646 cy = __mpn_lshift (p.frac, fp_input, p.fracsize, to_shift);
647 p.frac[p.fracsize++] = cy;
648 assert (cy == 1 || (p.frac[p.fracsize - 2] == 0 && p.frac[0] == 0));
650 p.expsign = 1;
651 p.exponent = -p.exponent;
653 assert (powers != &_fpioconst_pow10[0]);
656 --powers;
658 if (p.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 (p.fracsize < powers->arraysize - _FPIO_CONST_OFFSET)
666 cy = __mpn_mul (p.tmp, &__tens[powers->arrayoff
667 + _FPIO_CONST_OFFSET],
668 powers->arraysize - _FPIO_CONST_OFFSET,
669 p.frac, p.fracsize);
670 else
671 cy = __mpn_mul (p.tmp, p.frac, p.fracsize,
672 &__tens[powers->arrayoff + _FPIO_CONST_OFFSET],
673 powers->arraysize - _FPIO_CONST_OFFSET);
674 p.tmpsize = p.fracsize + powers->arraysize - _FPIO_CONST_OFFSET;
675 if (cy == 0)
676 --p.tmpsize;
678 count_leading_zeros (cnt_h, p.tmp[p.tmpsize - 1]);
679 incr = (p.tmpsize - p.fracsize) * BITS_PER_MP_LIMB
680 + BITS_PER_MP_LIMB - 1 - cnt_h;
682 assert (incr <= powers->p_expo);
684 /* If we increased the p.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 == p.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 < p.exponent + 3
710 || (incr == p.exponent + 3 &&
711 (p.tmp[p.tmpsize - 1] < topval[1]
712 || (p.tmp[p.tmpsize - 1] == topval[1]
713 && p.tmp[p.tmpsize - 2] < topval[0]))))
715 /* The factor is right. Adapt binary and decimal
716 exponents. */
717 p.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 (p.exponent < 0)
723 cnt_h += -p.exponent;
725 /* Now we optimize the number representation. */
726 for (i = 0; p.tmp[i] == 0; ++i);
727 if (cnt_h == BITS_PER_MP_LIMB - 1)
729 MPN_COPY (p.frac, p.tmp + i, p.tmpsize - i);
730 p.fracsize = p.tmpsize - i;
732 else
734 count_trailing_zeros (cnt_l, p.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 (p.frac, p.tmp, p.tmpsize,
744 cnt_h + 1);
745 p.fracsize = p.tmpsize + 1;
746 p.frac[p.fracsize - 1] = cy;
748 else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
750 (void) __mpn_rshift (p.frac, p.tmp + i, p.tmpsize - i,
751 BITS_PER_MP_LIMB - 1 - cnt_h);
752 p.fracsize = p.tmpsize - i;
754 else
756 /* We can only save the memory of the limbs which
757 are zero. The non-zero parts occupy the same
758 number of limbs. */
760 (void) __mpn_rshift (p.frac, p.tmp + (i - 1),
761 p.tmpsize - (i - 1),
762 BITS_PER_MP_LIMB - 1 - cnt_h);
763 p.fracsize = p.tmpsize - (i - 1);
768 --explog;
770 while (powers != &_fpioconst_pow10[1] && p.exponent > 0);
771 /* All factors but 10^-1 are tested now. */
772 if (p.exponent > 0)
774 int cnt_l;
776 cy = __mpn_mul_1 (p.tmp, p.frac, p.fracsize, 10);
777 p.tmpsize = p.fracsize;
778 assert (cy == 0 || p.tmp[p.tmpsize - 1] < 20);
780 count_trailing_zeros (cnt_l, p.tmp[0]);
781 if (cnt_l < MIN (4, p.exponent))
783 cy = __mpn_lshift (p.frac, p.tmp, p.tmpsize,
784 BITS_PER_MP_LIMB - MIN (4, p.exponent));
785 if (cy != 0)
786 p.frac[p.tmpsize++] = cy;
788 else
789 (void) __mpn_rshift (p.frac, p.tmp, p.tmpsize, MIN (4, p.exponent));
790 p.fracsize = p.tmpsize;
791 exp10 |= 1;
792 assert (p.frac[p.fracsize - 1] < 10);
794 p.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 <= p.exponent && p.exponent < 3 &&
803 p.exponent + to_shift < BITS_PER_MP_LIMB);
805 /* Now shift the input value to its right place. */
806 cy = __mpn_lshift (p.frac, fp_input, p.fracsize, (p.exponent + to_shift));
807 p.frac[p.fracsize++] = cy;
808 p.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 p.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 p.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 (p.expsign == 0)
842 intdig_max = p.exponent + 1;
843 /* This can be really big! */ /* XXX Maybe malloc if too big? */
844 chars_needed = (size_t) p.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 ((p.expsign == 0 && p.exponent >= dig_max)
856 || (p.expsign != 0 && p.exponent > 4))
858 if ('g' - 'G' == 'e' - 'E')
859 p.type = 'E' + (info->spec - 'G');
860 else
861 p.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 p.type = 'f';
869 intdig_max = p.expsign == 0 ? p.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 p.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 /* Allocate one more character in case rounding increases the
888 number of groups. */
889 chars_needed += ngroups + 1;
892 /* Allocate buffer for output. We need two more because while rounding
893 it is possible that we need two more characters in front of all the
894 other output. If the amount of memory we have to allocate is too
895 large use `malloc' instead of `alloca'. */
896 if (__builtin_expect (chars_needed >= (size_t) -1 / sizeof (wchar_t) - 2
897 || chars_needed < fracdig_max, 0))
899 /* Some overflow occurred. */
900 __set_errno (ERANGE);
901 return -1;
903 size_t wbuffer_to_alloc = (2 + chars_needed) * sizeof (wchar_t);
904 buffer_malloced = ! __libc_use_alloca (wbuffer_to_alloc);
905 if (__builtin_expect (buffer_malloced, 0))
907 wbuffer = (wchar_t *) malloc (wbuffer_to_alloc);
908 if (wbuffer == NULL)
909 /* Signal an error to the caller. */
910 return -1;
912 else
913 wbuffer = (wchar_t *) alloca (wbuffer_to_alloc);
914 wcp = wstartp = wbuffer + 2; /* Let room for rounding. */
916 /* Do the real work: put digits in allocated buffer. */
917 if (p.expsign == 0 || p.type != 'f')
919 assert (p.expsign == 0 || intdig_max == 1);
920 while (intdig_no < intdig_max)
922 ++intdig_no;
923 *wcp++ = hack_digit (&p);
925 significant = 1;
926 if (info->alt
927 || fracdig_min > 0
928 || (fracdig_max > 0 && (p.fracsize > 1 || p.frac[0] != 0)))
929 *wcp++ = decimalwc;
931 else
933 /* |fp| < 1.0 and the selected p.type is 'f', so put "0."
934 in the buffer. */
935 *wcp++ = L'0';
936 --p.exponent;
937 *wcp++ = decimalwc;
940 /* Generate the needed number of fractional digits. */
941 int fracdig_no = 0;
942 int added_zeros = 0;
943 while (fracdig_no < fracdig_min + added_zeros
944 || (fracdig_no < fracdig_max && (p.fracsize > 1 || p.frac[0] != 0)))
946 ++fracdig_no;
947 *wcp = hack_digit (&p);
948 if (*wcp++ != L'0')
949 significant = 1;
950 else if (significant == 0)
952 ++fracdig_max;
953 if (fracdig_min > 0)
954 ++added_zeros;
958 /* Do rounding. */
959 wchar_t last_digit = wcp[-1] != decimalwc ? wcp[-1] : wcp[-2];
960 wchar_t next_digit = hack_digit (&p);
961 bool more_bits;
962 if (next_digit != L'0' && next_digit != L'5')
963 more_bits = true;
964 else if (p.fracsize == 1 && p.frac[0] == 0)
965 /* Rest of the number is zero. */
966 more_bits = false;
967 else if (p.scalesize == 0)
969 /* Here we have to see whether all limbs are zero since no
970 normalization happened. */
971 size_t lcnt = p.fracsize;
972 while (lcnt >= 1 && p.frac[lcnt - 1] == 0)
973 --lcnt;
974 more_bits = lcnt > 0;
976 else
977 more_bits = true;
978 int rounding_mode = get_rounding_mode ();
979 if (round_away (is_neg, (last_digit - L'0') & 1, next_digit >= L'5',
980 more_bits, rounding_mode))
982 wchar_t *wtp = wcp;
984 if (fracdig_no > 0)
986 /* Process fractional digits. Terminate if not rounded or
987 radix character is reached. */
988 int removed = 0;
989 while (*--wtp != decimalwc && *wtp == L'9')
991 *wtp = L'0';
992 ++removed;
994 if (removed == fracdig_min && added_zeros > 0)
995 --added_zeros;
996 if (*wtp != decimalwc)
997 /* Round up. */
998 (*wtp)++;
999 else if (__builtin_expect (spec == 'g' && p.type == 'f' && info->alt
1000 && wtp == wstartp + 1
1001 && wstartp[0] == L'0',
1003 /* This is a special case: the rounded number is 1.0,
1004 the format is 'g' or 'G', and the alternative format
1005 is selected. This means the result must be "1.". */
1006 --added_zeros;
1009 if (fracdig_no == 0 || *wtp == decimalwc)
1011 /* Round the integer digits. */
1012 if (*(wtp - 1) == decimalwc)
1013 --wtp;
1015 while (--wtp >= wstartp && *wtp == L'9')
1016 *wtp = L'0';
1018 if (wtp >= wstartp)
1019 /* Round up. */
1020 (*wtp)++;
1021 else
1022 /* It is more critical. All digits were 9's. */
1024 if (p.type != 'f')
1026 *wstartp = '1';
1027 p.exponent += p.expsign == 0 ? 1 : -1;
1029 /* The above p.exponent adjustment could lead to 1.0e-00,
1030 e.g. for 0.999999999. Make sure p.exponent 0 always
1031 uses + sign. */
1032 if (p.exponent == 0)
1033 p.expsign = 0;
1035 else if (intdig_no == dig_max)
1037 /* This is the case where for p.type %g the number fits
1038 really in the range for %f output but after rounding
1039 the number of digits is too big. */
1040 *--wstartp = decimalwc;
1041 *--wstartp = L'1';
1043 if (info->alt || fracdig_no > 0)
1045 /* Overwrite the old radix character. */
1046 wstartp[intdig_no + 2] = L'0';
1047 ++fracdig_no;
1050 fracdig_no += intdig_no;
1051 intdig_no = 1;
1052 fracdig_max = intdig_max - intdig_no;
1053 ++p.exponent;
1054 /* Now we must print the p.exponent. */
1055 p.type = isupper (info->spec) ? 'E' : 'e';
1057 else
1059 /* We can simply add another another digit before the
1060 radix. */
1061 *--wstartp = L'1';
1062 ++intdig_no;
1065 /* While rounding the number of digits can change.
1066 If the number now exceeds the limits remove some
1067 fractional digits. */
1068 if (intdig_no + fracdig_no > dig_max)
1070 wcp -= intdig_no + fracdig_no - dig_max;
1071 fracdig_no -= intdig_no + fracdig_no - dig_max;
1077 /* Now remove unnecessary '0' at the end of the string. */
1078 while (fracdig_no > fracdig_min + added_zeros && *(wcp - 1) == L'0')
1080 --wcp;
1081 --fracdig_no;
1083 /* If we eliminate all fractional digits we perhaps also can remove
1084 the radix character. */
1085 if (fracdig_no == 0 && !info->alt && *(wcp - 1) == decimalwc)
1086 --wcp;
1088 if (grouping)
1090 /* Rounding might have changed the number of groups. We allocated
1091 enough memory but we need here the correct number of groups. */
1092 if (intdig_no != intdig_max)
1093 ngroups = __guess_grouping (intdig_no, grouping);
1095 /* Add in separator characters, overwriting the same buffer. */
1096 wcp = group_number (wstartp, wcp, intdig_no, grouping, thousands_sepwc,
1097 ngroups);
1100 /* Write the p.exponent if it is needed. */
1101 if (p.type != 'f')
1103 if (__glibc_unlikely (p.expsign != 0 && p.exponent == 4 && spec == 'g'))
1105 /* This is another special case. The p.exponent of the number is
1106 really smaller than -4, which requires the 'e'/'E' format.
1107 But after rounding the number has an p.exponent of -4. */
1108 assert (wcp >= wstartp + 1);
1109 assert (wstartp[0] == L'1');
1110 __wmemcpy (wstartp, L"0.0001", 6);
1111 wstartp[1] = decimalwc;
1112 if (wcp >= wstartp + 2)
1114 __wmemset (wstartp + 6, L'0', wcp - (wstartp + 2));
1115 wcp += 4;
1117 else
1118 wcp += 5;
1120 else
1122 *wcp++ = (wchar_t) p.type;
1123 *wcp++ = p.expsign ? L'-' : L'+';
1125 /* Find the magnitude of the p.exponent. */
1126 expscale = 10;
1127 while (expscale <= p.exponent)
1128 expscale *= 10;
1130 if (p.exponent < 10)
1131 /* Exponent always has at least two digits. */
1132 *wcp++ = L'0';
1133 else
1136 expscale /= 10;
1137 *wcp++ = L'0' + (p.exponent / expscale);
1138 p.exponent %= expscale;
1140 while (expscale > 10);
1141 *wcp++ = L'0' + p.exponent;
1145 /* Compute number of characters which must be filled with the padding
1146 character. */
1147 if (is_neg || info->showsign || info->space)
1148 --width;
1149 width -= wcp - wstartp;
1151 if (!info->left && info->pad != '0' && width > 0)
1152 PADN (info->pad, width);
1154 if (is_neg)
1155 outchar ('-');
1156 else if (info->showsign)
1157 outchar ('+');
1158 else if (info->space)
1159 outchar (' ');
1161 if (!info->left && info->pad == '0' && width > 0)
1162 PADN ('0', width);
1165 char *buffer = NULL;
1166 char *buffer_end = NULL;
1167 char *cp = NULL;
1168 char *tmpptr;
1170 if (! wide)
1172 /* Create the single byte string. */
1173 size_t decimal_len;
1174 size_t thousands_sep_len;
1175 wchar_t *copywc;
1176 size_t factor;
1177 if (info->i18n)
1178 factor = _nl_lookup_word (loc, LC_CTYPE, _NL_CTYPE_MB_CUR_MAX);
1179 else
1180 factor = 1;
1182 decimal_len = strlen (decimal);
1184 if (thousands_sep == NULL)
1185 thousands_sep_len = 0;
1186 else
1187 thousands_sep_len = strlen (thousands_sep);
1189 size_t nbuffer = (2 + chars_needed * factor + decimal_len
1190 + ngroups * thousands_sep_len);
1191 if (__glibc_unlikely (buffer_malloced))
1193 buffer = (char *) malloc (nbuffer);
1194 if (buffer == NULL)
1196 /* Signal an error to the caller. */
1197 free (wbuffer);
1198 return -1;
1201 else
1202 buffer = (char *) alloca (nbuffer);
1203 buffer_end = buffer + nbuffer;
1205 /* Now copy the wide character string. Since the character
1206 (except for the decimal point and thousands separator) must
1207 be coming from the ASCII range we can esily convert the
1208 string without mapping tables. */
1209 for (cp = buffer, copywc = wstartp; copywc < wcp; ++copywc)
1210 if (*copywc == decimalwc)
1211 cp = (char *) __mempcpy (cp, decimal, decimal_len);
1212 else if (*copywc == thousands_sepwc)
1213 cp = (char *) __mempcpy (cp, thousands_sep, thousands_sep_len);
1214 else
1215 *cp++ = (char) *copywc;
1218 tmpptr = buffer;
1219 if (__glibc_unlikely (info->i18n))
1221 #ifdef COMPILE_WPRINTF
1222 wstartp = _i18n_number_rewrite (wstartp, wcp,
1223 wbuffer + wbuffer_to_alloc);
1224 wcp = wbuffer + wbuffer_to_alloc;
1225 assert ((uintptr_t) wbuffer <= (uintptr_t) wstartp);
1226 assert ((uintptr_t) wstartp
1227 < (uintptr_t) wbuffer + wbuffer_to_alloc);
1228 #else
1229 tmpptr = _i18n_number_rewrite (tmpptr, cp, buffer_end);
1230 cp = buffer_end;
1231 assert ((uintptr_t) buffer <= (uintptr_t) tmpptr);
1232 assert ((uintptr_t) tmpptr < (uintptr_t) buffer_end);
1233 #endif
1236 PRINT (tmpptr, wstartp, wide ? wcp - wstartp : cp - tmpptr);
1238 /* Free the memory if necessary. */
1239 if (__glibc_unlikely (buffer_malloced))
1241 free (buffer);
1242 free (wbuffer);
1246 if (info->left && width > 0)
1247 PADN (info->pad, width);
1249 return done;
1251 libc_hidden_def (__printf_fp_l)
1254 ___printf_fp (FILE *fp, const struct printf_info *info,
1255 const void *const *args)
1257 return __printf_fp_l (fp, _NL_CURRENT_LOCALE, info, args);
1259 ldbl_hidden_def (___printf_fp, __printf_fp)
1260 ldbl_strong_alias (___printf_fp, __printf_fp)
1263 /* Return the number of extra grouping characters that will be inserted
1264 into a number with INTDIG_MAX integer digits. */
1266 unsigned int
1267 __guess_grouping (unsigned int intdig_max, const char *grouping)
1269 unsigned int groups;
1271 /* We treat all negative values like CHAR_MAX. */
1273 if (*grouping == CHAR_MAX || *grouping <= 0)
1274 /* No grouping should be done. */
1275 return 0;
1277 groups = 0;
1278 while (intdig_max > (unsigned int) *grouping)
1280 ++groups;
1281 intdig_max -= *grouping++;
1283 if (*grouping == CHAR_MAX
1284 #if CHAR_MIN < 0
1285 || *grouping < 0
1286 #endif
1288 /* No more grouping should be done. */
1289 break;
1290 else if (*grouping == 0)
1292 /* Same grouping repeats. */
1293 groups += (intdig_max - 1) / grouping[-1];
1294 break;
1298 return groups;
1301 /* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
1302 There is guaranteed enough space past BUFEND to extend it.
1303 Return the new end of buffer. */
1305 static wchar_t *
1306 internal_function
1307 group_number (wchar_t *buf, wchar_t *bufend, unsigned int intdig_no,
1308 const char *grouping, wchar_t thousands_sep, int ngroups)
1310 wchar_t *p;
1312 if (ngroups == 0)
1313 return bufend;
1315 /* Move the fractional part down. */
1316 __wmemmove (buf + intdig_no + ngroups, buf + intdig_no,
1317 bufend - (buf + intdig_no));
1319 p = buf + intdig_no + ngroups - 1;
1322 unsigned int len = *grouping++;
1324 *p-- = buf[--intdig_no];
1325 while (--len > 0);
1326 *p-- = thousands_sep;
1328 if (*grouping == CHAR_MAX
1329 #if CHAR_MIN < 0
1330 || *grouping < 0
1331 #endif
1333 /* No more grouping should be done. */
1334 break;
1335 else if (*grouping == 0)
1336 /* Same grouping repeats. */
1337 --grouping;
1338 } while (intdig_no > (unsigned int) *grouping);
1340 /* Copy the remaining ungrouped digits. */
1342 *p-- = buf[--intdig_no];
1343 while (p > buf);
1345 return bufend + ngroups;