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