update from main archive 961208
[platform/upstream/glibc.git] / stdio-common / printf_fp.c
1 /* Floating point output for `printf'.
2    Copyright (C) 1995, 1996 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Library General Public License as
8    published by the Free Software Foundation; either version 2 of the
9    License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Library General Public License for more details.
15
16    You should have received a copy of the GNU Library General Public
17    License along with the GNU C Library; see the file COPYING.LIB.  If not,
18    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 /* The gmp headers need some configuration frobs.  */
22 #define HAVE_ALLOCA 1
23
24 #ifdef USE_IN_LIBIO
25 #  include <libioP.h>
26 #else
27 #  include <stdio.h>
28 #endif
29 #include <alloca.h>
30 #include <ctype.h>
31 #include <float.h>
32 #include <gmp-mparam.h>
33 #include "../stdlib/gmp.h"
34 #include "../stdlib/gmp-impl.h"
35 #include "../stdlib/longlong.h"
36 #include "../stdlib/fpioconst.h"
37 #include "../locale/localeinfo.h"
38 #include <limits.h>
39 #include <math.h>
40 #include <printf.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <stdlib.h>
44
45 #define NDEBUG                  /* Undefine this for debugging assertions.  */
46 #include <assert.h>
47
48 /* This defines make it possible to use the same code for GNU C library and
49    the GNU I/O library.  */
50 #ifdef USE_IN_LIBIO
51 #  define PUT(f, s, n) _IO_sputn (f, s, n)
52 #  define PAD(f, c, n) _IO_padn (f, c, n)
53 /* We use this file GNU C library and GNU I/O library.  So make
54    names equal.  */
55 #  undef putc
56 #  define putc(c, f) _IO_putc_unlocked (c, f)
57 #  define size_t     _IO_size_t
58 #  define FILE       _IO_FILE
59 #else   /* ! USE_IN_LIBIO */
60 #  define PUT(f, s, n) fwrite (s, 1, n, f)
61 #  define PAD(f, c, n) __printf_pad (f, c, n)
62 ssize_t __printf_pad __P ((FILE *, char pad, int n)); /* In vfprintf.c.  */
63 #endif  /* USE_IN_LIBIO */
64 \f
65 /* Macros for doing the actual output.  */
66
67 #define outchar(ch)                                                           \
68   do                                                                          \
69     {                                                                         \
70       register const int outc = (ch);                                         \
71       if (putc (outc, fp) == EOF)                                             \
72         return -1;                                                            \
73       ++done;                                                                 \
74     } while (0)
75
76 #define PRINT(ptr, len)                                                       \
77   do                                                                          \
78     {                                                                         \
79       register size_t outlen = (len);                                         \
80       if (len > 20)                                                           \
81         {                                                                     \
82           if (PUT (fp, ptr, outlen) != outlen)                                \
83             return -1;                                                        \
84           ptr += outlen;                                                      \
85           done += outlen;                                                     \
86         }                                                                     \
87       else                                                                    \
88         {                                                                     \
89           while (outlen-- > 0)                                                \
90             outchar (*ptr++);                                                 \
91         }                                                                     \
92     } while (0)
93
94 #define PADN(ch, len)                                                         \
95   do                                                                          \
96     {                                                                         \
97       if (PAD (fp, ch, len) != len)                                           \
98         return -1;                                                            \
99       done += len;                                                            \
100     }                                                                         \
101   while (0)
102 \f
103 /* We use the GNU MP library to handle large numbers.
104
105    An MP variable occupies a varying number of entries in its array.  We keep
106    track of this number for efficiency reasons.  Otherwise we would always
107    have to process the whole array.  */
108 #define MPN_VAR(name) mp_limb_t *name; mp_size_t name##size
109
110 #define MPN_ASSIGN(dst,src)                                                   \
111   memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
112 #define MPN_GE(u,v) \
113   (u##size > v##size || (u##size == v##size && __mpn_cmp (u, v, u##size) >= 0))
114
115 extern int __isinfl (long double), __isnanl (long double);
116
117 extern mp_size_t __mpn_extract_double (mp_ptr res_ptr, mp_size_t size,
118                                        int *expt, int *is_neg,
119                                        double value);
120 extern mp_size_t __mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size,
121                                             int *expt, int *is_neg,
122                                             long double value);
123 extern unsigned int __guess_grouping (unsigned int intdig_max,
124                                       const char *grouping, wchar_t sepchar);
125
126
127 static char *group_number (char *buf, char *bufend, unsigned int intdig_no,
128                            const char *grouping, wchar_t thousands_sep);
129
130
131 int
132 __printf_fp (FILE *fp,
133              const struct printf_info *info,
134              const void *const *args)
135 {
136   /* The floating-point value to output.  */
137   union
138     {
139       double dbl;
140       __long_double_t ldbl;
141     }
142   fpnum;
143
144   /* Locale-dependent representation of decimal point.  */
145   wchar_t decimal;
146
147   /* Locale-dependent thousands separator and grouping specification.  */
148   wchar_t thousands_sep;
149   const char *grouping;
150
151   /* "NaN" or "Inf" for the special cases.  */
152   const char *special = NULL;
153
154   /* We need just a few limbs for the input before shifting to the right
155      position.  */
156   mp_limb_t fp_input[(LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB];
157   /* We need to shift the contents of fp_input by this amount of bits.  */
158   int to_shift = 0;
159
160   /* The significant of the floting-point value in question  */
161   MPN_VAR(frac);
162   /* and the exponent.  */
163   int exponent;
164   /* Sign of the exponent.  */
165   int expsign = 0;
166   /* Sign of float number.  */
167   int is_neg = 0;
168
169   /* Scaling factor.  */
170   MPN_VAR(scale);
171
172   /* Temporary bignum value.  */
173   MPN_VAR(tmp);
174
175   /* Digit which is result of last hack_digit() call.  */
176   int digit;
177
178   /* The type of output format that will be used: 'e'/'E' or 'f'.  */
179   int type;
180
181   /* Counter for number of written characters.  */
182   int done = 0;
183
184   /* General helper (carry limb).  */
185   mp_limb_t cy;
186
187   char hack_digit (void)
188     {
189       mp_limb_t hi;
190
191       if (expsign != 0 && type == 'f' && exponent-- > 0)
192         hi = 0;
193       else if (scalesize == 0)
194         {
195           hi = frac[fracsize - 1];
196           cy = __mpn_mul_1 (frac, frac, fracsize - 1, 10);
197           frac[fracsize - 1] = cy;
198         }
199       else
200         {
201           if (fracsize < scalesize)
202             hi = 0;
203           else
204             {
205               hi = mpn_divmod (tmp, frac, fracsize, scale, scalesize);
206               tmp[fracsize - scalesize] = hi;
207               hi = tmp[0];
208
209               fracsize = scalesize;
210               while (fracsize != 0 && frac[fracsize - 1] == 0)
211                 --fracsize;
212               if (fracsize == 0)
213                 {
214                   /* We're not prepared for an mpn variable with zero
215                      limbs.  */
216                   fracsize = 1;
217                   return '0' + hi;
218                 }
219             }
220
221           cy = __mpn_mul_1 (frac, frac, fracsize, 10);
222           if (cy != 0)
223             frac[fracsize++] = cy;
224         }
225
226       return '0' + hi;
227     }
228
229
230   /* Figure out the decimal point character.  */
231   if (info->extra == 0)
232     {
233       if (mbtowc (&decimal, _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT),
234                   strlen (_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT))) <= 0)
235         decimal = (wchar_t) *_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
236     }
237   else
238     {
239       if (mbtowc (&decimal, _NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT),
240                   strlen (_NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT))) <= 0)
241         decimal = (wchar_t) *_NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT);
242     }
243   /* Give default value.  */
244   if (decimal == L'\0')
245     decimal = L'.';
246
247
248   if (info->group)
249     {
250       if (info->extra == 0)
251         grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
252       else
253         grouping = _NL_CURRENT (LC_MONETARY, MON_GROUPING);
254
255       if (*grouping <= 0 || *grouping == CHAR_MAX)
256         grouping = NULL;
257       else
258         {
259           /* Figure out the thousands seperator character.  */
260           if (info->extra == 0)
261             {
262               if (mbtowc (&thousands_sep, _NL_CURRENT (LC_NUMERIC,
263                                                        THOUSANDS_SEP),
264                           strlen (_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP)))
265                   <= 0)
266                 thousands_sep = (wchar_t) *_NL_CURRENT (LC_NUMERIC,
267                                                         THOUSANDS_SEP);
268             }
269           else
270             {
271               if (mbtowc (&thousands_sep, _NL_CURRENT (LC_MONETARY,
272                                                        MON_THOUSANDS_SEP),
273                           strlen (_NL_CURRENT (LC_MONETARY,
274                                                MON_THOUSANDS_SEP))) <= 0)
275                 thousands_sep = (wchar_t) *_NL_CURRENT (LC_MONETARY,
276                                                         MON_THOUSANDS_SEP);
277             }
278
279           if (thousands_sep == L'\0')
280             grouping = NULL;
281         }
282     }
283   else
284     grouping = NULL;
285
286   /* Fetch the argument value.  */
287   if (info->is_long_double && sizeof (long double) > sizeof (double))
288     {
289       fpnum.ldbl = *(const long double *) args[0];
290
291       /* Check for special values: not a number or infinity.  */
292       if (__isnanl (fpnum.ldbl))
293         {
294           special = "NaN";
295           is_neg = 0;
296         }
297       else if (__isinfl (fpnum.ldbl))
298         {
299           special = "Inf";
300           is_neg = fpnum.ldbl < 0;
301         }
302       else
303         {
304           fracsize = __mpn_extract_long_double (fp_input,
305                                                 (sizeof (fp_input) /
306                                                  sizeof (fp_input[0])),
307                                                 &exponent, &is_neg,
308                                                 fpnum.ldbl);
309           to_shift = 1 + fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
310         }
311     }
312   else
313     {
314       fpnum.dbl = *(const double *) args[0];
315
316       /* Check for special values: not a number or infinity.  */
317       if (__isnan (fpnum.dbl))
318         {
319           special = "NaN";
320           is_neg = 0;
321         }
322       else if (__isinf (fpnum.dbl))
323         {
324           special = "Inf";
325           is_neg = fpnum.dbl < 0;
326         }
327       else
328         {
329           fracsize = __mpn_extract_double (fp_input,
330                                            (sizeof (fp_input)
331                                             / sizeof (fp_input[0])),
332                                            &exponent, &is_neg, fpnum.dbl);
333           to_shift = 1 + fracsize * BITS_PER_MP_LIMB - DBL_MANT_DIG;
334         }
335     }
336
337   if (special)
338     {
339       int width = info->prec > info->width ? info->prec : info->width;
340
341       if (is_neg || info->showsign || info->space)
342         --width;
343       width -= 3;
344
345       if (!info->left && width > 0)
346         PADN (' ', width);
347
348       if (is_neg)
349         outchar ('-');
350       else if (info->showsign)
351         outchar ('+');
352       else if (info->space)
353         outchar (' ');
354
355       PRINT (special, 3);
356
357       if (info->left && width > 0)
358         PADN (' ', width);
359
360       return done;
361     }
362
363
364   /* We need three multiprecision variables.  Now that we have the exponent
365      of the number we can allocate the needed memory.  It would be more
366      efficient to use variables of the fixed maximum size but because this
367      would be really big it could lead to memory problems.  */
368   {
369     mp_size_t bignum_size = ((ABS (exponent) + BITS_PER_MP_LIMB - 1)
370                              / BITS_PER_MP_LIMB + 4) * sizeof (mp_limb_t);
371     frac = (mp_limb_t *) alloca (bignum_size);
372     tmp = (mp_limb_t *) alloca (bignum_size);
373     scale = (mp_limb_t *) alloca (bignum_size);
374   }
375
376   /* We now have to distinguish between numbers with positive and negative
377      exponents because the method used for the one is not applicable/efficient
378      for the other.  */
379   scalesize = 0;
380   if (exponent > 2)
381     {
382       /* |FP| >= 8.0.  */
383       int scaleexpo = 0;
384       int explog = LDBL_MAX_10_EXP_LOG;
385       int exp10 = 0;
386       const struct mp_power *tens = &_fpioconst_pow10[explog + 1];
387       int cnt_h, cnt_l, i;
388
389       if ((exponent + to_shift) % BITS_PER_MP_LIMB == 0)
390         {
391           MPN_COPY_DECR (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
392                          fp_input, fracsize);
393           fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
394         }
395       else
396         {
397           cy = __mpn_lshift (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
398                              fp_input, fracsize,
399                              (exponent + to_shift) % BITS_PER_MP_LIMB);
400           fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
401           if (cy)
402             frac[fracsize++] = cy;
403         }
404       MPN_ZERO (frac, (exponent + to_shift) / BITS_PER_MP_LIMB);
405
406       assert (tens > &_fpioconst_pow10[0]);
407       do
408         {
409           --tens;
410
411           /* The number of the product of two binary numbers with n and m
412              bits respectively has m+n or m+n-1 bits.   */
413           if (exponent >= scaleexpo + tens->p_expo - 1)
414             {
415               if (scalesize == 0)
416                 MPN_ASSIGN (tmp, tens->array);
417               else
418                 {
419                   cy = __mpn_mul (tmp, scale, scalesize,
420                                   &tens->array[_FPIO_CONST_OFFSET],
421                                   tens->arraysize - _FPIO_CONST_OFFSET);
422                   tmpsize = scalesize + tens->arraysize - _FPIO_CONST_OFFSET;
423                   if (cy == 0)
424                     --tmpsize;
425                 }
426
427               if (MPN_GE (frac, tmp))
428                 {
429                   int cnt;
430                   MPN_ASSIGN (scale, tmp);
431                   count_leading_zeros (cnt, scale[scalesize - 1]);
432                   scaleexpo = (scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
433                   exp10 |= 1 << explog;
434                 }
435             }
436           --explog;
437         }
438       while (tens > &_fpioconst_pow10[0]);
439       exponent = exp10;
440
441       /* Optimize number representations.  We want to represent the numbers
442          with the lowest number of bytes possible without losing any
443          bytes. Also the highest bit in the scaling factor has to be set
444          (this is a requirement of the MPN division routines).  */
445       if (scalesize > 0)
446         {
447           /* Determine minimum number of zero bits at the end of
448              both numbers.  */
449           for (i = 0; scale[i] == 0 && frac[i] == 0; i++)
450             ;
451
452           /* Determine number of bits the scaling factor is misplaced.  */
453           count_leading_zeros (cnt_h, scale[scalesize - 1]);
454
455           if (cnt_h == 0)
456             {
457               /* The highest bit of the scaling factor is already set.  So
458                  we only have to remove the trailing empty limbs.  */
459               if (i > 0)
460                 {
461                   MPN_COPY_INCR (scale, scale + i, scalesize - i);
462                   scalesize -= i;
463                   MPN_COPY_INCR (frac, frac + i, fracsize - i);
464                   fracsize -= i;
465                 }
466             }
467           else
468             {
469               if (scale[i] != 0)
470                 {
471                   count_trailing_zeros (cnt_l, scale[i]);
472                   if (frac[i] != 0)
473                     {
474                       int cnt_l2;
475                       count_trailing_zeros (cnt_l2, frac[i]);
476                       if (cnt_l2 < cnt_l)
477                         cnt_l = cnt_l2;
478                     }
479                 }
480               else
481                 count_trailing_zeros (cnt_l, frac[i]);
482
483               /* Now shift the numbers to their optimal position.  */
484               if (i == 0 && BITS_PER_MP_LIMB - cnt_h > cnt_l)
485                 {
486                   /* We cannot save any memory.  So just roll both numbers
487                      so that the scaling factor has its highest bit set.  */
488
489                   (void) __mpn_lshift (scale, scale, scalesize, cnt_h);
490                   cy = __mpn_lshift (frac, frac, fracsize, cnt_h);
491                   if (cy != 0)
492                     frac[fracsize++] = cy;
493                 }
494               else if (BITS_PER_MP_LIMB - cnt_h <= cnt_l)
495                 {
496                   /* We can save memory by removing the trailing zero limbs
497                      and by packing the non-zero limbs which gain another
498                      free one. */
499
500                   (void) __mpn_rshift (scale, scale + i, scalesize - i,
501                                        BITS_PER_MP_LIMB - cnt_h);
502                   scalesize -= i + 1;
503                   (void) __mpn_rshift (frac, frac + i, fracsize - i,
504                                        BITS_PER_MP_LIMB - cnt_h);
505                   fracsize -= frac[fracsize - i - 1] == 0 ? i + 1 : i;
506                 }
507               else
508                 {
509                   /* We can only save the memory of the limbs which are zero.
510                      The non-zero parts occupy the same number of limbs.  */
511
512                   (void) __mpn_rshift (scale, scale + (i - 1),
513                                        scalesize - (i - 1),
514                                        BITS_PER_MP_LIMB - cnt_h);
515                   scalesize -= i;
516                   (void) __mpn_rshift (frac, frac + (i - 1),
517                                        fracsize - (i - 1),
518                                        BITS_PER_MP_LIMB - cnt_h);
519                   fracsize -= frac[fracsize - (i - 1) - 1] == 0 ? i : i - 1;
520                 }
521             }
522         }
523     }
524   else if (exponent < 0)
525     {
526       /* |FP| < 1.0.  */
527       int exp10 = 0;
528       int explog = LDBL_MAX_10_EXP_LOG;
529       const struct mp_power *tens = &_fpioconst_pow10[explog + 1];
530       mp_size_t used_limbs = fracsize - 1;
531
532       /* Now shift the input value to its right place.  */
533       cy = __mpn_lshift (frac, fp_input, fracsize, to_shift);
534       frac[fracsize++] = cy;
535       assert (cy == 1 || (frac[fracsize - 2] == 0 && frac[0] == 0));
536
537       expsign = 1;
538       exponent = -exponent;
539
540       assert (tens != &_fpioconst_pow10[0]);
541       do
542         {
543           --tens;
544
545           if (exponent >= tens->m_expo)
546             {
547               int i, incr, cnt_h, cnt_l;
548               mp_limb_t topval[2];
549
550               /* The __mpn_mul function expects the first argument to be
551                  bigger than the second.  */
552               if (fracsize < tens->arraysize - _FPIO_CONST_OFFSET)
553                 cy = __mpn_mul (tmp, &tens->array[_FPIO_CONST_OFFSET],
554                                 tens->arraysize - _FPIO_CONST_OFFSET,
555                                 frac, fracsize);
556               else
557                 cy = __mpn_mul (tmp, frac, fracsize,
558                                 &tens->array[_FPIO_CONST_OFFSET],
559                                 tens->arraysize - _FPIO_CONST_OFFSET);
560               tmpsize = fracsize + tens->arraysize - _FPIO_CONST_OFFSET;
561               if (cy == 0)
562                 --tmpsize;
563
564               count_leading_zeros (cnt_h, tmp[tmpsize - 1]);
565               incr = (tmpsize - fracsize) * BITS_PER_MP_LIMB
566                      + BITS_PER_MP_LIMB - 1 - cnt_h;
567
568               assert (incr <= tens->p_expo);
569
570               /* If we increased the exponent by exactly 3 we have to test
571                  for overflow.  This is done by comparing with 10 shifted
572                  to the right position.  */
573               if (incr == exponent + 3)
574                 if (cnt_h <= BITS_PER_MP_LIMB - 4)
575                   {
576                     topval[0] = 0;
577                     topval[1]
578                       = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4 - cnt_h);
579                   }
580                 else
581                   {
582                     topval[0] = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4);
583                     topval[1] = 0;
584                     (void) __mpn_lshift (topval, topval, 2,
585                                          BITS_PER_MP_LIMB - cnt_h);
586                   }
587
588               /* We have to be careful when multiplying the last factor.
589                  If the result is greater than 1.0 be have to test it
590                  against 10.0.  If it is greater or equal to 10.0 the
591                  multiplication was not valid.  This is because we cannot
592                  determine the number of bits in the result in advance.  */
593               if (incr < exponent + 3
594                   || (incr == exponent + 3 &&
595                       (tmp[tmpsize - 1] < topval[1]
596                        || (tmp[tmpsize - 1] == topval[1]
597                            && tmp[tmpsize - 2] < topval[0]))))
598                 {
599                   /* The factor is right.  Adapt binary and decimal
600                      exponents.  */
601                   exponent -= incr;
602                   exp10 |= 1 << explog;
603
604                   /* If this factor yields a number greater or equal to
605                      1.0, we must not shift the non-fractional digits down. */
606                   if (exponent < 0)
607                     cnt_h += -exponent;
608
609                   /* Now we optimize the number representation.  */
610                   for (i = 0; tmp[i] == 0; ++i);
611                   if (cnt_h == BITS_PER_MP_LIMB - 1)
612                     {
613                       MPN_COPY (frac, tmp + i, tmpsize - i);
614                       fracsize = tmpsize - i;
615                     }
616                   else
617                     {
618                       count_trailing_zeros (cnt_l, tmp[i]);
619
620                       /* Now shift the numbers to their optimal position.  */
621                       if (i == 0 && BITS_PER_MP_LIMB - 1 - cnt_h > cnt_l)
622                         {
623                           /* We cannot save any memory.  Just roll the
624                              number so that the leading digit is in a
625                              seperate limb.  */
626
627                           cy = __mpn_lshift (frac, tmp, tmpsize, cnt_h + 1);
628                           fracsize = tmpsize + 1;
629                           frac[fracsize - 1] = cy;
630                         }
631                       else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
632                         {
633                           (void) __mpn_rshift (frac, tmp + i, tmpsize - i,
634                                                BITS_PER_MP_LIMB - 1 - cnt_h);
635                           fracsize = tmpsize - i;
636                         }
637                       else
638                         {
639                           /* We can only save the memory of the limbs which
640                              are zero.  The non-zero parts occupy the same
641                              number of limbs.  */
642
643                           (void) __mpn_rshift (frac, tmp + (i - 1),
644                                                tmpsize - (i - 1),
645                                                BITS_PER_MP_LIMB - 1 - cnt_h);
646                           fracsize = tmpsize - (i - 1);
647                         }
648                     }
649                   used_limbs = fracsize - 1;
650                 }
651             }
652           --explog;
653         }
654       while (tens != &_fpioconst_pow10[1] && exponent > 0);
655       /* All factors but 10^-1 are tested now.  */
656       if (exponent > 0)
657         {
658           int cnt_l;
659
660           cy = __mpn_mul_1 (tmp, frac, fracsize, 10);
661           tmpsize = fracsize;
662           assert (cy == 0 || tmp[tmpsize - 1] < 20);
663
664           count_trailing_zeros (cnt_l, tmp[0]);
665           if (cnt_l < MIN (4, exponent))
666             {
667               cy = __mpn_lshift (frac, tmp, tmpsize,
668                                  BITS_PER_MP_LIMB - MIN (4, exponent));
669               if (cy != 0)
670                 frac[tmpsize++] = cy;
671             }
672           else
673             (void) __mpn_rshift (frac, tmp, tmpsize, MIN (4, exponent));
674           fracsize = tmpsize;
675           exp10 |= 1;
676           assert (frac[fracsize - 1] < 10);
677         }
678       exponent = exp10;
679     }
680   else
681     {
682       /* This is a special case.  We don't need a factor because the
683          numbers are in the range of 0.0 <= fp < 8.0.  We simply
684          shift it to the right place and divide it by 1.0 to get the
685          leading digit.  (Of course this division is not really made.)  */
686       assert (0 <= exponent && exponent < 3 &&
687               exponent + to_shift < BITS_PER_MP_LIMB);
688
689       /* Now shift the input value to its right place.  */
690       cy = __mpn_lshift (frac, fp_input, fracsize, (exponent + to_shift));
691       frac[fracsize++] = cy;
692       exponent = 0;
693     }
694
695   {
696     int width = info->width;
697     char *buffer, *startp, *cp;
698     int chars_needed;
699     int expscale;
700     int intdig_max, intdig_no = 0;
701     int fracdig_min, fracdig_max, fracdig_no = 0;
702     int dig_max;
703     int significant;
704
705     if (tolower (info->spec) == 'e')
706       {
707         type = info->spec;
708         intdig_max = 1;
709         fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
710         chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
711         /*             d   .     ddd         e   +-  ddd  */
712         dig_max = INT_MAX;              /* Unlimited.  */
713         significant = 1;                /* Does not matter here.  */
714       }
715     else if (info->spec == 'f')
716       {
717         type = 'f';
718         fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
719         if (expsign == 0)
720           {
721             intdig_max = exponent + 1;
722             /* This can be really big!  */  /* XXX Maybe malloc if too big? */
723             chars_needed = exponent + 1 + 1 + fracdig_max;
724           }
725         else
726           {
727             intdig_max = 1;
728             chars_needed = 1 + 1 + fracdig_max;
729           }
730         dig_max = INT_MAX;              /* Unlimited.  */
731         significant = 1;                /* Does not matter here.  */
732       }
733     else
734       {
735         dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
736         if ((expsign == 0 && exponent >= dig_max)
737             || (expsign != 0 && exponent > 4))
738           {
739             type = isupper (info->spec) ? 'E' : 'e';
740             fracdig_max = dig_max - 1;
741             intdig_max = 1;
742             chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
743           }
744         else
745           {
746             type = 'f';
747             intdig_max = expsign == 0 ? exponent + 1 : 0;
748             fracdig_max = dig_max - intdig_max;
749             /* We need space for the significant digits and perhaps for
750                leading zeros when < 1.0.  Pessimistic guess: dig_max.  */
751             chars_needed = dig_max + dig_max + 1;
752           }
753         fracdig_min = info->alt ? fracdig_max : 0;
754         significant = 0;                /* We count significant digits.  */
755       }
756
757     if (grouping)
758       /* Guess the number of groups we will make, and thus how
759          many spaces we need for separator characters.  */
760       chars_needed += __guess_grouping (intdig_max, grouping, thousands_sep);
761
762     /* Allocate buffer for output.  We need two more because while rounding
763        it is possible that we need two more characters in front of all the
764        other output.  */
765     buffer = alloca (2 + chars_needed);
766     cp = startp = buffer + 2;   /* Let room for rounding.  */
767
768     /* Do the real work: put digits in allocated buffer.  */
769     if (expsign == 0 || type != 'f')
770       {
771         assert (expsign == 0 || intdig_max == 1);
772         while (intdig_no < intdig_max)
773           {
774             ++intdig_no;
775             *cp++ = hack_digit ();
776           }
777         significant = 1;
778         if (info->alt
779             || fracdig_min > 0
780             || (fracdig_max > 0 && (fracsize > 1 || frac[0] != 0)))
781           *cp++ = decimal;
782       }
783     else
784       {
785         /* |fp| < 1.0 and the selected type is 'f', so put "0."
786            in the buffer.  */
787         *cp++ = '0';
788         --exponent;
789         *cp++ = decimal;
790       }
791
792     /* Generate the needed number of fractional digits.  */
793     while (fracdig_no < fracdig_min
794            || (fracdig_no < fracdig_max && (fracsize > 1 || frac[0] != 0)))
795       {
796         ++fracdig_no;
797         *cp = hack_digit ();
798         if (*cp != '0')
799           significant = 1;
800         else if (significant == 0)
801           {
802             ++fracdig_max;
803             if (fracdig_min > 0)
804               ++fracdig_min;
805           }
806         ++cp;
807       }
808
809     /* Do rounding.  */
810     digit = hack_digit ();
811     if (digit > '4')
812       {
813         char *tp = cp;
814
815         if (digit == '5')
816           /* This is the critical case.  */
817           if (fracsize == 1 && frac[0] == 0)
818             /* Rest of the number is zero -> round to even.
819                (IEEE 754-1985 4.1 says this is the default rounding.)  */
820             if ((*(cp - 1) & 1) == 0)
821               goto do_expo;
822
823         if (fracdig_no > 0)
824           {
825             /* Process fractional digits.  Terminate if not rounded or
826                radix character is reached.  */
827             while (*--tp != decimal && *tp == '9')
828               *tp = '0';
829             if (*tp != decimal)
830               /* Round up.  */
831               (*tp)++;
832           }
833
834         if (fracdig_no == 0 || *tp == decimal)
835           {
836             /* Round the integer digits.  */
837             if (*(tp - 1) == decimal)
838               --tp;
839
840             while (--tp >= startp && *tp == '9')
841               *tp = '0';
842
843             if (tp >= startp)
844               /* Round up.  */
845               (*tp)++;
846             else
847               /* It is more citical.  All digits were 9's.  */
848               {
849                 if (type != 'f')
850                   {
851                     *startp = '1';
852                     exponent += expsign == 0 ? 1 : -1;
853                   }
854                 else if (intdig_no == dig_max)
855                   {
856                     /* This is the case where for type %g the number fits
857                        really in the range for %f output but after rounding
858                        the number of digits is too big.  */
859                     *--startp = decimal;
860                     *--startp = '1';
861
862                     if (info->alt || fracdig_no > 0)
863                       {
864                         /* Overwrite the old radix character.  */
865                         startp[intdig_no + 2] = '0';
866                         ++fracdig_no;
867                       }
868
869                     fracdig_no += intdig_no;
870                     intdig_no = 1;
871                     fracdig_max = intdig_max - intdig_no;
872                     ++exponent;
873                     /* Now we must print the exponent.  */
874                     type = isupper (info->spec) ? 'E' : 'e';
875                   }
876                 else
877                   {
878                     /* We can simply add another another digit before the
879                        radix.  */
880                     *--startp = '1';
881                     ++intdig_no;
882                   }
883
884                 /* While rounding the number of digits can change.
885                    If the number now exceeds the limits remove some
886                    fractional digits.  */
887                 if (intdig_no + fracdig_no > dig_max)
888                   {
889                     cp -= intdig_no + fracdig_no - dig_max;
890                     fracdig_no -= intdig_no + fracdig_no - dig_max;
891                   }
892               }
893           }
894       }
895
896   do_expo:
897     /* Now remove unnecessary '0' at the end of the string.  */
898     while (fracdig_no > fracdig_min && *(cp - 1) == '0')
899       {
900         --cp;
901         --fracdig_no;
902       }
903     /* If we eliminate all fractional digits we perhaps also can remove
904        the radix character.  */
905     if (fracdig_no == 0 && !info->alt && *(cp - 1) == decimal)
906       --cp;
907
908     if (grouping)
909       /* Add in separator characters, overwriting the same buffer.  */
910       cp = group_number (startp, cp, intdig_no, grouping, thousands_sep);
911
912     /* Write the exponent if it is needed.  */
913     if (type != 'f')
914       {
915         *cp++ = type;
916         *cp++ = expsign ? '-' : '+';
917
918         /* Find the magnitude of the exponent.  */
919         expscale = 10;
920         while (expscale <= exponent)
921           expscale *= 10;
922
923         if (exponent < 10)
924           /* Exponent always has at least two digits.  */
925           *cp++ = '0';
926         else
927           do
928             {
929               expscale /= 10;
930               *cp++ = '0' + (exponent / expscale);
931               exponent %= expscale;
932             }
933           while (expscale > 10);
934         *cp++ = '0' + exponent;
935       }
936
937     /* Compute number of characters which must be filled with the padding
938        character.  */
939     if (is_neg || info->showsign || info->space)
940       --width;
941     width -= cp - startp;
942
943     if (!info->left && info->pad != '0' && width > 0)
944       PADN (info->pad, width);
945
946     if (is_neg)
947       outchar ('-');
948     else if (info->showsign)
949       outchar ('+');
950     else if (info->space)
951       outchar (' ');
952
953     if (!info->left && info->pad == '0' && width > 0)
954       PADN ('0', width);
955
956     PRINT (startp, cp - startp);
957
958     if (info->left && width > 0)
959       PADN (info->pad, width);
960   }
961   return done;
962 }
963 \f
964 /* Return the number of extra grouping characters that will be inserted
965    into a number with INTDIG_MAX integer digits.  */
966
967 unsigned int
968 __guess_grouping (unsigned int intdig_max, const char *grouping,
969                   wchar_t sepchar)
970 {
971   unsigned int groups;
972
973   /* We treat all negative values like CHAR_MAX.  */
974
975   if (*grouping == CHAR_MAX || *grouping <= 0)
976     /* No grouping should be done.  */
977     return 0;
978
979   groups = 0;
980   while (intdig_max > (unsigned int) *grouping)
981     {
982       ++groups;
983       intdig_max -= *grouping++;
984
985       if (*grouping == CHAR_MAX || *grouping < 0)
986         /* No more grouping should be done.  */
987         break;
988       else if (*grouping == 0)
989         {
990           /* Same grouping repeats.  */
991           groups += intdig_max / grouping[-1];
992           break;
993         }
994     }
995
996   return groups;
997 }
998
999 /* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
1000    There is guaranteed enough space past BUFEND to extend it.
1001    Return the new end of buffer.  */
1002
1003 static char *
1004 group_number (char *buf, char *bufend, unsigned int intdig_no,
1005               const char *grouping, wchar_t thousands_sep)
1006 {
1007   unsigned int groups = __guess_grouping (intdig_no, grouping, thousands_sep);
1008   char *p;
1009
1010   if (groups == 0)
1011     return bufend;
1012
1013   /* Move the fractional part down.  */
1014   memmove (buf + intdig_no + groups, buf + intdig_no,
1015            bufend - (buf + intdig_no));
1016
1017   p = buf + intdig_no + groups - 1;
1018   do
1019     {
1020       unsigned int len = *grouping++;
1021       do
1022         *p-- = buf[--intdig_no];
1023       while (--len > 0);
1024       *p-- = thousands_sep;
1025
1026       if (*grouping == CHAR_MAX || *grouping < 0)
1027         /* No more grouping should be done.  */
1028         break;
1029       else if (*grouping == 0)
1030         /* Same grouping repeats.  */
1031         --grouping;
1032     } while (intdig_no > (unsigned int) *grouping);
1033
1034   /* Copy the remaining ungrouped digits.  */
1035   do
1036     *p-- = buf[--intdig_no];
1037   while (p > buf);
1038
1039   return bufend + groups;
1040 }