Hide internal printf functions [BZ #18822/21986]
[glibc.git] / stdio-common / printf_fp.c
blob2633a02cc50f4188937384d2ddc5f2b16b30e93b
1 /* Floating point output for `printf'.
2 Copyright (C) 1995-2017 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);
144 static wchar_t *group_number (wchar_t *buf, wchar_t *bufend,
145 unsigned int intdig_no, const char *grouping,
146 wchar_t thousands_sep, int ngroups)
147 internal_function;
149 struct hack_digit_param
151 /* Sign of the exponent. */
152 int expsign;
153 /* The type of output format that will be used: 'e'/'E' or 'f'. */
154 int type;
155 /* and the exponent. */
156 int exponent;
157 /* The fraction of the floting-point value in question */
158 MPN_VAR(frac);
159 /* Scaling factor. */
160 MPN_VAR(scale);
161 /* Temporary bignum value. */
162 MPN_VAR(tmp);
165 static wchar_t
166 hack_digit (struct hack_digit_param *p)
168 mp_limb_t hi;
170 if (p->expsign != 0 && p->type == 'f' && p->exponent-- > 0)
171 hi = 0;
172 else if (p->scalesize == 0)
174 hi = p->frac[p->fracsize - 1];
175 p->frac[p->fracsize - 1] = __mpn_mul_1 (p->frac, p->frac,
176 p->fracsize - 1, 10);
178 else
180 if (p->fracsize < p->scalesize)
181 hi = 0;
182 else
184 hi = mpn_divmod (p->tmp, p->frac, p->fracsize,
185 p->scale, p->scalesize);
186 p->tmp[p->fracsize - p->scalesize] = hi;
187 hi = p->tmp[0];
189 p->fracsize = p->scalesize;
190 while (p->fracsize != 0 && p->frac[p->fracsize - 1] == 0)
191 --p->fracsize;
192 if (p->fracsize == 0)
194 /* We're not prepared for an mpn variable with zero
195 limbs. */
196 p->fracsize = 1;
197 return L'0' + hi;
201 mp_limb_t _cy = __mpn_mul_1 (p->frac, p->frac, p->fracsize, 10);
202 if (_cy != 0)
203 p->frac[p->fracsize++] = _cy;
206 return L'0' + hi;
210 __printf_fp_l (FILE *fp, locale_t loc,
211 const struct printf_info *info,
212 const void *const *args)
214 /* The floating-point value to output. */
215 union
217 double dbl;
218 long double ldbl;
219 #if __HAVE_DISTINCT_FLOAT128
220 _Float128 f128;
221 #endif
223 fpnum;
225 /* Locale-dependent representation of decimal point. */
226 const char *decimal;
227 wchar_t decimalwc;
229 /* Locale-dependent thousands separator and grouping specification. */
230 const char *thousands_sep = NULL;
231 wchar_t thousands_sepwc = 0;
232 const char *grouping;
234 /* "NaN" or "Inf" for the special cases. */
235 const char *special = NULL;
236 const wchar_t *wspecial = NULL;
238 /* When _Float128 is enabled in the library and ABI-distinct from long
239 double, we need mp_limbs enough for any of them. */
240 #if __HAVE_DISTINCT_FLOAT128
241 # define GREATER_MANT_DIG FLT128_MANT_DIG
242 #else
243 # define GREATER_MANT_DIG LDBL_MANT_DIG
244 #endif
245 /* We need just a few limbs for the input before shifting to the right
246 position. */
247 mp_limb_t fp_input[(GREATER_MANT_DIG + BITS_PER_MP_LIMB - 1)
248 / BITS_PER_MP_LIMB];
249 /* We need to shift the contents of fp_input by this amount of bits. */
250 int to_shift = 0;
252 struct hack_digit_param p;
253 /* Sign of float number. */
254 int is_neg = 0;
256 /* Counter for number of written characters. */
257 int done = 0;
259 /* General helper (carry limb). */
260 mp_limb_t cy;
262 /* Nonzero if this is output on a wide character stream. */
263 int wide = info->wide;
265 /* Buffer in which we produce the output. */
266 wchar_t *wbuffer = NULL;
267 /* Flag whether wbuffer is malloc'ed or not. */
268 int buffer_malloced = 0;
270 p.expsign = 0;
272 /* Figure out the decimal point character. */
273 if (info->extra == 0)
275 decimal = _nl_lookup (loc, LC_NUMERIC, DECIMAL_POINT);
276 decimalwc = _nl_lookup_word
277 (loc, LC_NUMERIC, _NL_NUMERIC_DECIMAL_POINT_WC);
279 else
281 decimal = _nl_lookup (loc, LC_MONETARY, MON_DECIMAL_POINT);
282 if (*decimal == '\0')
283 decimal = _nl_lookup (loc, LC_NUMERIC, DECIMAL_POINT);
284 decimalwc = _nl_lookup_word (loc, LC_MONETARY,
285 _NL_MONETARY_DECIMAL_POINT_WC);
286 if (decimalwc == L'\0')
287 decimalwc = _nl_lookup_word (loc, LC_NUMERIC,
288 _NL_NUMERIC_DECIMAL_POINT_WC);
290 /* The decimal point character must not be zero. */
291 assert (*decimal != '\0');
292 assert (decimalwc != L'\0');
294 if (info->group)
296 if (info->extra == 0)
297 grouping = _nl_lookup (loc, LC_NUMERIC, GROUPING);
298 else
299 grouping = _nl_lookup (loc, LC_MONETARY, MON_GROUPING);
301 if (*grouping <= 0 || *grouping == CHAR_MAX)
302 grouping = NULL;
303 else
305 /* Figure out the thousands separator character. */
306 if (wide)
308 if (info->extra == 0)
309 thousands_sepwc = _nl_lookup_word
310 (loc, LC_NUMERIC, _NL_NUMERIC_THOUSANDS_SEP_WC);
311 else
312 thousands_sepwc =
313 _nl_lookup_word (loc, LC_MONETARY,
314 _NL_MONETARY_THOUSANDS_SEP_WC);
316 else
318 if (info->extra == 0)
319 thousands_sep = _nl_lookup (loc, LC_NUMERIC, THOUSANDS_SEP);
320 else
321 thousands_sep = _nl_lookup
322 (loc, LC_MONETARY, MON_THOUSANDS_SEP);
325 if ((wide && thousands_sepwc == L'\0')
326 || (! wide && *thousands_sep == '\0'))
327 grouping = NULL;
328 else if (thousands_sepwc == L'\0')
329 /* If we are printing multibyte characters and there is a
330 multibyte representation for the thousands separator,
331 we must ensure the wide character thousands separator
332 is available, even if it is fake. */
333 thousands_sepwc = 0xfffffffe;
336 else
337 grouping = NULL;
339 #define PRINTF_FP_FETCH(FLOAT, VAR, SUFFIX, MANT_DIG) \
341 (VAR) = *(const FLOAT *) args[0]; \
343 /* Check for special values: not a number or infinity. */ \
344 if (isnan (VAR)) \
346 is_neg = signbit (VAR); \
347 if (isupper (info->spec)) \
349 special = "NAN"; \
350 wspecial = L"NAN"; \
352 else \
354 special = "nan"; \
355 wspecial = L"nan"; \
358 else if (isinf (VAR)) \
360 is_neg = signbit (VAR); \
361 if (isupper (info->spec)) \
363 special = "INF"; \
364 wspecial = L"INF"; \
366 else \
368 special = "inf"; \
369 wspecial = L"inf"; \
372 else \
374 p.fracsize = __mpn_extract_##SUFFIX \
375 (fp_input, \
376 (sizeof (fp_input) / sizeof (fp_input[0])), \
377 &p.exponent, &is_neg, VAR); \
378 to_shift = 1 + p.fracsize * BITS_PER_MP_LIMB - MANT_DIG; \
382 /* Fetch the argument value. */
383 #if __HAVE_DISTINCT_FLOAT128
384 if (info->is_binary128)
385 PRINTF_FP_FETCH (_Float128, fpnum.f128, float128, FLT128_MANT_DIG)
386 else
387 #endif
388 #ifndef __NO_LONG_DOUBLE_MATH
389 if (info->is_long_double && sizeof (long double) > sizeof (double))
390 PRINTF_FP_FETCH (long double, fpnum.ldbl, long_double, LDBL_MANT_DIG)
391 else
392 #endif
393 PRINTF_FP_FETCH (double, fpnum.dbl, double, DBL_MANT_DIG)
395 #undef PRINTF_FP_FETCH
397 if (special)
399 int width = info->width;
401 if (is_neg || info->showsign || info->space)
402 --width;
403 width -= 3;
405 if (!info->left && width > 0)
406 PADN (' ', width);
408 if (is_neg)
409 outchar ('-');
410 else if (info->showsign)
411 outchar ('+');
412 else if (info->space)
413 outchar (' ');
415 PRINT (special, wspecial, 3);
417 if (info->left && width > 0)
418 PADN (' ', width);
420 return done;
424 /* We need three multiprecision variables. Now that we have the p.exponent
425 of the number we can allocate the needed memory. It would be more
426 efficient to use variables of the fixed maximum size but because this
427 would be really big it could lead to memory problems. */
429 mp_size_t bignum_size = ((abs (p.exponent) + BITS_PER_MP_LIMB - 1)
430 / BITS_PER_MP_LIMB
431 + (GREATER_MANT_DIG / BITS_PER_MP_LIMB > 2
432 ? 8 : 4))
433 * sizeof (mp_limb_t);
434 p.frac = (mp_limb_t *) alloca (bignum_size);
435 p.tmp = (mp_limb_t *) alloca (bignum_size);
436 p.scale = (mp_limb_t *) alloca (bignum_size);
439 /* We now have to distinguish between numbers with positive and negative
440 exponents because the method used for the one is not applicable/efficient
441 for the other. */
442 p.scalesize = 0;
443 if (p.exponent > 2)
445 /* |FP| >= 8.0. */
446 int scaleexpo = 0;
447 int explog;
448 #if __HAVE_DISTINCT_FLOAT128
449 if (info->is_binary128)
450 explog = FLT128_MAX_10_EXP_LOG;
451 else
452 explog = LDBL_MAX_10_EXP_LOG;
453 #else
454 explog = LDBL_MAX_10_EXP_LOG;
455 #endif
456 int exp10 = 0;
457 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
458 int cnt_h, cnt_l, i;
460 if ((p.exponent + to_shift) % BITS_PER_MP_LIMB == 0)
462 MPN_COPY_DECR (p.frac + (p.exponent + to_shift) / BITS_PER_MP_LIMB,
463 fp_input, p.fracsize);
464 p.fracsize += (p.exponent + to_shift) / BITS_PER_MP_LIMB;
466 else
468 cy = __mpn_lshift (p.frac +
469 (p.exponent + to_shift) / BITS_PER_MP_LIMB,
470 fp_input, p.fracsize,
471 (p.exponent + to_shift) % BITS_PER_MP_LIMB);
472 p.fracsize += (p.exponent + to_shift) / BITS_PER_MP_LIMB;
473 if (cy)
474 p.frac[p.fracsize++] = cy;
476 MPN_ZERO (p.frac, (p.exponent + to_shift) / BITS_PER_MP_LIMB);
478 assert (powers > &_fpioconst_pow10[0]);
481 --powers;
483 /* The number of the product of two binary numbers with n and m
484 bits respectively has m+n or m+n-1 bits. */
485 if (p.exponent >= scaleexpo + powers->p_expo - 1)
487 if (p.scalesize == 0)
489 #if __HAVE_DISTINCT_FLOAT128
490 if ((FLT128_MANT_DIG
491 > _FPIO_CONST_OFFSET * BITS_PER_MP_LIMB)
492 && info->is_binary128)
494 #define _FLT128_FPIO_CONST_SHIFT \
495 (((FLT128_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB) \
496 - _FPIO_CONST_OFFSET)
497 /* 64bit const offset is not enough for
498 IEEE 854 quad long double (_Float128). */
499 p.tmpsize = powers->arraysize + _FLT128_FPIO_CONST_SHIFT;
500 memcpy (p.tmp + _FLT128_FPIO_CONST_SHIFT,
501 &__tens[powers->arrayoff],
502 p.tmpsize * sizeof (mp_limb_t));
503 MPN_ZERO (p.tmp, _FLT128_FPIO_CONST_SHIFT);
504 /* Adjust p.exponent, as scaleexpo will be this much
505 bigger too. */
506 p.exponent += _FLT128_FPIO_CONST_SHIFT * BITS_PER_MP_LIMB;
508 else
509 #endif /* __HAVE_DISTINCT_FLOAT128 */
510 #ifndef __NO_LONG_DOUBLE_MATH
511 if (LDBL_MANT_DIG > _FPIO_CONST_OFFSET * BITS_PER_MP_LIMB
512 && info->is_long_double)
514 #define _FPIO_CONST_SHIFT \
515 (((LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB) \
516 - _FPIO_CONST_OFFSET)
517 /* 64bit const offset is not enough for
518 IEEE quad long double. */
519 p.tmpsize = powers->arraysize + _FPIO_CONST_SHIFT;
520 memcpy (p.tmp + _FPIO_CONST_SHIFT,
521 &__tens[powers->arrayoff],
522 p.tmpsize * sizeof (mp_limb_t));
523 MPN_ZERO (p.tmp, _FPIO_CONST_SHIFT);
524 /* Adjust p.exponent, as scaleexpo will be this much
525 bigger too. */
526 p.exponent += _FPIO_CONST_SHIFT * BITS_PER_MP_LIMB;
528 else
529 #endif
531 p.tmpsize = powers->arraysize;
532 memcpy (p.tmp, &__tens[powers->arrayoff],
533 p.tmpsize * sizeof (mp_limb_t));
536 else
538 cy = __mpn_mul (p.tmp, p.scale, p.scalesize,
539 &__tens[powers->arrayoff
540 + _FPIO_CONST_OFFSET],
541 powers->arraysize - _FPIO_CONST_OFFSET);
542 p.tmpsize = p.scalesize +
543 powers->arraysize - _FPIO_CONST_OFFSET;
544 if (cy == 0)
545 --p.tmpsize;
548 if (MPN_GE (p.frac, p.tmp))
550 int cnt;
551 MPN_ASSIGN (p.scale, p.tmp);
552 count_leading_zeros (cnt, p.scale[p.scalesize - 1]);
553 scaleexpo = (p.scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
554 exp10 |= 1 << explog;
557 --explog;
559 while (powers > &_fpioconst_pow10[0]);
560 p.exponent = exp10;
562 /* Optimize number representations. We want to represent the numbers
563 with the lowest number of bytes possible without losing any
564 bytes. Also the highest bit in the scaling factor has to be set
565 (this is a requirement of the MPN division routines). */
566 if (p.scalesize > 0)
568 /* Determine minimum number of zero bits at the end of
569 both numbers. */
570 for (i = 0; p.scale[i] == 0 && p.frac[i] == 0; i++)
573 /* Determine number of bits the scaling factor is misplaced. */
574 count_leading_zeros (cnt_h, p.scale[p.scalesize - 1]);
576 if (cnt_h == 0)
578 /* The highest bit of the scaling factor is already set. So
579 we only have to remove the trailing empty limbs. */
580 if (i > 0)
582 MPN_COPY_INCR (p.scale, p.scale + i, p.scalesize - i);
583 p.scalesize -= i;
584 MPN_COPY_INCR (p.frac, p.frac + i, p.fracsize - i);
585 p.fracsize -= i;
588 else
590 if (p.scale[i] != 0)
592 count_trailing_zeros (cnt_l, p.scale[i]);
593 if (p.frac[i] != 0)
595 int cnt_l2;
596 count_trailing_zeros (cnt_l2, p.frac[i]);
597 if (cnt_l2 < cnt_l)
598 cnt_l = cnt_l2;
601 else
602 count_trailing_zeros (cnt_l, p.frac[i]);
604 /* Now shift the numbers to their optimal position. */
605 if (i == 0 && BITS_PER_MP_LIMB - cnt_h > cnt_l)
607 /* We cannot save any memory. So just roll both numbers
608 so that the scaling factor has its highest bit set. */
610 (void) __mpn_lshift (p.scale, p.scale, p.scalesize, cnt_h);
611 cy = __mpn_lshift (p.frac, p.frac, p.fracsize, cnt_h);
612 if (cy != 0)
613 p.frac[p.fracsize++] = cy;
615 else if (BITS_PER_MP_LIMB - cnt_h <= cnt_l)
617 /* We can save memory by removing the trailing zero limbs
618 and by packing the non-zero limbs which gain another
619 free one. */
621 (void) __mpn_rshift (p.scale, p.scale + i, p.scalesize - i,
622 BITS_PER_MP_LIMB - cnt_h);
623 p.scalesize -= i + 1;
624 (void) __mpn_rshift (p.frac, p.frac + i, p.fracsize - i,
625 BITS_PER_MP_LIMB - cnt_h);
626 p.fracsize -= p.frac[p.fracsize - i - 1] == 0 ? i + 1 : i;
628 else
630 /* We can only save the memory of the limbs which are zero.
631 The non-zero parts occupy the same number of limbs. */
633 (void) __mpn_rshift (p.scale, p.scale + (i - 1),
634 p.scalesize - (i - 1),
635 BITS_PER_MP_LIMB - cnt_h);
636 p.scalesize -= i;
637 (void) __mpn_rshift (p.frac, p.frac + (i - 1),
638 p.fracsize - (i - 1),
639 BITS_PER_MP_LIMB - cnt_h);
640 p.fracsize -=
641 p.frac[p.fracsize - (i - 1) - 1] == 0 ? i : i - 1;
646 else if (p.exponent < 0)
648 /* |FP| < 1.0. */
649 int exp10 = 0;
650 int explog;
651 #if __HAVE_DISTINCT_FLOAT128
652 if (info->is_binary128)
653 explog = FLT128_MAX_10_EXP_LOG;
654 else
655 explog = LDBL_MAX_10_EXP_LOG;
656 #else
657 explog = LDBL_MAX_10_EXP_LOG;
658 #endif
659 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
661 /* Now shift the input value to its right place. */
662 cy = __mpn_lshift (p.frac, fp_input, p.fracsize, to_shift);
663 p.frac[p.fracsize++] = cy;
664 assert (cy == 1 || (p.frac[p.fracsize - 2] == 0 && p.frac[0] == 0));
666 p.expsign = 1;
667 p.exponent = -p.exponent;
669 assert (powers != &_fpioconst_pow10[0]);
672 --powers;
674 if (p.exponent >= powers->m_expo)
676 int i, incr, cnt_h, cnt_l;
677 mp_limb_t topval[2];
679 /* The __mpn_mul function expects the first argument to be
680 bigger than the second. */
681 if (p.fracsize < powers->arraysize - _FPIO_CONST_OFFSET)
682 cy = __mpn_mul (p.tmp, &__tens[powers->arrayoff
683 + _FPIO_CONST_OFFSET],
684 powers->arraysize - _FPIO_CONST_OFFSET,
685 p.frac, p.fracsize);
686 else
687 cy = __mpn_mul (p.tmp, p.frac, p.fracsize,
688 &__tens[powers->arrayoff + _FPIO_CONST_OFFSET],
689 powers->arraysize - _FPIO_CONST_OFFSET);
690 p.tmpsize = p.fracsize + powers->arraysize - _FPIO_CONST_OFFSET;
691 if (cy == 0)
692 --p.tmpsize;
694 count_leading_zeros (cnt_h, p.tmp[p.tmpsize - 1]);
695 incr = (p.tmpsize - p.fracsize) * BITS_PER_MP_LIMB
696 + BITS_PER_MP_LIMB - 1 - cnt_h;
698 assert (incr <= powers->p_expo);
700 /* If we increased the p.exponent by exactly 3 we have to test
701 for overflow. This is done by comparing with 10 shifted
702 to the right position. */
703 if (incr == p.exponent + 3)
705 if (cnt_h <= BITS_PER_MP_LIMB - 4)
707 topval[0] = 0;
708 topval[1]
709 = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4 - cnt_h);
711 else
713 topval[0] = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4);
714 topval[1] = 0;
715 (void) __mpn_lshift (topval, topval, 2,
716 BITS_PER_MP_LIMB - cnt_h);
720 /* We have to be careful when multiplying the last factor.
721 If the result is greater than 1.0 be have to test it
722 against 10.0. If it is greater or equal to 10.0 the
723 multiplication was not valid. This is because we cannot
724 determine the number of bits in the result in advance. */
725 if (incr < p.exponent + 3
726 || (incr == p.exponent + 3 &&
727 (p.tmp[p.tmpsize - 1] < topval[1]
728 || (p.tmp[p.tmpsize - 1] == topval[1]
729 && p.tmp[p.tmpsize - 2] < topval[0]))))
731 /* The factor is right. Adapt binary and decimal
732 exponents. */
733 p.exponent -= incr;
734 exp10 |= 1 << explog;
736 /* If this factor yields a number greater or equal to
737 1.0, we must not shift the non-fractional digits down. */
738 if (p.exponent < 0)
739 cnt_h += -p.exponent;
741 /* Now we optimize the number representation. */
742 for (i = 0; p.tmp[i] == 0; ++i);
743 if (cnt_h == BITS_PER_MP_LIMB - 1)
745 MPN_COPY (p.frac, p.tmp + i, p.tmpsize - i);
746 p.fracsize = p.tmpsize - i;
748 else
750 count_trailing_zeros (cnt_l, p.tmp[i]);
752 /* Now shift the numbers to their optimal position. */
753 if (i == 0 && BITS_PER_MP_LIMB - 1 - cnt_h > cnt_l)
755 /* We cannot save any memory. Just roll the
756 number so that the leading digit is in a
757 separate limb. */
759 cy = __mpn_lshift (p.frac, p.tmp, p.tmpsize,
760 cnt_h + 1);
761 p.fracsize = p.tmpsize + 1;
762 p.frac[p.fracsize - 1] = cy;
764 else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
766 (void) __mpn_rshift (p.frac, p.tmp + i, p.tmpsize - i,
767 BITS_PER_MP_LIMB - 1 - cnt_h);
768 p.fracsize = p.tmpsize - i;
770 else
772 /* We can only save the memory of the limbs which
773 are zero. The non-zero parts occupy the same
774 number of limbs. */
776 (void) __mpn_rshift (p.frac, p.tmp + (i - 1),
777 p.tmpsize - (i - 1),
778 BITS_PER_MP_LIMB - 1 - cnt_h);
779 p.fracsize = p.tmpsize - (i - 1);
784 --explog;
786 while (powers != &_fpioconst_pow10[1] && p.exponent > 0);
787 /* All factors but 10^-1 are tested now. */
788 if (p.exponent > 0)
790 int cnt_l;
792 cy = __mpn_mul_1 (p.tmp, p.frac, p.fracsize, 10);
793 p.tmpsize = p.fracsize;
794 assert (cy == 0 || p.tmp[p.tmpsize - 1] < 20);
796 count_trailing_zeros (cnt_l, p.tmp[0]);
797 if (cnt_l < MIN (4, p.exponent))
799 cy = __mpn_lshift (p.frac, p.tmp, p.tmpsize,
800 BITS_PER_MP_LIMB - MIN (4, p.exponent));
801 if (cy != 0)
802 p.frac[p.tmpsize++] = cy;
804 else
805 (void) __mpn_rshift (p.frac, p.tmp, p.tmpsize, MIN (4, p.exponent));
806 p.fracsize = p.tmpsize;
807 exp10 |= 1;
808 assert (p.frac[p.fracsize - 1] < 10);
810 p.exponent = exp10;
812 else
814 /* This is a special case. We don't need a factor because the
815 numbers are in the range of 1.0 <= |fp| < 8.0. We simply
816 shift it to the right place and divide it by 1.0 to get the
817 leading digit. (Of course this division is not really made.) */
818 assert (0 <= p.exponent && p.exponent < 3 &&
819 p.exponent + to_shift < BITS_PER_MP_LIMB);
821 /* Now shift the input value to its right place. */
822 cy = __mpn_lshift (p.frac, fp_input, p.fracsize, (p.exponent + to_shift));
823 p.frac[p.fracsize++] = cy;
824 p.exponent = 0;
828 int width = info->width;
829 wchar_t *wstartp, *wcp;
830 size_t chars_needed;
831 int expscale;
832 int intdig_max, intdig_no = 0;
833 int fracdig_min;
834 int fracdig_max;
835 int dig_max;
836 int significant;
837 int ngroups = 0;
838 char spec = _tolower (info->spec);
840 if (spec == 'e')
842 p.type = info->spec;
843 intdig_max = 1;
844 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
845 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
846 /* d . ddd e +- ddd */
847 dig_max = INT_MAX; /* Unlimited. */
848 significant = 1; /* Does not matter here. */
850 else if (spec == 'f')
852 p.type = 'f';
853 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
854 dig_max = INT_MAX; /* Unlimited. */
855 significant = 1; /* Does not matter here. */
856 if (p.expsign == 0)
858 intdig_max = p.exponent + 1;
859 /* This can be really big! */ /* XXX Maybe malloc if too big? */
860 chars_needed = (size_t) p.exponent + 1 + 1 + (size_t) fracdig_max;
862 else
864 intdig_max = 1;
865 chars_needed = 1 + 1 + (size_t) fracdig_max;
868 else
870 dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
871 if ((p.expsign == 0 && p.exponent >= dig_max)
872 || (p.expsign != 0 && p.exponent > 4))
874 if ('g' - 'G' == 'e' - 'E')
875 p.type = 'E' + (info->spec - 'G');
876 else
877 p.type = isupper (info->spec) ? 'E' : 'e';
878 fracdig_max = dig_max - 1;
879 intdig_max = 1;
880 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
882 else
884 p.type = 'f';
885 intdig_max = p.expsign == 0 ? p.exponent + 1 : 0;
886 fracdig_max = dig_max - intdig_max;
887 /* We need space for the significant digits and perhaps
888 for leading zeros when < 1.0. The number of leading
889 zeros can be as many as would be required for
890 exponential notation with a negative two-digit
891 p.exponent, which is 4. */
892 chars_needed = (size_t) dig_max + 1 + 4;
894 fracdig_min = info->alt ? fracdig_max : 0;
895 significant = 0; /* We count significant digits. */
898 if (grouping)
900 /* Guess the number of groups we will make, and thus how
901 many spaces we need for separator characters. */
902 ngroups = __guess_grouping (intdig_max, grouping);
903 /* Allocate one more character in case rounding increases the
904 number of groups. */
905 chars_needed += ngroups + 1;
908 /* Allocate buffer for output. We need two more because while rounding
909 it is possible that we need two more characters in front of all the
910 other output. If the amount of memory we have to allocate is too
911 large use `malloc' instead of `alloca'. */
912 if (__builtin_expect (chars_needed >= (size_t) -1 / sizeof (wchar_t) - 2
913 || chars_needed < fracdig_max, 0))
915 /* Some overflow occurred. */
916 __set_errno (ERANGE);
917 return -1;
919 size_t wbuffer_to_alloc = (2 + chars_needed) * sizeof (wchar_t);
920 buffer_malloced = ! __libc_use_alloca (wbuffer_to_alloc);
921 if (__builtin_expect (buffer_malloced, 0))
923 wbuffer = (wchar_t *) malloc (wbuffer_to_alloc);
924 if (wbuffer == NULL)
925 /* Signal an error to the caller. */
926 return -1;
928 else
929 wbuffer = (wchar_t *) alloca (wbuffer_to_alloc);
930 wcp = wstartp = wbuffer + 2; /* Let room for rounding. */
932 /* Do the real work: put digits in allocated buffer. */
933 if (p.expsign == 0 || p.type != 'f')
935 assert (p.expsign == 0 || intdig_max == 1);
936 while (intdig_no < intdig_max)
938 ++intdig_no;
939 *wcp++ = hack_digit (&p);
941 significant = 1;
942 if (info->alt
943 || fracdig_min > 0
944 || (fracdig_max > 0 && (p.fracsize > 1 || p.frac[0] != 0)))
945 *wcp++ = decimalwc;
947 else
949 /* |fp| < 1.0 and the selected p.type is 'f', so put "0."
950 in the buffer. */
951 *wcp++ = L'0';
952 --p.exponent;
953 *wcp++ = decimalwc;
956 /* Generate the needed number of fractional digits. */
957 int fracdig_no = 0;
958 int added_zeros = 0;
959 while (fracdig_no < fracdig_min + added_zeros
960 || (fracdig_no < fracdig_max && (p.fracsize > 1 || p.frac[0] != 0)))
962 ++fracdig_no;
963 *wcp = hack_digit (&p);
964 if (*wcp++ != L'0')
965 significant = 1;
966 else if (significant == 0)
968 ++fracdig_max;
969 if (fracdig_min > 0)
970 ++added_zeros;
974 /* Do rounding. */
975 wchar_t last_digit = wcp[-1] != decimalwc ? wcp[-1] : wcp[-2];
976 wchar_t next_digit = hack_digit (&p);
977 bool more_bits;
978 if (next_digit != L'0' && next_digit != L'5')
979 more_bits = true;
980 else if (p.fracsize == 1 && p.frac[0] == 0)
981 /* Rest of the number is zero. */
982 more_bits = false;
983 else if (p.scalesize == 0)
985 /* Here we have to see whether all limbs are zero since no
986 normalization happened. */
987 size_t lcnt = p.fracsize;
988 while (lcnt >= 1 && p.frac[lcnt - 1] == 0)
989 --lcnt;
990 more_bits = lcnt > 0;
992 else
993 more_bits = true;
994 int rounding_mode = get_rounding_mode ();
995 if (round_away (is_neg, (last_digit - L'0') & 1, next_digit >= L'5',
996 more_bits, rounding_mode))
998 wchar_t *wtp = wcp;
1000 if (fracdig_no > 0)
1002 /* Process fractional digits. Terminate if not rounded or
1003 radix character is reached. */
1004 int removed = 0;
1005 while (*--wtp != decimalwc && *wtp == L'9')
1007 *wtp = L'0';
1008 ++removed;
1010 if (removed == fracdig_min && added_zeros > 0)
1011 --added_zeros;
1012 if (*wtp != decimalwc)
1013 /* Round up. */
1014 (*wtp)++;
1015 else if (__builtin_expect (spec == 'g' && p.type == 'f' && info->alt
1016 && wtp == wstartp + 1
1017 && wstartp[0] == L'0',
1019 /* This is a special case: the rounded number is 1.0,
1020 the format is 'g' or 'G', and the alternative format
1021 is selected. This means the result must be "1.". */
1022 --added_zeros;
1025 if (fracdig_no == 0 || *wtp == decimalwc)
1027 /* Round the integer digits. */
1028 if (*(wtp - 1) == decimalwc)
1029 --wtp;
1031 while (--wtp >= wstartp && *wtp == L'9')
1032 *wtp = L'0';
1034 if (wtp >= wstartp)
1035 /* Round up. */
1036 (*wtp)++;
1037 else
1038 /* It is more critical. All digits were 9's. */
1040 if (p.type != 'f')
1042 *wstartp = '1';
1043 p.exponent += p.expsign == 0 ? 1 : -1;
1045 /* The above p.exponent adjustment could lead to 1.0e-00,
1046 e.g. for 0.999999999. Make sure p.exponent 0 always
1047 uses + sign. */
1048 if (p.exponent == 0)
1049 p.expsign = 0;
1051 else if (intdig_no == dig_max)
1053 /* This is the case where for p.type %g the number fits
1054 really in the range for %f output but after rounding
1055 the number of digits is too big. */
1056 *--wstartp = decimalwc;
1057 *--wstartp = L'1';
1059 if (info->alt || fracdig_no > 0)
1061 /* Overwrite the old radix character. */
1062 wstartp[intdig_no + 2] = L'0';
1063 ++fracdig_no;
1066 fracdig_no += intdig_no;
1067 intdig_no = 1;
1068 fracdig_max = intdig_max - intdig_no;
1069 ++p.exponent;
1070 /* Now we must print the p.exponent. */
1071 p.type = isupper (info->spec) ? 'E' : 'e';
1073 else
1075 /* We can simply add another another digit before the
1076 radix. */
1077 *--wstartp = L'1';
1078 ++intdig_no;
1081 /* While rounding the number of digits can change.
1082 If the number now exceeds the limits remove some
1083 fractional digits. */
1084 if (intdig_no + fracdig_no > dig_max)
1086 wcp -= intdig_no + fracdig_no - dig_max;
1087 fracdig_no -= intdig_no + fracdig_no - dig_max;
1093 /* Now remove unnecessary '0' at the end of the string. */
1094 while (fracdig_no > fracdig_min + added_zeros && *(wcp - 1) == L'0')
1096 --wcp;
1097 --fracdig_no;
1099 /* If we eliminate all fractional digits we perhaps also can remove
1100 the radix character. */
1101 if (fracdig_no == 0 && !info->alt && *(wcp - 1) == decimalwc)
1102 --wcp;
1104 if (grouping)
1106 /* Rounding might have changed the number of groups. We allocated
1107 enough memory but we need here the correct number of groups. */
1108 if (intdig_no != intdig_max)
1109 ngroups = __guess_grouping (intdig_no, grouping);
1111 /* Add in separator characters, overwriting the same buffer. */
1112 wcp = group_number (wstartp, wcp, intdig_no, grouping, thousands_sepwc,
1113 ngroups);
1116 /* Write the p.exponent if it is needed. */
1117 if (p.type != 'f')
1119 if (__glibc_unlikely (p.expsign != 0 && p.exponent == 4 && spec == 'g'))
1121 /* This is another special case. The p.exponent of the number is
1122 really smaller than -4, which requires the 'e'/'E' format.
1123 But after rounding the number has an p.exponent of -4. */
1124 assert (wcp >= wstartp + 1);
1125 assert (wstartp[0] == L'1');
1126 __wmemcpy (wstartp, L"0.0001", 6);
1127 wstartp[1] = decimalwc;
1128 if (wcp >= wstartp + 2)
1130 __wmemset (wstartp + 6, L'0', wcp - (wstartp + 2));
1131 wcp += 4;
1133 else
1134 wcp += 5;
1136 else
1138 *wcp++ = (wchar_t) p.type;
1139 *wcp++ = p.expsign ? L'-' : L'+';
1141 /* Find the magnitude of the p.exponent. */
1142 expscale = 10;
1143 while (expscale <= p.exponent)
1144 expscale *= 10;
1146 if (p.exponent < 10)
1147 /* Exponent always has at least two digits. */
1148 *wcp++ = L'0';
1149 else
1152 expscale /= 10;
1153 *wcp++ = L'0' + (p.exponent / expscale);
1154 p.exponent %= expscale;
1156 while (expscale > 10);
1157 *wcp++ = L'0' + p.exponent;
1161 /* Compute number of characters which must be filled with the padding
1162 character. */
1163 if (is_neg || info->showsign || info->space)
1164 --width;
1165 width -= wcp - wstartp;
1167 if (!info->left && info->pad != '0' && width > 0)
1168 PADN (info->pad, width);
1170 if (is_neg)
1171 outchar ('-');
1172 else if (info->showsign)
1173 outchar ('+');
1174 else if (info->space)
1175 outchar (' ');
1177 if (!info->left && info->pad == '0' && width > 0)
1178 PADN ('0', width);
1181 char *buffer = NULL;
1182 char *buffer_end = NULL;
1183 char *cp = NULL;
1184 char *tmpptr;
1186 if (! wide)
1188 /* Create the single byte string. */
1189 size_t decimal_len;
1190 size_t thousands_sep_len;
1191 wchar_t *copywc;
1192 size_t factor;
1193 if (info->i18n)
1194 factor = _nl_lookup_word (loc, LC_CTYPE, _NL_CTYPE_MB_CUR_MAX);
1195 else
1196 factor = 1;
1198 decimal_len = strlen (decimal);
1200 if (thousands_sep == NULL)
1201 thousands_sep_len = 0;
1202 else
1203 thousands_sep_len = strlen (thousands_sep);
1205 size_t nbuffer = (2 + chars_needed * factor + decimal_len
1206 + ngroups * thousands_sep_len);
1207 if (__glibc_unlikely (buffer_malloced))
1209 buffer = (char *) malloc (nbuffer);
1210 if (buffer == NULL)
1212 /* Signal an error to the caller. */
1213 free (wbuffer);
1214 return -1;
1217 else
1218 buffer = (char *) alloca (nbuffer);
1219 buffer_end = buffer + nbuffer;
1221 /* Now copy the wide character string. Since the character
1222 (except for the decimal point and thousands separator) must
1223 be coming from the ASCII range we can esily convert the
1224 string without mapping tables. */
1225 for (cp = buffer, copywc = wstartp; copywc < wcp; ++copywc)
1226 if (*copywc == decimalwc)
1227 cp = (char *) __mempcpy (cp, decimal, decimal_len);
1228 else if (*copywc == thousands_sepwc)
1229 cp = (char *) __mempcpy (cp, thousands_sep, thousands_sep_len);
1230 else
1231 *cp++ = (char) *copywc;
1234 tmpptr = buffer;
1235 if (__glibc_unlikely (info->i18n))
1237 #ifdef COMPILE_WPRINTF
1238 wstartp = _i18n_number_rewrite (wstartp, wcp,
1239 wbuffer + wbuffer_to_alloc);
1240 wcp = wbuffer + wbuffer_to_alloc;
1241 assert ((uintptr_t) wbuffer <= (uintptr_t) wstartp);
1242 assert ((uintptr_t) wstartp
1243 < (uintptr_t) wbuffer + wbuffer_to_alloc);
1244 #else
1245 tmpptr = _i18n_number_rewrite (tmpptr, cp, buffer_end);
1246 cp = buffer_end;
1247 assert ((uintptr_t) buffer <= (uintptr_t) tmpptr);
1248 assert ((uintptr_t) tmpptr < (uintptr_t) buffer_end);
1249 #endif
1252 PRINT (tmpptr, wstartp, wide ? wcp - wstartp : cp - tmpptr);
1254 /* Free the memory if necessary. */
1255 if (__glibc_unlikely (buffer_malloced))
1257 free (buffer);
1258 free (wbuffer);
1262 if (info->left && width > 0)
1263 PADN (info->pad, width);
1265 return done;
1267 libc_hidden_def (__printf_fp_l)
1270 ___printf_fp (FILE *fp, const struct printf_info *info,
1271 const void *const *args)
1273 return __printf_fp_l (fp, _NL_CURRENT_LOCALE, info, args);
1275 ldbl_hidden_def (___printf_fp, __printf_fp)
1276 ldbl_strong_alias (___printf_fp, __printf_fp)
1279 /* Return the number of extra grouping characters that will be inserted
1280 into a number with INTDIG_MAX integer digits. */
1282 unsigned int
1283 __guess_grouping (unsigned int intdig_max, const char *grouping)
1285 unsigned int groups;
1287 /* We treat all negative values like CHAR_MAX. */
1289 if (*grouping == CHAR_MAX || *grouping <= 0)
1290 /* No grouping should be done. */
1291 return 0;
1293 groups = 0;
1294 while (intdig_max > (unsigned int) *grouping)
1296 ++groups;
1297 intdig_max -= *grouping++;
1299 if (*grouping == CHAR_MAX
1300 #if CHAR_MIN < 0
1301 || *grouping < 0
1302 #endif
1304 /* No more grouping should be done. */
1305 break;
1306 else if (*grouping == 0)
1308 /* Same grouping repeats. */
1309 groups += (intdig_max - 1) / grouping[-1];
1310 break;
1314 return groups;
1317 /* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
1318 There is guaranteed enough space past BUFEND to extend it.
1319 Return the new end of buffer. */
1321 static wchar_t *
1322 internal_function
1323 group_number (wchar_t *buf, wchar_t *bufend, unsigned int intdig_no,
1324 const char *grouping, wchar_t thousands_sep, int ngroups)
1326 wchar_t *p;
1328 if (ngroups == 0)
1329 return bufend;
1331 /* Move the fractional part down. */
1332 __wmemmove (buf + intdig_no + ngroups, buf + intdig_no,
1333 bufend - (buf + intdig_no));
1335 p = buf + intdig_no + ngroups - 1;
1338 unsigned int len = *grouping++;
1340 *p-- = buf[--intdig_no];
1341 while (--len > 0);
1342 *p-- = thousands_sep;
1344 if (*grouping == CHAR_MAX
1345 #if CHAR_MIN < 0
1346 || *grouping < 0
1347 #endif
1349 /* No more grouping should be done. */
1350 break;
1351 else if (*grouping == 0)
1352 /* Same grouping repeats. */
1353 --grouping;
1354 } while (intdig_no > (unsigned int) *grouping);
1356 /* Copy the remaining ungrouped digits. */
1358 *p-- = buf[--intdig_no];
1359 while (p > buf);
1361 return bufend + ngroups;